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
cf6912e3f07a77320d958965614854cca6cfd9d2
0
highlnd/camel-slack
package io.mikekennedy.camel; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.http.client.HttpClient; public class SlackEndpoint extends DefaultEndpoint { private static final transient Logger LOG = LoggerFactory.getLogger(SlackEndpoint.class); public SlackEndpoint(String uri, SlackComponent component) { super(uri, component); } @Override public Producer createProducer() throws Exception { SlackProducer producer = new SlackProducer(this); return producer; } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot consume slack messages from this endpoint: " + getEndpointUri()); } @Override public boolean isSingleton() { return false; } }
src/main/java/io/mikekennedy/camel/SlackEndpoint.java
package io.mikekennedy.camel; import org.apache.camel.Consumer; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.impl.DefaultEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SlackEndpoint extends DefaultEndpoint { private static final transient Logger LOG = LoggerFactory.getLogger(SlackEndpoint.class); public SlackEndpoint(String uri, SlackComponent component) { super(uri, component); } @Override public Producer createProducer() throws Exception { return null; } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot consume slack messages from this endpoint: " + getEndpointUri()); } @Override public boolean isSingleton() { return false; } }
Creates new producer and returns it
src/main/java/io/mikekennedy/camel/SlackEndpoint.java
Creates new producer and returns it
Java
apache-2.0
8e10afc0126984a4115f5dd1c5a8f8cccd9d4e94
0
apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc
package io.shardingjdbc.core.util; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; public final class InlineExpressionParserTest { @Test public void assertEvaluateForSimpleString() { List<String> expected = new InlineExpressionParser(" t_order_0, t_order_1 ").evaluate(); assertThat(expected.size(), is(2)); assertThat(expected, hasItems("t_order_0", "t_order_1")); } @Test public void assertEvaluateForNull() { List<String> expected = new InlineExpressionParser("t_order_${null}").evaluate(); assertThat(expected.size(), is(1)); assertThat(expected, hasItems("t_order_")); } @Test public void assertEvaluateForLiteral() { List<String> expected = new InlineExpressionParser("t_order_${'xx'}").evaluate(); assertThat(expected.size(), is(1)); assertThat(expected, hasItems("t_order_xx")); } @Test public void assertEvaluateForArray() { List<String> expected = new InlineExpressionParser("t_order_${[0, 1, 2]},t_order_item_${[0, 2]}").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_order_0", "t_order_1", "t_order_2", "t_order_item_0", "t_order_item_2")); } @Test public void assertEvaluateForRange() { List<String> expected = new InlineExpressionParser("t_order_${0..2},t_order_item_${0..1}").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_order_0", "t_order_1", "t_order_2", "t_order_item_0", "t_order_item_1")); } @Test public void assertEvaluateForComplex() { List<String> expected = new InlineExpressionParser("t_${['new','old']}_order_${1..2}, t_config").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_new_order_1", "t_new_order_2", "t_old_order_1", "t_old_order_2", "t_config")); } @Test public void assertEvaluateForCalculate() { List<String> expected = new InlineExpressionParser("t_${[\"new${1+2}\",'old']}_order_${1..2}").evaluate(); assertThat(expected.size(), is(4)); assertThat(expected, hasItems("t_new3_order_1", "t_new3_order_2", "t_old_order_1", "t_old_order_2")); } @Test public void assertEvaluateForLong() { StringBuilder expression = new StringBuilder(); for (int i = 0; i < 1024; i++) { expression.append("ds_"); expression.append(i/64); expression.append(".t_user_"); expression.append(i); if (i != 1023) { expression.append(","); } } List<String> expected = new InlineExpressionParser(expression.toString()).evaluate(); assertThat(expected.size(), is(1024)); assertThat(expected, hasItems("ds_0.t_user_0", "ds_15.t_user_1023")); } }
sharding-jdbc-core/src/test/java/io/shardingjdbc/core/util/InlineExpressionParserTest.java
package io.shardingjdbc.core.util; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsCollectionContaining.hasItems; import static org.junit.Assert.assertThat; public final class InlineExpressionParserTest { @Test public void assertEvaluateForSimpleString() { List<String> expected = new InlineExpressionParser(" t_order_0, t_order_1 ").evaluate(); assertThat(expected.size(), is(2)); assertThat(expected, hasItems("t_order_0", "t_order_1")); } @Test public void assertEvaluateForNull() { List<String> expected = new InlineExpressionParser("t_order_${null}").evaluate(); assertThat(expected.size(), is(1)); assertThat(expected, hasItems("t_order_")); } @Test public void assertEvaluateForLiteral() { List<String> expected = new InlineExpressionParser("t_order_${'xx'}").evaluate(); assertThat(expected.size(), is(1)); assertThat(expected, hasItems("t_order_xx")); } @Test public void assertEvaluateForArray() { List<String> expected = new InlineExpressionParser("t_order_${[0, 1, 2]},t_order_item_${[0, 2]}").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_order_0", "t_order_1", "t_order_2", "t_order_item_0", "t_order_item_2")); } @Test public void assertEvaluateForRange() { List<String> expected = new InlineExpressionParser("t_order_${0..2},t_order_item_${0..1}").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_order_0", "t_order_1", "t_order_2", "t_order_item_0", "t_order_item_1")); } @Test public void assertEvaluateForComplex() { List<String> expected = new InlineExpressionParser("t_${['new','old']}_order_${1..2}, t_config").evaluate(); assertThat(expected.size(), is(5)); assertThat(expected, hasItems("t_new_order_1", "t_new_order_2", "t_old_order_1", "t_old_order_2", "t_config")); } @Test public void assertEvaluateForCalculate() { List<String> expected = new InlineExpressionParser("t_${[\"new${1+2}\",'old']}_order_${1..2}").evaluate(); assertThat(expected.size(), is(4)); assertThat(expected, hasItems("t_new3_order_1", "t_new3_order_2", "t_old_order_1", "t_old_order_2")); } }
Refactor codes.
sharding-jdbc-core/src/test/java/io/shardingjdbc/core/util/InlineExpressionParserTest.java
Refactor codes.
Java
apache-2.0
237b44b623a19ecb39b4d1985558c93987535bcc
0
ahb0327/yobi,bloodybear/yona,ahb0327/yobi,bloodybear/yona,yona-projects/yona,ChangsungKim/TestRepository01,ihoneymon/yobi,violetag/demo,doortts/forked-for-history,Limseunghwan/oss,doortts/forked-for-history,naver/yobi,bloodybear/yona,oolso/yobi,yona-projects/yona,ChangsungKim/TestRepository01,ahb0327/yobi,Limseunghwan/oss,brainagenet/yobi,doortts/fork-yobi,oolso/yobi,naver/yobi,doortts/forked-for-history,brainagenet/yobi,ihoneymon/yobi,violetag/demo,ihoneymon/yobi,yona-projects/yona,oolso/yobi,doortts/fork-yobi,doortts/fork-yobi,yona-projects/yona,brainagenet/yobi,naver/yobi,Limseunghwan/oss,bloodybear/yona,doortts/fork-yobi
/** * @author Taehyun Park */ package controllers; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import play.Logger; import jxl.write.WriteException; import models.Assignee; import models.Attachment; import models.Issue; import models.IssueComment; import models.IssueLabel; import models.Project; import models.enumeration.Direction; import models.enumeration.Operation; import models.enumeration.Resource; import models.enumeration.State; import models.support.FinderTemplate; import models.support.OrderParams; import models.support.SearchCondition; import org.apache.tika.Tika; import play.cache.Cached; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import utils.AccessControl; import utils.Constants; import utils.HttpUtil; import utils.JodaDateUtil; import views.html.issue.editIssue; import views.html.issue.issue; import views.html.issue.issueList; import views.html.issue.newIssue; import views.html.issue.notExistingPage; import com.avaje.ebean.Page; public class IssueApp extends Controller { /** * ํŽ˜์ด์ง€ ์ฒ˜๋ฆฌ๋œ ์ด์Šˆ๋“ค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. * * @param projectName * ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ * @param state * ์ด์Šˆ ํ•ด๊ฒฐ ์ƒํƒœ * @return * @throws IOException * @throws WriteException */ public static Result issues(String userName, String projectName, String state, String format) throws WriteException, IOException { Project project = ProjectApp.getProject(userName, projectName); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return unauthorized(views.html.project.unauthorized.render(project)); } Form<SearchCondition> issueParamForm = new Form<SearchCondition>(SearchCondition.class); SearchCondition issueParam = issueParamForm.bindFromRequest().get(); OrderParams orderParams = new OrderParams().add(issueParam.sortBy, Direction.getValue(issueParam.orderBy)); issueParam.state = state; String[] labelIds = request().queryString().get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { issueParam.labelIds.add(Long.valueOf(labelId)); } } if (format.equals("xls")) { return issuesAsExcel(issueParam, orderParams, project, state); } else { Page<Issue> issues = FinderTemplate.getPage(orderParams, issueParam.asSearchParam(project), Issue.finder, Issue.ISSUE_COUNT_PER_PAGE, issueParam.pageNum); return ok(issueList.render("title.issueList", issues, issueParam, project)); } } public static Result issuesAsExcel(SearchCondition issueParam, OrderParams orderParams, Project project, String state) throws WriteException, IOException, UnsupportedEncodingException { List<Issue> issues = FinderTemplate.findBy(orderParams, issueParam.asSearchParam(project), Issue.finder); File excelFile = Issue.excelSave(issues, project.name + "_" + state + "_filter_" + issueParam.filter + "_milestone_" + issueParam.milestone); String filename = HttpUtil.encodeContentDisposition(excelFile.getName()); response().setHeader("Content-Length", Long.toString(excelFile.length())); response().setHeader("Content-Type", new Tika().detect(excelFile)); response().setHeader("Content-Disposition", "attachment; " + filename); return ok(excelFile); } public static Result issue(String userName, String projectName, Long issueId) { Project project = ProjectApp.getProject(userName, projectName); Issue issueInfo = Issue.findById(issueId); if (issueInfo == null) { return ok(notExistingPage.render("title.post.notExistingPage", project)); } else { for (IssueLabel label: issueInfo.labels) { label.refresh(); } Form<IssueComment> commentForm = new Form<IssueComment>(IssueComment.class); Issue targetIssue = Issue.findById(issueId); Form<Issue> editForm = new Form<Issue>(Issue.class).fill(targetIssue); return ok(issue.render("title.issueDetail", issueInfo, editForm, commentForm, project)); } } public static Result newIssueForm(String userName, String projectName) { Project project = ProjectApp.getProject(userName, projectName); if (UserApp.currentUser() == UserApp.anonymous) { return unauthorized(views.html.project.unauthorized.render(project)); } return ok(newIssue.render("title.newIssue", new Form<Issue>(Issue.class), project)); } public static Result newIssue(String ownerName, String projectName) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); Project project = ProjectApp.getProject(ownerName, projectName); if (issueForm.hasErrors()) { return badRequest(newIssue.render(issueForm.errors().toString(), issueForm, project)); } else { Issue newIssue = issueForm.get(); newIssue.date = JodaDateUtil.now(); newIssue.authorId = UserApp.currentUser().id; newIssue.authorLoginId = UserApp.currentUser().loginId; newIssue.authorName = UserApp.currentUser().name; newIssue.project = project; newIssue.state = State.OPEN; if (newIssue.assignee.user.id != null) { newIssue.assignee = Assignee.add(newIssue.assignee.user.id, project.id); } else { newIssue.assignee = null; } String[] labelIds = request().body().asMultipartFormData().asFormUrlEncoded() .get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { newIssue.labels.add(IssueLabel.findById(Long.parseLong(labelId))); } } Long issueId = Issue.create(newIssue); // Attach all of the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, project.id, Resource.ISSUE_POST, issueId); } return redirect(routes.IssueApp.issues(project.owner, project.name, State.ALL.state(), "html")); } public static Result editIssueForm(String userName, String projectName, Long id) { Issue targetIssue = Issue.findById(id); Form<Issue> editForm = new Form<Issue>(Issue.class).fill(targetIssue); Project project = ProjectApp.getProject(userName, projectName); if (!AccessControl.isAllowed(UserApp.currentUser(), targetIssue.asResource(), Operation.UPDATE)) { return unauthorized(views.html.project.unauthorized.render(project)); } return ok(editIssue.render("title.editIssue", editForm, targetIssue, project)); } public static Result editIssue(String userName, String projectName, Long id) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); if (issueForm.hasErrors()) { return badRequest(issueForm.errors().toString()); } Issue issue = issueForm.get(); Issue originalIssue = Issue.findById(id); issue.id = id; issue.date = originalIssue.date; issue.authorId = originalIssue.authorId; issue.authorLoginId = originalIssue.authorLoginId; issue.authorName = originalIssue.authorName; issue.project = originalIssue.project; if (issue.assignee.user.id != null) { issue.assignee = Assignee.add(issue.assignee.user.id, originalIssue.project.id); } else { issue.assignee = null; } String[] labelIds = request().body().asMultipartFormData().asFormUrlEncoded() .get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { issue.labels.add(IssueLabel.findById(Long.parseLong(labelId))); } } Issue.edit(issue); // Attach the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, originalIssue.project.id, Resource.ISSUE_POST, id); return redirect(routes.IssueApp.issues(originalIssue.project.owner, originalIssue.project.name, State.ALL.name(), "html")); } public static Result deleteIssue(String userName, String projectName, Long issueId) { Project project = ProjectApp.getProject(userName, projectName); Issue.delete(issueId); Attachment.deleteAll(Resource.ISSUE_POST, issueId); return redirect(routes.IssueApp.issues(project.owner, project.name, State.ALL.state(), "html")); } public static Result newComment(String userName, String projectName, Long issueId) throws IOException { Form<IssueComment> commentForm = new Form<IssueComment>(IssueComment.class) .bindFromRequest(); Project project = ProjectApp.getProject(userName, projectName); if (commentForm.hasErrors()) { flash(Constants.WARNING, "board.comment.empty"); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } else { IssueComment comment = commentForm.get(); comment.issue = Issue.findById(issueId); comment.authorId = UserApp.currentUser().id; comment.authorLoginId = UserApp.currentUser().loginId; comment.authorName = UserApp.currentUser().name; Long commentId = IssueComment.create(comment); Issue.updateNumOfComments(issueId); // Attach all of the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, project.id, Resource.ISSUE_COMMENT, commentId); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } } public static Result deleteComment(String userName, String projectName, Long issueId, Long commentId) { Project project = ProjectApp.getProject(userName, projectName); IssueComment.delete(commentId); Issue.updateNumOfComments(issueId); Attachment.deleteAll(Resource.ISSUE_COMMENT, commentId); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } }
app/controllers/IssueApp.java
/** * @author Taehyun Park */ package controllers; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import play.Logger; import jxl.write.WriteException; import models.Assignee; import models.Attachment; import models.Issue; import models.IssueComment; import models.IssueLabel; import models.Project; import models.enumeration.Direction; import models.enumeration.Operation; import models.enumeration.Resource; import models.enumeration.State; import models.support.FinderTemplate; import models.support.OrderParams; import models.support.SearchCondition; import org.apache.tika.Tika; import play.cache.Cached; import play.data.Form; import play.mvc.Controller; import play.mvc.Result; import utils.AccessControl; import utils.Constants; import utils.HttpUtil; import utils.JodaDateUtil; import views.html.issue.editIssue; import views.html.issue.issue; import views.html.issue.issueList; import views.html.issue.newIssue; import views.html.issue.notExistingPage; import com.avaje.ebean.Page; public class IssueApp extends Controller { /** * ํŽ˜์ด์ง€ ์ฒ˜๋ฆฌ๋œ ์ด์Šˆ๋“ค์˜ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋ณด์—ฌ์ค€๋‹ค. * * @param projectName * ํ”„๋กœ์ ํŠธ ์ด๋ฆ„ * @param state * ์ด์Šˆ ํ•ด๊ฒฐ ์ƒํƒœ * @return * @throws IOException * @throws WriteException */ @Cached(key = "issues") public static Result issues(String userName, String projectName, String state, String format) throws WriteException, IOException { Project project = ProjectApp.getProject(userName, projectName); if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return unauthorized(views.html.project.unauthorized.render(project)); } Form<SearchCondition> issueParamForm = new Form<SearchCondition>(SearchCondition.class); SearchCondition issueParam = issueParamForm.bindFromRequest().get(); OrderParams orderParams = new OrderParams().add(issueParam.sortBy, Direction.getValue(issueParam.orderBy)); issueParam.state = state; String[] labelIds = request().queryString().get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { issueParam.labelIds.add(Long.valueOf(labelId)); } } if (format.equals("xls")) { return issuesAsExcel(issueParam, orderParams, project, state); } else { Page<Issue> issues = FinderTemplate.getPage(orderParams, issueParam.asSearchParam(project), Issue.finder, Issue.ISSUE_COUNT_PER_PAGE, issueParam.pageNum); return ok(issueList.render("title.issueList", issues, issueParam, project)); } } public static Result issuesAsExcel(SearchCondition issueParam, OrderParams orderParams, Project project, String state) throws WriteException, IOException, UnsupportedEncodingException { List<Issue> issues = FinderTemplate.findBy(orderParams, issueParam.asSearchParam(project), Issue.finder); File excelFile = Issue.excelSave(issues, project.name + "_" + state + "_filter_" + issueParam.filter + "_milestone_" + issueParam.milestone); String filename = HttpUtil.encodeContentDisposition(excelFile.getName()); response().setHeader("Content-Length", Long.toString(excelFile.length())); response().setHeader("Content-Type", new Tika().detect(excelFile)); response().setHeader("Content-Disposition", "attachment; " + filename); return ok(excelFile); } @Cached(key = "issue") public static Result issue(String userName, String projectName, Long issueId) { Project project = ProjectApp.getProject(userName, projectName); Issue issueInfo = Issue.findById(issueId); if (issueInfo == null) { return ok(notExistingPage.render("title.post.notExistingPage", project)); } else { for (IssueLabel label: issueInfo.labels) { label.refresh(); } Form<IssueComment> commentForm = new Form<IssueComment>(IssueComment.class); Issue targetIssue = Issue.findById(issueId); Form<Issue> editForm = new Form<Issue>(Issue.class).fill(targetIssue); return ok(issue.render("title.issueDetail", issueInfo, editForm, commentForm, project)); } } public static Result newIssueForm(String userName, String projectName) { Project project = ProjectApp.getProject(userName, projectName); if (UserApp.currentUser() == UserApp.anonymous) { return unauthorized(views.html.project.unauthorized.render(project)); } return ok(newIssue.render("title.newIssue", new Form<Issue>(Issue.class), project)); } public static Result newIssue(String ownerName, String projectName) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); Project project = ProjectApp.getProject(ownerName, projectName); if (issueForm.hasErrors()) { return badRequest(newIssue.render(issueForm.errors().toString(), issueForm, project)); } else { Issue newIssue = issueForm.get(); newIssue.date = JodaDateUtil.now(); newIssue.authorId = UserApp.currentUser().id; newIssue.authorLoginId = UserApp.currentUser().loginId; newIssue.authorName = UserApp.currentUser().name; newIssue.project = project; newIssue.state = State.OPEN; if (newIssue.assignee.user.id != null) { newIssue.assignee = Assignee.add(newIssue.assignee.user.id, project.id); } else { newIssue.assignee = null; } String[] labelIds = request().body().asMultipartFormData().asFormUrlEncoded() .get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { newIssue.labels.add(IssueLabel.findById(Long.parseLong(labelId))); } } Long issueId = Issue.create(newIssue); // Attach all of the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, project.id, Resource.ISSUE_POST, issueId); } return redirect(routes.IssueApp.issues(project.owner, project.name, State.ALL.state(), "html")); } public static Result editIssueForm(String userName, String projectName, Long id) { Issue targetIssue = Issue.findById(id); Form<Issue> editForm = new Form<Issue>(Issue.class).fill(targetIssue); Project project = ProjectApp.getProject(userName, projectName); if (!AccessControl.isAllowed(UserApp.currentUser(), targetIssue.asResource(), Operation.UPDATE)) { return unauthorized(views.html.project.unauthorized.render(project)); } return ok(editIssue.render("title.editIssue", editForm, targetIssue, project)); } public static Result editIssue(String userName, String projectName, Long id) throws IOException { Form<Issue> issueForm = new Form<Issue>(Issue.class).bindFromRequest(); if (issueForm.hasErrors()) { return badRequest(issueForm.errors().toString()); } Issue issue = issueForm.get(); Issue originalIssue = Issue.findById(id); issue.id = id; issue.date = originalIssue.date; issue.authorId = originalIssue.authorId; issue.authorLoginId = originalIssue.authorLoginId; issue.authorName = originalIssue.authorName; issue.project = originalIssue.project; if (issue.assignee.user.id != null) { issue.assignee = Assignee.add(issue.assignee.user.id, originalIssue.project.id); } else { issue.assignee = null; } String[] labelIds = request().body().asMultipartFormData().asFormUrlEncoded() .get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { issue.labels.add(IssueLabel.findById(Long.parseLong(labelId))); } } Issue.edit(issue); // Attach the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, originalIssue.project.id, Resource.ISSUE_POST, id); return redirect(routes.IssueApp.issues(originalIssue.project.owner, originalIssue.project.name, State.ALL.name(), "html")); } public static Result deleteIssue(String userName, String projectName, Long issueId) { Project project = ProjectApp.getProject(userName, projectName); Issue.delete(issueId); Attachment.deleteAll(Resource.ISSUE_POST, issueId); return redirect(routes.IssueApp.issues(project.owner, project.name, State.ALL.state(), "html")); } public static Result newComment(String userName, String projectName, Long issueId) throws IOException { Form<IssueComment> commentForm = new Form<IssueComment>(IssueComment.class) .bindFromRequest(); Project project = ProjectApp.getProject(userName, projectName); if (commentForm.hasErrors()) { flash(Constants.WARNING, "board.comment.empty"); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } else { IssueComment comment = commentForm.get(); comment.issue = Issue.findById(issueId); comment.authorId = UserApp.currentUser().id; comment.authorLoginId = UserApp.currentUser().loginId; comment.authorName = UserApp.currentUser().name; Long commentId = IssueComment.create(comment); Issue.updateNumOfComments(issueId); // Attach all of the files in the current user's temporary storage. Attachment.attachFiles(UserApp.currentUser().id, project.id, Resource.ISSUE_COMMENT, commentId); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } } public static Result deleteComment(String userName, String projectName, Long issueId, Long commentId) { Project project = ProjectApp.getProject(userName, projectName); IssueComment.delete(commentId); Issue.updateNumOfComments(issueId); Attachment.deleteAll(Resource.ISSUE_COMMENT, commentId); return redirect(routes.IssueApp.issue(project.owner, project.name, issueId)); } }
issue: Remove caching which doesn't work correctly.
app/controllers/IssueApp.java
issue: Remove caching which doesn't work correctly.
Java
apache-2.0
4457abd65bfcb088fc4f6c2700d72da9a623db40
0
googleapis/java-automl,googleapis/java-automl,googleapis/java-automl
/* * Copyright 2020 Google LLC * * 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.beta.automl; // [START automl_get_model_beta] // [START automl_tables_get_model] import com.google.cloud.automl.v1beta1.AutoMlClient; import com.google.cloud.automl.v1beta1.Model; import com.google.cloud.automl.v1beta1.ModelName; import io.grpc.StatusRuntimeException; import java.io.IOException; class GetModel { static void getModel() throws IOException, StatusRuntimeException { // TODO(developer): Replace these variables before running the sample. String projectId = "YOUR_PROJECT_ID"; String modelId = "YOUR_MODEL_ID"; getModel(projectId, modelId); } // Get a model static void getModel(String projectId, String modelId) throws IOException, StatusRuntimeException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (AutoMlClient client = AutoMlClient.create()) { // Get the full path of the model. ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); Model model = client.getModel(modelFullId); // Display the model information. System.out.format("Model name: %s%n", model.getName()); // To get the model id, you have to parse it out of the `name` field. As models Ids are // required for other methods. // Name Format: `projects/{project_id}/locations/{location_id}/models/{model_id}` String[] names = model.getName().split("/"); String retrievedModelId = names[names.length - 1]; System.out.format("Model id: %s%n", retrievedModelId); System.out.format("Model display name: %s%n", model.getDisplayName()); System.out.println("Model create time:"); System.out.format("\tseconds: %s%n", model.getCreateTime().getSeconds()); System.out.format("\tnanos: %s%n", model.getCreateTime().getNanos()); System.out.format("Model deployment state: %s%n", model.getDeploymentState()); } } } // [END automl_tables_get_model] // [END automl_get_model_beta]
samples/snippets/src/main/java/com/beta/automl/GetModel.java
/* * Copyright 2020 Google LLC * * 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.beta.automl; // [START automl_get_model_beta] import com.google.cloud.automl.v1beta1.AutoMlClient; import com.google.cloud.automl.v1beta1.Model; import com.google.cloud.automl.v1beta1.ModelName; import io.grpc.StatusRuntimeException; import java.io.IOException; class GetModel { static void getModel() throws IOException, StatusRuntimeException { // TODO(developer): Replace these variables before running the sample. String projectId = "YOUR_PROJECT_ID"; String modelId = "YOUR_MODEL_ID"; getModel(projectId, modelId); } // Get a model static void getModel(String projectId, String modelId) throws IOException, StatusRuntimeException { // Initialize client that will be used to send requests. This client only needs to be created // once, and can be reused for multiple requests. After completing all of your requests, call // the "close" method on the client to safely clean up any remaining background resources. try (AutoMlClient client = AutoMlClient.create()) { // Get the full path of the model. ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId); Model model = client.getModel(modelFullId); // Display the model information. System.out.format("Model name: %s%n", model.getName()); // To get the model id, you have to parse it out of the `name` field. As models Ids are // required for other methods. // Name Format: `projects/{project_id}/locations/{location_id}/models/{model_id}` String[] names = model.getName().split("/"); String retrievedModelId = names[names.length - 1]; System.out.format("Model id: %s%n", retrievedModelId); System.out.format("Model display name: %s%n", model.getDisplayName()); System.out.println("Model create time:"); System.out.format("\tseconds: %s%n", model.getCreateTime().getSeconds()); System.out.format("\tnanos: %s%n", model.getCreateTime().getNanos()); System.out.format("Model deployment state: %s%n", model.getDeploymentState()); } } } // [END automl_get_model_beta]
add region tags (#361)
samples/snippets/src/main/java/com/beta/automl/GetModel.java
add region tags (#361)
Java
apache-2.0
896a4b57543ee3d3e6b690f32bcde4da654bb923
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.ui.layout.impl; import com.intellij.execution.ui.layout.*; import com.intellij.execution.ui.layout.actions.CloseViewAction; import com.intellij.execution.ui.layout.actions.MinimizeViewAction; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.MutualMap; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.tabs.*; import com.intellij.ui.tabs.newImpl.JBEditorTabs; import com.intellij.ui.tabs.newImpl.TabLabel; import com.intellij.ui.tabs.newImpl.singleRow.ScrollableSingleRowLayout; import com.intellij.ui.tabs.newImpl.singleRow.SingleRowLayout; import com.intellij.util.SmartList; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashSet; import java.util.List; import java.util.Set; public class GridCellImpl implements GridCell { private final GridImpl myContainer; private final MutualMap<Content, TabInfo> myContents = new MutualMap<>(true); private final Set<Content> myMinimizedContents = new HashSet<>(); private final JBTabs myTabs; private final GridImpl.Placeholder myPlaceholder; private final PlaceInGrid myPlaceInGrid; private final ViewContextEx myContext; private JBPopup myPopup; public GridCellImpl(ViewContextEx context, @NotNull GridImpl container, GridImpl.Placeholder placeholder, PlaceInGrid placeInGrid) { myContext = context; myContainer = container; myPlaceInGrid = placeInGrid; myPlaceholder = placeholder; myPlaceholder.setContentProvider(() -> getContents()); myTabs = JBTabsFactory.getUseNewTabs() ? new GridCellTabs(context, container) : new GridCellTabsOld(context, container); myTabs.setDataProvider(new DataProvider() { @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (ViewContext.CONTENT_KEY.is(dataId)) { TabInfo target = myTabs.getTargetInfo(); if (target != null) { return new Content[]{getContentFor(target)}; } } else if (ViewContext.CONTEXT_KEY.is(dataId)) { return myContext; } return null; } }); myTabs.getPresentation().setUiDecorator(new UiDecorator() { @Override @NotNull public UiDecoration getDecoration() { return new UiDecoration(null, JBTabsFactory.getUseNewTabs()? JBUI.insets(6, 8, 6, 9) : new Insets(1, -1, 1, -1)); } }).setSideComponentVertical(!context.getLayoutSettings().isToolbarHorizontal()) .setStealthTabMode(!JBTabsFactory.getUseNewTabs()).setFocusCycle(false).setPaintFocus(true) .setTabDraggingEnabled(context.isMoveToGridActionEnabled()).setSideComponentOnTabs(false); myTabs.addTabMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (UIUtil.isCloseClick(e)) { // see RunnerContentUi tabMouseListener as well closeOrMinimize(e); } } }); rebuildPopupGroup(); myTabs.addListener(new TabsListener() { @Override public void beforeSelectionChanged(TabInfo oldSelection, TabInfo newSelection) { if (oldSelection != null && myContext.isStateBeingRestored()) { saveUiState(); } } @Override public void selectionChanged(final TabInfo oldSelection, final TabInfo newSelection) { updateSelection(myTabs.getComponent().isShowing()); if (!myTabs.getComponent().isShowing()) return; if (newSelection != null) { newSelection.stopAlerting(); } } }); } public void rebuildPopupGroup() { myTabs.setPopupGroup(myContext.getCellPopupGroup(ViewContext.CELL_POPUP_PLACE), ViewContext.CELL_POPUP_PLACE, true); } public PlaceInGrid getPlaceInGrid() { return myPlaceInGrid; } void add(final Content content) { if (myContents.containsKey(content)) return; myContents.put(content, null); revalidateCell(() -> myTabs.addTab(createTabInfoFor(content))); updateSelection(myTabs.getComponent().getRootPane() != null); } void remove(Content content) { if (!myContents.containsKey(content)) return; final TabInfo info = getTabFor(content); myContents.remove(content); revalidateCell(() -> myTabs.removeTab(info)); updateSelection(myTabs.getComponent().getRootPane() != null); } private void revalidateCell(Runnable contentAction) { if (myContents.size() == 0) { myPlaceholder.removeAll(); myTabs.removeAllTabs(); if (myPopup != null) { myPopup.cancel(); myPopup = null; } } else { if (myPlaceholder.isNull()) { myPlaceholder.setContent(myTabs.getComponent()); } contentAction.run(); } restoreProportions(); myTabs.getComponent().revalidate(); myTabs.getComponent().repaint(); } void setHideTabs(boolean hide) { myTabs.getPresentation().setHideTabs(hide); } private TabInfo createTabInfoFor(Content content) { final TabInfo tabInfo = updatePresentation(new TabInfo(new ProviderWrapper(content, myContext)), content) .setObject(content) .setPreferredFocusableComponent(content.getPreferredFocusableComponent()) .setActionsContextComponent(content.getActionsContextComponent()); myContents.remove(content); myContents.put(content, tabInfo); ActionGroup group = (ActionGroup)myContext.getActionManager().getAction(RunnerContentUi.VIEW_TOOLBAR); tabInfo.setTabLabelActions(group, ViewContext.CELL_TOOLBAR_PLACE); tabInfo.setDragOutDelegate(((RunnerContentUi)myContext).myDragOutDelegate); return tabInfo; } @Nullable private static TabInfo updatePresentation(TabInfo info, Content content) { if (info == null) { return null; } return info. setIcon(content.getIcon()). setText(content.getDisplayName()). setTooltipText(content.getDescription()). setActionsContextComponent(content.getActionsContextComponent()). setActions(content.getActions(), content.getPlace()); } public ActionCallback select(final Content content, final boolean requestFocus) { final TabInfo tabInfo = myContents.getValue(content); return tabInfo != null ? myTabs.select(tabInfo, requestFocus) : ActionCallback.DONE; } public void processAlert(final Content content, final boolean activate) { if (myMinimizedContents.contains(content)) { content.fireAlert(); } TabInfo tab = getTabFor(content); if (tab == null) return; if (myTabs.getSelectedInfo() != tab) { if (activate) { tab.fireAlert(); } else { tab.stopAlerting(); } } } public void updateTabPresentation(Content content) { updatePresentation(myTabs.findInfo(content), content); } public boolean isMinimized(Content content) { return myMinimizedContents.contains(content); } public boolean contains(Component c) { return myTabs.getComponent().isAncestorOf(c); } private static class ProviderWrapper extends NonOpaquePanel implements DataProvider { Content myContent; ViewContext myContext; private ProviderWrapper(final Content content, final ViewContext context) { myContent = content; myContext = context; setLayout(new BorderLayout()); add(content.getComponent(), BorderLayout.CENTER); } @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (ViewContext.CONTENT_KEY.is(dataId)) { return new Content[]{myContent}; } else if (ViewContext.CONTEXT_KEY.is(dataId)) { return myContext; } return null; } } @Nullable TabInfo getTabFor(Content content) { return myContents.getValue(content); } @NotNull private Content getContentFor(TabInfo tab) { return myContents.getKey(tab); } public void setToolbarHorizontal(final boolean horizontal) { myTabs.getPresentation().setSideComponentVertical(!horizontal); } public void setToolbarBefore(final boolean before) { myTabs.getPresentation().setSideComponentBefore(before); } public ActionCallback restoreLastUiState() { final ActionCallback result = new ActionCallback(); restoreProportions(); final Content[] contents = getContents(); final List<Content> toMinimize = new SmartList<>(); int window = 0; for (final Content each : contents) { final View view = myContainer.getStateFor(each); if (view.isMinimizedInGrid()) { toMinimize.add(each); } window = view.getWindow(); } minimize(toMinimize.toArray(new Content[0])); final Tab tab = myContainer.getTab(); final boolean detached = (tab != null && tab.isDetached(myPlaceInGrid)) || window != myContext.getWindow(); if (detached && contents.length > 0) { if (tab != null) { tab.setDetached(myPlaceInGrid, false); } myContext.detachTo(window, this).notifyWhenDone(result); } else { result.setDone(); } return result; } Content[] getContents() { return myContents.getKeys().toArray(new Content[myContents.size()]); } @Override public int getContentCount() { return myContents.size(); } public void saveUiState() { saveProportions(); for (Content each : myContents.getKeys()) { saveState(each, false); } for (Content each : myMinimizedContents) { saveState(each, true); } final DimensionService service = DimensionService.getInstance(); final Dimension size = myContext.getContentManager().getComponent().getSize(); service.setSize(getDimensionKey(), size, myContext.getProject()); if (myContext.getWindow() != 0) { final Window frame = SwingUtilities.getWindowAncestor(myPlaceholder); if (frame != null) { service.setLocation(getDimensionKey(), frame.getLocationOnScreen()); } } } public void saveProportions() { myContainer.saveSplitterProportions(myPlaceInGrid); } private void saveState(Content content, boolean minimized) { View state = myContext.getStateFor(content); state.setMinimizedInGrid(minimized); state.setPlaceInGrid(myPlaceInGrid); final List<Content> contents = myContainer.getContents(); final Tab tab = myContainer.getTabIndex(); if (minimized && contents.size() == 1 && contents.get(0).equals(content)) { state.setTabIndex(-1); if (tab instanceof TabImpl) { ((TabImpl)tab).setIndex(-1); } } state.assignTab(tab); state.setWindow(myContext.getWindow()); } public void restoreProportions() { myContainer.restoreLastSplitterProportions(myPlaceInGrid); } public void updateSelection(final boolean isShowing) { ContentManager contentManager = myContext.getContentManager(); if (contentManager.isDisposed()) return; for (Content each : myContents.getKeys()) { final TabInfo eachTab = getTabFor(each); boolean isSelected = eachTab != null && myTabs.getSelectedInfo() == eachTab; if (isSelected && isShowing) { contentManager.addSelectedContent(each); } else { contentManager.removeFromSelection(each); } } for (Content each : myMinimizedContents) { contentManager.removeFromSelection(each); } } public void minimize(Content[] contents) { if (contents.length == 0) return; myContext.saveUiState(); for (final Content each : contents) { myMinimizedContents.add(each); remove(each); saveState(each, true); boolean isShowing = myTabs.getComponent().getRootPane() != null; myContainer.minimize(each, new CellTransform.Restore() { @Override public ActionCallback restoreInGrid() { return restore(each); } }); updateSelection(isShowing); } } @Nullable public Point getLocation() { return DimensionService.getInstance().getLocation(getDimensionKey(), myContext.getProject()); } @Nullable public Dimension getSize() { return DimensionService.getInstance().getSize(getDimensionKey(), myContext.getProject()); } private String getDimensionKey() { return "GridCell.Tab." + myContainer.getTab().getIndex() + "." + myPlaceInGrid.name(); } public boolean isValidForCalculateProportions() { return getContentCount() > 0; } @Override public void minimize(Content content) { minimize(new Content[]{content}); } public void closeOrMinimize(MouseEvent e) { TabInfo tabInfo = myTabs.findInfo(e); if (tabInfo == null) return; Content content = getContentFor(tabInfo); if (CloseViewAction.isEnabled(new Content[]{content})) { CloseViewAction.perform(myContext, content); } else if (MinimizeViewAction.isEnabled(myContext, getContents(), ViewContext.CELL_TOOLBAR_PLACE)) { minimize(content); } } ActionCallback restore(Content content) { myMinimizedContents.remove(content); return ActionCallback.DONE; } private static class GridCellTabs extends JBEditorTabs { private final ViewContextEx myContext; @Override protected JBTabPainter createTabPainter() { return JBTabPainter.getDEBUGGER(); } private GridCellTabs(ViewContextEx context, GridImpl container) { super(context.getProject(), context.getActionManager(), context.getFocusManager(), container); myContext = context; } @Override public boolean useSmallLabels() { return true; } @Override protected SingleRowLayout createSingleRowLayout() { return new ScrollableSingleRowLayout(this); } @Override public int tabMSize() { return 12; } @Override public void processDropOver(TabInfo over, RelativePoint point) { ((RunnerContentUi)myContext).myTabs.processDropOver(over, point); } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { return ((RunnerContentUi)myContext).myTabs.startDropOver(tabInfo, point); } @Override public void resetDropOver(TabInfo tabInfo) { ((RunnerContentUi)myContext).myTabs.resetDropOver(tabInfo); } @Override protected TabLabel createTabLabel(TabInfo info) { return new TabLabel(this, info) { @Override public void setAlignmentToCenter(boolean toCenter) { super.setAlignmentToCenter(false); } }; } } private static class GridCellTabsOld extends com.intellij.ui.tabs.impl.JBEditorTabs { private final ViewContextEx myContext; private GridCellTabsOld(ViewContextEx context, GridImpl container) { super(context.getProject(), context.getActionManager(), context.getFocusManager(), container); myContext = context; myDefaultPainter.setDefaultTabColor(JBColor.namedColor("DebuggerTabs.selectedBackground", new JBColor(0xC6CFDF, 0x424D5F))); } @Override public boolean useSmallLabels() { return true; } @Override protected com.intellij.ui.tabs.impl.singleRow.SingleRowLayout createSingleRowLayout() { return new com.intellij.ui.tabs.impl.singleRow.ScrollableSingleRowLayout(this); } @Override public int tabMSize() { return 12; } @Override public void processDropOver(TabInfo over, RelativePoint point) { ((RunnerContentUi)myContext).myTabs.processDropOver(over, point); } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { return ((RunnerContentUi)myContext).myTabs.startDropOver(tabInfo, point); } @Override public void resetDropOver(TabInfo tabInfo) { ((RunnerContentUi)myContext).myTabs.resetDropOver(tabInfo); } @Override protected com.intellij.ui.tabs.impl.TabLabel createTabLabel(TabInfo info) { return new com.intellij.ui.tabs.impl.TabLabel(this, info) { @Override public void setAlignmentToCenter(boolean toCenter) { super.setAlignmentToCenter(false); } }; } @Override protected void paintBorder(Graphics2D g2d, ShapeInfo shape, Color borderColor) { if (UIUtil.isUnderDarcula()) { return; } super.paintBorder(g2d, shape, borderColor); } } }
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.ui.layout.impl; import com.intellij.execution.ui.layout.*; import com.intellij.execution.ui.layout.actions.CloseViewAction; import com.intellij.execution.ui.layout.actions.MinimizeViewAction; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.util.ActionCallback; import com.intellij.openapi.util.DimensionService; import com.intellij.openapi.util.MutualMap; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.panels.NonOpaquePanel; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import com.intellij.ui.tabs.*; import com.intellij.ui.tabs.newImpl.JBEditorTabs; import com.intellij.ui.tabs.newImpl.TabLabel; import com.intellij.ui.tabs.newImpl.singleRow.ScrollableSingleRowLayout; import com.intellij.ui.tabs.newImpl.singleRow.SingleRowLayout; import com.intellij.util.SmartList; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashSet; import java.util.List; import java.util.Set; public class GridCellImpl implements GridCell { private final GridImpl myContainer; private final MutualMap<Content, TabInfo> myContents = new MutualMap<>(true); private final Set<Content> myMinimizedContents = new HashSet<>(); private final JBTabs myTabs; private final GridImpl.Placeholder myPlaceholder; private final PlaceInGrid myPlaceInGrid; private final ViewContextEx myContext; private JBPopup myPopup; public GridCellImpl(ViewContextEx context, @NotNull GridImpl container, GridImpl.Placeholder placeholder, PlaceInGrid placeInGrid) { myContext = context; myContainer = container; myPlaceInGrid = placeInGrid; myPlaceholder = placeholder; myPlaceholder.setContentProvider(() -> getContents()); myTabs = JBTabsFactory.getUseNewTabs() ? new GridCellTabs(context, container) : new GridCellTabsOld(context, container); myTabs.setDataProvider(new DataProvider() { @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (ViewContext.CONTENT_KEY.is(dataId)) { TabInfo target = myTabs.getTargetInfo(); if (target != null) { return new Content[]{getContentFor(target)}; } } else if (ViewContext.CONTEXT_KEY.is(dataId)) { return myContext; } return null; } }); myTabs.getPresentation().setUiDecorator(new UiDecorator() { @Override @NotNull public UiDecoration getDecoration() { return new UiDecoration(null, JBTabsFactory.getUseNewTabs()? JBUI.insets(4, 8, 4, 9) : new Insets(1, -1, 1, -1)); } }).setSideComponentVertical(!context.getLayoutSettings().isToolbarHorizontal()) .setStealthTabMode(!JBTabsFactory.getUseNewTabs()).setFocusCycle(false).setPaintFocus(true) .setTabDraggingEnabled(context.isMoveToGridActionEnabled()).setSideComponentOnTabs(false); myTabs.addTabMouseListener(new MouseAdapter() { @Override public void mousePressed(final MouseEvent e) { if (UIUtil.isCloseClick(e)) { // see RunnerContentUi tabMouseListener as well closeOrMinimize(e); } } }); rebuildPopupGroup(); myTabs.addListener(new TabsListener() { @Override public void beforeSelectionChanged(TabInfo oldSelection, TabInfo newSelection) { if (oldSelection != null && myContext.isStateBeingRestored()) { saveUiState(); } } @Override public void selectionChanged(final TabInfo oldSelection, final TabInfo newSelection) { updateSelection(myTabs.getComponent().isShowing()); if (!myTabs.getComponent().isShowing()) return; if (newSelection != null) { newSelection.stopAlerting(); } } }); } public void rebuildPopupGroup() { myTabs.setPopupGroup(myContext.getCellPopupGroup(ViewContext.CELL_POPUP_PLACE), ViewContext.CELL_POPUP_PLACE, true); } public PlaceInGrid getPlaceInGrid() { return myPlaceInGrid; } void add(final Content content) { if (myContents.containsKey(content)) return; myContents.put(content, null); revalidateCell(() -> myTabs.addTab(createTabInfoFor(content))); updateSelection(myTabs.getComponent().getRootPane() != null); } void remove(Content content) { if (!myContents.containsKey(content)) return; final TabInfo info = getTabFor(content); myContents.remove(content); revalidateCell(() -> myTabs.removeTab(info)); updateSelection(myTabs.getComponent().getRootPane() != null); } private void revalidateCell(Runnable contentAction) { if (myContents.size() == 0) { myPlaceholder.removeAll(); myTabs.removeAllTabs(); if (myPopup != null) { myPopup.cancel(); myPopup = null; } } else { if (myPlaceholder.isNull()) { myPlaceholder.setContent(myTabs.getComponent()); } contentAction.run(); } restoreProportions(); myTabs.getComponent().revalidate(); myTabs.getComponent().repaint(); } void setHideTabs(boolean hide) { myTabs.getPresentation().setHideTabs(hide); } private TabInfo createTabInfoFor(Content content) { final TabInfo tabInfo = updatePresentation(new TabInfo(new ProviderWrapper(content, myContext)), content) .setObject(content) .setPreferredFocusableComponent(content.getPreferredFocusableComponent()) .setActionsContextComponent(content.getActionsContextComponent()); myContents.remove(content); myContents.put(content, tabInfo); ActionGroup group = (ActionGroup)myContext.getActionManager().getAction(RunnerContentUi.VIEW_TOOLBAR); tabInfo.setTabLabelActions(group, ViewContext.CELL_TOOLBAR_PLACE); tabInfo.setDragOutDelegate(((RunnerContentUi)myContext).myDragOutDelegate); return tabInfo; } @Nullable private static TabInfo updatePresentation(TabInfo info, Content content) { if (info == null) { return null; } return info. setIcon(content.getIcon()). setText(content.getDisplayName()). setTooltipText(content.getDescription()). setActionsContextComponent(content.getActionsContextComponent()). setActions(content.getActions(), content.getPlace()); } public ActionCallback select(final Content content, final boolean requestFocus) { final TabInfo tabInfo = myContents.getValue(content); return tabInfo != null ? myTabs.select(tabInfo, requestFocus) : ActionCallback.DONE; } public void processAlert(final Content content, final boolean activate) { if (myMinimizedContents.contains(content)) { content.fireAlert(); } TabInfo tab = getTabFor(content); if (tab == null) return; if (myTabs.getSelectedInfo() != tab) { if (activate) { tab.fireAlert(); } else { tab.stopAlerting(); } } } public void updateTabPresentation(Content content) { updatePresentation(myTabs.findInfo(content), content); } public boolean isMinimized(Content content) { return myMinimizedContents.contains(content); } public boolean contains(Component c) { return myTabs.getComponent().isAncestorOf(c); } private static class ProviderWrapper extends NonOpaquePanel implements DataProvider { Content myContent; ViewContext myContext; private ProviderWrapper(final Content content, final ViewContext context) { myContent = content; myContext = context; setLayout(new BorderLayout()); add(content.getComponent(), BorderLayout.CENTER); } @Override @Nullable public Object getData(@NotNull @NonNls final String dataId) { if (ViewContext.CONTENT_KEY.is(dataId)) { return new Content[]{myContent}; } else if (ViewContext.CONTEXT_KEY.is(dataId)) { return myContext; } return null; } } @Nullable TabInfo getTabFor(Content content) { return myContents.getValue(content); } @NotNull private Content getContentFor(TabInfo tab) { return myContents.getKey(tab); } public void setToolbarHorizontal(final boolean horizontal) { myTabs.getPresentation().setSideComponentVertical(!horizontal); } public void setToolbarBefore(final boolean before) { myTabs.getPresentation().setSideComponentBefore(before); } public ActionCallback restoreLastUiState() { final ActionCallback result = new ActionCallback(); restoreProportions(); final Content[] contents = getContents(); final List<Content> toMinimize = new SmartList<>(); int window = 0; for (final Content each : contents) { final View view = myContainer.getStateFor(each); if (view.isMinimizedInGrid()) { toMinimize.add(each); } window = view.getWindow(); } minimize(toMinimize.toArray(new Content[0])); final Tab tab = myContainer.getTab(); final boolean detached = (tab != null && tab.isDetached(myPlaceInGrid)) || window != myContext.getWindow(); if (detached && contents.length > 0) { if (tab != null) { tab.setDetached(myPlaceInGrid, false); } myContext.detachTo(window, this).notifyWhenDone(result); } else { result.setDone(); } return result; } Content[] getContents() { return myContents.getKeys().toArray(new Content[myContents.size()]); } @Override public int getContentCount() { return myContents.size(); } public void saveUiState() { saveProportions(); for (Content each : myContents.getKeys()) { saveState(each, false); } for (Content each : myMinimizedContents) { saveState(each, true); } final DimensionService service = DimensionService.getInstance(); final Dimension size = myContext.getContentManager().getComponent().getSize(); service.setSize(getDimensionKey(), size, myContext.getProject()); if (myContext.getWindow() != 0) { final Window frame = SwingUtilities.getWindowAncestor(myPlaceholder); if (frame != null) { service.setLocation(getDimensionKey(), frame.getLocationOnScreen()); } } } public void saveProportions() { myContainer.saveSplitterProportions(myPlaceInGrid); } private void saveState(Content content, boolean minimized) { View state = myContext.getStateFor(content); state.setMinimizedInGrid(minimized); state.setPlaceInGrid(myPlaceInGrid); final List<Content> contents = myContainer.getContents(); final Tab tab = myContainer.getTabIndex(); if (minimized && contents.size() == 1 && contents.get(0).equals(content)) { state.setTabIndex(-1); if (tab instanceof TabImpl) { ((TabImpl)tab).setIndex(-1); } } state.assignTab(tab); state.setWindow(myContext.getWindow()); } public void restoreProportions() { myContainer.restoreLastSplitterProportions(myPlaceInGrid); } public void updateSelection(final boolean isShowing) { ContentManager contentManager = myContext.getContentManager(); if (contentManager.isDisposed()) return; for (Content each : myContents.getKeys()) { final TabInfo eachTab = getTabFor(each); boolean isSelected = eachTab != null && myTabs.getSelectedInfo() == eachTab; if (isSelected && isShowing) { contentManager.addSelectedContent(each); } else { contentManager.removeFromSelection(each); } } for (Content each : myMinimizedContents) { contentManager.removeFromSelection(each); } } public void minimize(Content[] contents) { if (contents.length == 0) return; myContext.saveUiState(); for (final Content each : contents) { myMinimizedContents.add(each); remove(each); saveState(each, true); boolean isShowing = myTabs.getComponent().getRootPane() != null; myContainer.minimize(each, new CellTransform.Restore() { @Override public ActionCallback restoreInGrid() { return restore(each); } }); updateSelection(isShowing); } } @Nullable public Point getLocation() { return DimensionService.getInstance().getLocation(getDimensionKey(), myContext.getProject()); } @Nullable public Dimension getSize() { return DimensionService.getInstance().getSize(getDimensionKey(), myContext.getProject()); } private String getDimensionKey() { return "GridCell.Tab." + myContainer.getTab().getIndex() + "." + myPlaceInGrid.name(); } public boolean isValidForCalculateProportions() { return getContentCount() > 0; } @Override public void minimize(Content content) { minimize(new Content[]{content}); } public void closeOrMinimize(MouseEvent e) { TabInfo tabInfo = myTabs.findInfo(e); if (tabInfo == null) return; Content content = getContentFor(tabInfo); if (CloseViewAction.isEnabled(new Content[]{content})) { CloseViewAction.perform(myContext, content); } else if (MinimizeViewAction.isEnabled(myContext, getContents(), ViewContext.CELL_TOOLBAR_PLACE)) { minimize(content); } } ActionCallback restore(Content content) { myMinimizedContents.remove(content); return ActionCallback.DONE; } private static class GridCellTabs extends JBEditorTabs { private final ViewContextEx myContext; @Override protected JBTabPainter createTabPainter() { return JBTabPainter.getDEBUGGER(); } private GridCellTabs(ViewContextEx context, GridImpl container) { super(context.getProject(), context.getActionManager(), context.getFocusManager(), container); myContext = context; } @Override public boolean useSmallLabels() { return true; } @Override protected SingleRowLayout createSingleRowLayout() { return new ScrollableSingleRowLayout(this); } @Override public int tabMSize() { return 12; } @Override public void processDropOver(TabInfo over, RelativePoint point) { ((RunnerContentUi)myContext).myTabs.processDropOver(over, point); } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { return ((RunnerContentUi)myContext).myTabs.startDropOver(tabInfo, point); } @Override public void resetDropOver(TabInfo tabInfo) { ((RunnerContentUi)myContext).myTabs.resetDropOver(tabInfo); } @Override protected TabLabel createTabLabel(TabInfo info) { return new TabLabel(this, info) { @Override public void setAlignmentToCenter(boolean toCenter) { super.setAlignmentToCenter(false); } }; } } private static class GridCellTabsOld extends com.intellij.ui.tabs.impl.JBEditorTabs { private final ViewContextEx myContext; private GridCellTabsOld(ViewContextEx context, GridImpl container) { super(context.getProject(), context.getActionManager(), context.getFocusManager(), container); myContext = context; myDefaultPainter.setDefaultTabColor(JBColor.namedColor("DebuggerTabs.selectedBackground", new JBColor(0xC6CFDF, 0x424D5F))); } @Override public boolean useSmallLabels() { return true; } @Override protected com.intellij.ui.tabs.impl.singleRow.SingleRowLayout createSingleRowLayout() { return new com.intellij.ui.tabs.impl.singleRow.ScrollableSingleRowLayout(this); } @Override public int tabMSize() { return 12; } @Override public void processDropOver(TabInfo over, RelativePoint point) { ((RunnerContentUi)myContext).myTabs.processDropOver(over, point); } @Override public Image startDropOver(TabInfo tabInfo, RelativePoint point) { return ((RunnerContentUi)myContext).myTabs.startDropOver(tabInfo, point); } @Override public void resetDropOver(TabInfo tabInfo) { ((RunnerContentUi)myContext).myTabs.resetDropOver(tabInfo); } @Override protected com.intellij.ui.tabs.impl.TabLabel createTabLabel(TabInfo info) { return new com.intellij.ui.tabs.impl.TabLabel(this, info) { @Override public void setAlignmentToCenter(boolean toCenter) { super.setAlignmentToCenter(false); } }; } @Override protected void paintBorder(Graphics2D g2d, ShapeInfo shape, Color borderColor) { if (UIUtil.isUnderDarcula()) { return; } super.paintBorder(g2d, shape, borderColor); } } }
new Editor Tabs UI: Tabs: fix tabs height (#IDEA-207080) (cherry picked from commit b0eac1441862405669f3cc478b00656c02758a94) GitOrigin-RevId: 45dba897f91e9fd027275f2e2d1d3b8327f7e909
platform/lang-impl/src/com/intellij/execution/ui/layout/impl/GridCellImpl.java
new Editor Tabs UI: Tabs: fix tabs height (#IDEA-207080)
Java
apache-2.0
19cae1820f9d97e313e11e6833f070ec23991e66
0
johnmccabe/maven-plugins,apache/maven-plugins,krosenvold/maven-plugins,PressAssociation/maven-plugins,ptahchiev/maven-plugins,Orange-OpenSource/maven-plugins,hgschmie/apache-maven-plugins,ptahchiev/maven-plugins,Orange-OpenSource/maven-plugins,hazendaz/maven-plugins,apache/maven-plugins,lennartj/maven-plugins,mcculls/maven-plugins,zigarn/maven-plugins,restlet/maven-plugins,Orange-OpenSource/maven-plugins,zigarn/maven-plugins,mcculls/maven-plugins,dmlloyd/maven-plugins,edwardmlyte/maven-plugins,mikkokar/maven-plugins,omnidavesz/maven-plugins,kikinteractive/maven-plugins,criteo-forks/maven-plugins,dmlloyd/maven-plugins,johnmccabe/maven-plugins,sonatype/maven-plugins,hazendaz/maven-plugins,rkorpachyov/maven-plugins,krosenvold/maven-plugins,apache/maven-plugins,mikkokar/maven-plugins,PressAssociation/maven-plugins,sonatype/maven-plugins,hgschmie/apache-maven-plugins,PressAssociation/maven-plugins,jdcasey/maven-plugins-fixes,dmlloyd/maven-plugins,rkorpachyov/maven-plugins,HubSpot/maven-plugins,johnmccabe/maven-plugins,hgschmie/apache-maven-plugins,ptahchiev/maven-plugins,hazendaz/maven-plugins,PressAssociation/maven-plugins,lennartj/maven-plugins,HubSpot/maven-plugins,edwardmlyte/maven-plugins,zigarn/maven-plugins,restlet/maven-plugins,sonatype/maven-plugins,jdcasey/maven-plugins-fixes,zigarn/maven-plugins,apache/maven-plugins,kikinteractive/maven-plugins,edwardmlyte/maven-plugins,criteo-forks/maven-plugins,omnidavesz/maven-plugins,lennartj/maven-plugins,kidaa/maven-plugins,jdcasey/maven-plugins-fixes,hazendaz/maven-plugins,mikkokar/maven-plugins,edwardmlyte/maven-plugins,omnidavesz/maven-plugins,omnidavesz/maven-plugins,rkorpachyov/maven-plugins,criteo-forks/maven-plugins,kidaa/maven-plugins,hgschmie/apache-maven-plugins,kidaa/maven-plugins,rkorpachyov/maven-plugins,mcculls/maven-plugins,criteo-forks/maven-plugins,restlet/maven-plugins,HubSpot/maven-plugins,apache/maven-plugins,johnmccabe/maven-plugins,hazendaz/maven-plugins,mcculls/maven-plugins,HubSpot/maven-plugins,kidaa/maven-plugins,sonatype/maven-plugins,krosenvold/maven-plugins,kikinteractive/maven-plugins,restlet/maven-plugins,rkorpachyov/maven-plugins,Orange-OpenSource/maven-plugins,ptahchiev/maven-plugins,lennartj/maven-plugins,mikkokar/maven-plugins,krosenvold/maven-plugins
package org.apache.maven.plugin.javadoc; /* * 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. */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.SystemUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; 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.ArtifactResolver; import org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.javadoc.options.BootclasspathArtifact; import org.apache.maven.plugin.javadoc.options.DocletArtifact; import org.apache.maven.plugin.javadoc.options.Group; import org.apache.maven.plugin.javadoc.options.JavadocPathArtifact; import org.apache.maven.plugin.javadoc.options.OfflineLink; import org.apache.maven.plugin.javadoc.options.ResourcesArtifact; import org.apache.maven.plugin.javadoc.options.Tag; import org.apache.maven.plugin.javadoc.options.Taglet; import org.apache.maven.plugin.javadoc.options.TagletArtifact; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.reporting.MavenReportException; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Settings; import org.apache.maven.shared.invoker.MavenInvocationException; import org.apache.maven.toolchain.Toolchain; import org.apache.maven.toolchain.ToolchainManager; import org.apache.maven.wagon.PathUtils; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; import org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * Base class with majority of Javadoc functionalities. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @author <a href="mailto:[email protected]">Vincent Siveton</a> * @version $Id$ * @since 2.0 * @requiresDependencyResolution compile * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html"> * The Java API Documentation Generator, 1.4.2</a> */ public abstract class AbstractJavadocMojo extends AbstractMojo { /** * The default Javadoc API urls according the * <a href="http://java.sun.com/reference/api/index.html">Sun API Specifications</a>: * <pre> * &lt;javaApiLinks&gt; * &lt;property&gt; * &lt;name&gt;api_1.3&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.3/docs/api&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.4&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.4.2/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.5&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.5.0/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.6&lt;/name&gt; * &lt;value&gt;http://java.sun.com/javase/6/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;/javaApiLinks&gt; * </pre> * * @since 2.6 */ public static final Properties DEFAULT_JAVA_API_LINKS = new Properties(); /** The Javadoc script file name when <code>debug</code> parameter is on, i.e. javadoc.bat or javadoc.sh */ protected static final String DEBUG_JAVADOC_SCRIPT_NAME = "javadoc." + ( SystemUtils.IS_OS_WINDOWS ? "bat" : "sh" ); /** The <code>options</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String OPTIONS_FILE_NAME = "options"; /** The <code>packages</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String PACKAGES_FILE_NAME = "packages"; /** The <code>argfile</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String ARGFILE_FILE_NAME = "argfile"; /** The <code>files</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String FILES_FILE_NAME = "files"; /** The current class directory */ private static final String RESOURCE_DIR = ClassUtils.getPackageName( JavadocReport.class ).replace( '.', '/' ); /** Default css file name */ private static final String DEFAULT_CSS_NAME = "stylesheet.css"; /** Default location for css */ private static final String RESOURCE_CSS_DIR = RESOURCE_DIR + "/css"; /** * For Javadoc options appears since Java 1.4. * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary"> * What's New in Javadoc 1.4</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_4 = 1.4f; /** * For Javadoc options appears since Java 1.4.2. * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * What's New in Javadoc 1.4.2</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_4_2 = 1.42f; /** * For Javadoc options appears since Java 5.0. * See <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * What's New in Javadoc 5.0</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_5 = 1.5f; /** * For Javadoc options appears since Java 6.0. * See <a href="http://java.sun.com/javase/6/docs/technotes/guides/javadoc/index.html"> * Javadoc Technology</a> * @since 2.4 */ private static final float SINCE_JAVADOC_1_6 = 1.6f; // ---------------------------------------------------------------------- // Mojo components // ---------------------------------------------------------------------- /** * Archiver manager * * @since 2.5 * @component */ private ArchiverManager archiverManager; /** * Factory for creating artifact objects * * @component */ private ArtifactFactory factory; /** * Used to resolve artifacts of aggregated modules * * @since 2.1 * @component */ private ArtifactMetadataSource artifactMetadataSource; /** * Used for resolving artifacts * * @component */ private ArtifactResolver resolver; /** * Project builder * * @since 2.5 * @component */ private MavenProjectBuilder mavenProjectBuilder; /** @component */ private ToolchainManager toolchainManager; // ---------------------------------------------------------------------- // Mojo parameters // ---------------------------------------------------------------------- /** * The current build session instance. This is used for * toolchain manager API calls. * * @parameter expression="${session}" * @required * @readonly */ private MavenSession session; /** * The Maven Settings. * * @since 2.3 * @parameter default-value="${settings}" * @required * @readonly */ private Settings settings; /** * The Maven Project Object * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * Specify if the Javadoc should operate in offline mode. * * @parameter default-value="${settings.offline}" * @required * @readonly */ private boolean isOffline; /** * Specifies the Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). * <br/> * Could be used in addition of <code>docfilessubdirs</code> parameter. * <br/> * See <a href="#docfilessubdirs">docfilessubdirs</a>. * * @since 2.1 * @parameter expression="${basedir}/src/main/javadoc" * @see #docfilessubdirs */ private File javadocDirectory; /** * Set an additional parameter(s) on the command line. This value should include quotes as necessary for * parameters that include spaces. Useful for a custom doclet. * * @parameter expression="${additionalparam}" */ private String additionalparam; /** * Set an additional Javadoc option(s) (i.e. JVM options) on the command line. * Example: * <pre> * &lt;additionalJOption&gt;-J-Xss128m&lt;/additionalJOption&gt; * </pre> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#J">Jflag</a>. * <br/> * See <a href="http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp">vmoptions</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html">Networking Properties</a>. * * @since 2.3 * @parameter expression="${additionalJOption}" */ private String additionalJOption; /** * A list of artifacts containing resources which should be copied into the * Javadoc output directory (like stylesheets, icons, etc.). * <br/> * Example: * <pre> * &lt;resourcesArtifacts&gt; * &nbsp;&nbsp;&lt;resourcesArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;external.group.id&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;external-resources&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.0&lt;/version&gt; * &nbsp;&nbsp;&lt;/resourcesArtifact&gt; * &lt;/resourcesArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/ResourcesArtifact.html">Javadoc</a>. * <br/> * * @since 2.5 * @parameter expression="${resourcesArtifacts}" */ private ResourcesArtifact[] resourcesArtifacts; /** * The local repository where the artifacts are located. * * @parameter expression="${localRepository}" */ private ArtifactRepository localRepository; /** * The remote repositories where artifacts are located. * * @parameter expression="${project.remoteArtifactRepositories}" */ private List remoteRepositories; /** * The projects in the reactor for aggregation report. * * @parameter expression="${reactorProjects}" * @readonly */ private List reactorProjects; /** * Whether to build an aggregated report at the root, or build individual reports. * * @parameter expression="${aggregate}" default-value="false" * @deprecated since 2.5. Use the goals <code>javadoc:aggregate</code> and <code>javadoc:test-aggregate</code> instead. */ protected boolean aggregate; /** * Set this to <code>true</code> to debug the Javadoc plugin. With this, <code>javadoc.bat(or.sh)</code>, * <code>options</code>, <code>@packages</code> or <code>argfile</code> files are provided in the output directory. * <br/> * * @since 2.1 * @parameter expression="${debug}" default-value="false" */ private boolean debug; /** * Sets the absolute path of the Javadoc Tool executable to use. Since version 2.5, a mere directory specification * is sufficient to have the plugin use "javadoc" or "javadoc.exe" respectively from this directory. * * @since 2.3 * @parameter expression="${javadocExecutable}" */ private String javadocExecutable; /** * Version of the Javadoc Tool executable to use, ex. "1.3", "1.5". * * @since 2.3 * @parameter expression="${javadocVersion}" */ private String javadocVersion; /** * Version of the Javadoc Tool executable to use as float. */ private float fJavadocVersion = 0.0f; /** * Specifies whether the Javadoc generation should be skipped. * * @since 2.5 * @parameter expression="${maven.javadoc.skip}" default-value="false" */ protected boolean skip; /** * Specifies whether the build will continue even if there are errors. * * @parameter expression="${maven.javadoc.failOnError}" default-value="true" * @since 2.5 */ protected boolean failOnError; /** * Specifies to use the <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard"> * options provided by the Standard Doclet</a> for a custom doclet. * <br/> * Example: * <pre> * &lt;docletArtifacts&gt; * &nbsp;&nbsp;&lt;docletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &nbsp;&nbsp;&lt;/docletArtifact&gt; * &lt;/docletArtifacts&gt; * &lt;useStandardDocletOptions&gt;true&lt;/useStandardDocletOptions&gt; * </pre> * * @parameter expression="${useStandardDocletOptions}" default-value="true" * @since 2.5 */ protected boolean useStandardDocletOptions; /** * Detect the Javadoc links for all dependencies defined in the project. The detection is based on the default * Maven conventions, i.e.: <code>${project.url}/apidocs</code>. * <br/> * For instance, if the project has a dependency to * <a href="http://commons.apache.org/lang/">Apache Commons Lang</a> i.e.: * <pre> * &lt;dependency&gt; * &lt;groupId&gt;commons-lang&lt;/groupId&gt; * &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; * &lt;/dependency&gt; * </pre> * The added Javadoc <code>-link</code> parameter will be <code>http://commons.apache.org/lang/apidocs</code>. * * @parameter expression="${detectLinks}" default-value="false" * @see #links * @since 2.6 */ private boolean detectLinks; /** * Detect the links for all modules defined in the project. * <br/> * If {@link #reactorProjects} is defined in a non-aggregator way, it generates default offline links * between modules based on the defined project's urls. For instance, if a parent project has two projects * <code>module1</code> and <code>module2</code>, the <code>-linkoffline</code> will be: * <br/> * The added Javadoc <code>-linkoffline</code> parameter for <b>module1</b> will be * <code>/absolute/path/to/</code><b>module2</b><code>/target/site/apidocs</code> * <br/> * The added Javadoc <code>-linkoffline</code> parameter for <b>module2</b> will be * <code>/absolute/path/to/</code><b>module1</b><code>/target/site/apidocs</code> * * @parameter expression="${detectOfflineLinks}" default-value="true" * @see #offlineLinks * @since 2.6 */ private boolean detectOfflineLinks; /** * Detect the Java API link for the current build, i.e. <code>http://java.sun.com/j2se/1.4.2/docs/api</code> * for Java source 1.4. * <br/> * By default, the goal detects the Javadoc API link depending the value of the <code>source</code> * parameter in the <code>org.apache.maven.plugins:maven-compiler-plugin</code> * (defined in <code>${project.build.plugins}</code> or in <code>${project.build.pluginManagement}</code>), * or try to compute it from the {@link #javadocExecutable} version. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.html#DEFAULT_JAVA_API_LINKS">Javadoc</a> for the default values. * <br/> * * @parameter expression="${detectJavaApiLink}" default-value="true" * @see #links * @see #javaApiLinks * @see #DEFAULT_JAVA_API_LINKS * @since 2.6 */ private boolean detectJavaApiLink; /** * Use this parameter <b>only</b> if the <a href="http://java.sun.com/reference/api/index.html">Sun Javadoc API</a> * urls have been changed or to use custom urls for Javadoc API url. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.html#DEFAULT_JAVA_API_LINKS">Javadoc</a> * for the default values. * <br/> * * @parameter expression="${javaApiLinks}" * @see #DEFAULT_JAVA_API_LINKS * @since 2.6 */ private Properties javaApiLinks; // ---------------------------------------------------------------------- // Javadoc Options - all alphabetical // ---------------------------------------------------------------------- /** * Specifies the paths where the boot classes reside. The <code>bootclasspath</code> can contain multiple paths * by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bootclasspath">bootclasspath</a>. * <br/> * * @parameter expression="${bootclasspath}" * @since 2.5 */ private String bootclasspath; /** * Specifies the artifacts where the boot classes reside. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bootclasspath">bootclasspath</a>. * <br/> * Example: * <pre> * &lt;bootclasspathArtifacts&gt; * &nbsp;&nbsp;&lt;bootclasspathArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;my-groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;my-artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;my-version&lt;/version&gt; * &nbsp;&nbsp;&lt;/bootclasspathArtifact&gt; * &lt;/bootclasspathArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/BootclasspathArtifact.html">Javadoc</a>. * <br/> * * @parameter expression="${bootclasspathArtifacts}" * @since 2.5 */ private BootclasspathArtifact[] bootclasspathArtifacts; /** * Uses the sentence break iterator to determine the end of the first sentence. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#breakiterator">breakiterator</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${breakiterator}" default-value="false" */ private boolean breakiterator; /** * Specifies the class file that starts the doclet used in generating the documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#doclet">doclet</a>. * * @parameter expression="${doclet}" */ private String doclet; /** * Specifies the artifact containing the doclet starting class file (specified with the <code>-doclet</code> * option). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * <br/> * Example: * <pre> * &lt;docletArtifact&gt; * &nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &lt;/docletArtifact&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/DocletArtifact.html">Javadoc</a>. * <br/> * * @parameter expression="${docletArtifact}" */ private DocletArtifact docletArtifact; /** * Specifies multiple artifacts containing the path for the doclet starting class file (specified with the * <code>-doclet</code> option). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * <br/> * Example: * <pre> * &lt;docletArtifacts&gt; * &nbsp;&nbsp;&lt;docletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &nbsp;&nbsp;&lt;/docletArtifact&gt; * &lt;/docletArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/DocletArtifact.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${docletArtifacts}" */ private DocletArtifact[] docletArtifacts; /** * Specifies the path to the doclet starting class file (specified with the <code>-doclet</code> option) and * any jar files it depends on. The <code>docletPath</code> can contain multiple paths by separating them with * a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * * @parameter expression="${docletPath}" */ private String docletPath; /** * Specifies the encoding name of the source files. If not specificed, the encoding value will be the value of the * <code>file.encoding</code> system property. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#encoding">encoding</a>. * <br/> * <b>Note</b>: In 2.4, the default value was locked to <code>ISO-8859-1</code> to ensure reproducing build, but * this was reverted in 2.5. * <br/> * * @parameter expression="${encoding}" default-value="${project.build.sourceEncoding}" */ private String encoding; /** * Unconditionally excludes the specified packages and their subpackages from the list formed by * <code>-subpackages</code>. Multiple packages can be separated by commas (<code>,</code>), colons (<code>:</code>) * or semicolons (<code>;</code>). * <br/> * Example: * <pre> * &lt;excludePackageNames&gt;*.internal:org.acme.exclude1.*:org.acme.exclude2&lt;/excludePackageNames&gt; * </pre> * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#exclude">exclude</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${excludePackageNames}" */ private String excludePackageNames; /** * Specifies the directories where extension classes reside. Separate directories in <code>extdirs</code> with a * colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#extdirs">extdirs</a>. * * @parameter expression="${extdirs}" */ private String extdirs; /** * Specifies the locale that javadoc uses when generating documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#locale">locale</a>. * * @parameter expression="${locale}" */ private String locale; /** * Specifies the maximum Java heap size to be used when launching the Javadoc tool. * JVMs refer to this property as the <code>-Xmx</code> parameter. Example: '512' or '512m'. * The memory unit depends on the JVM used. The units supported could be: <code>k</code>, <code>kb</code>, * <code>m</code>, <code>mb</code>, <code>g</code>, <code>gb</code>, <code>t</code>, <code>tb</code>. * If no unit specified, the default unit is <code>m</code>. * * @parameter expression="${maxmemory}" */ private String maxmemory; /** * Specifies the minimum Java heap size to be used when launching the Javadoc tool. * JVMs refer to this property as the <code>-Xms</code> parameter. Example: '512' or '512m'. * The memory unit depends on the JVM used. The units supported could be: <code>k</code>, <code>kb</code>, * <code>m</code>, <code>mb</code>, <code>g</code>, <code>gb</code>, <code>t</code>, <code>tb</code>. * If no unit specified, the default unit is <code>m</code>. * * @parameter expression="${minmemory}" */ private String minmemory; /** * This option creates documentation with the appearance and functionality of documentation generated by * Javadoc 1.1. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#1.1">1.1</a>. * <br/> * * @parameter expression="${old}" default-value="false" */ private boolean old; /** * Specifies that javadoc should retrieve the text for the overview documentation from the "source" file * specified by path/filename and place it on the Overview page (overview-summary.html). * <br/> * <b>Note</b>: could be in conflict with &lt;nooverview/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#overview">overview</a>. * <br/> * * @parameter expression="${overview}" default-value="${basedir}/src/main/javadoc/overview.html" */ private File overview; /** * Specifies the proxy host where the javadoc web access in <code>-link</code> would pass through. * It defaults to the proxy host of the active proxy set in the <code>settings.xml</code>, otherwise it gets the * proxy configuration set in the pom. * <br/> * * @parameter expression="${proxyHost}" * @deprecated since 2.4. Instead of, configure an active proxy host in <code>settings.xml</code>. */ private String proxyHost; /** * Specifies the proxy port where the javadoc web access in <code>-link</code> would pass through. * It defaults to the proxy port of the active proxy set in the <code>settings.xml</code>, otherwise it gets the * proxy configuration set in the pom. * <br/> * * @parameter expression="${proxyPort}" * @deprecated since 2.4. Instead of, configure an active proxy port in <code>settings.xml</code>. */ private int proxyPort; /** * Shuts off non-error and non-warning messages, leaving only the warnings and errors appear, making them * easier to view. * <br/> * Note: was a standard doclet in Java 1.4.2 (refer to bug ID * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4714350">4714350</a>). * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#quiet">quiet</a>. * <br/> * Since Java 5.0. * <br/> * * @parameter expression="${quiet}" default-value="false" */ private boolean quiet; /** * Specifies the access level for classes and members to show in the Javadocs. * Possible values are: * <ul> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#public">public</a> * (shows only public classes and members)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#protected">protected</a> * (shows only public and protected classes and members)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package">package</a> * (shows all classes and members not marked private)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#private">private</a> * (shows all classes and members)</li> * </ul> * <br/> * * @parameter expression="${show}" default-value="protected" */ private String show; /** * Necessary to enable javadoc to handle assertions present in J2SE v 1.4 source code. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#source">source</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${source}" */ private String source; /** * Specifies the source paths where the subpackages are located. The <code>sourcepath</code> can contain * multiple paths by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#sourcepath">sourcepath</a>. * * @parameter expression="${sourcepath}" */ private String sourcepath; /** * Specifies the package directory where javadoc will be executed. Multiple packages can be separated by * colons (<code>:</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#subpackages">subpackages</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${subpackages}" */ private String subpackages; /** * Provides more detailed messages while javadoc is running. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#verbose">verbose</a>. * <br/> * * @parameter expression="${verbose}" default-value="false" */ private boolean verbose; // ---------------------------------------------------------------------- // Standard Doclet Options - all alphabetical // ---------------------------------------------------------------------- /** * Specifies whether or not the author text is included in the generated Javadocs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#author">author</a>. * <br/> * * @parameter expression="${author}" default-value="true" */ private boolean author; /** * Specifies the text to be placed at the bottom of each output file.<br/> * If you want to use html you have to put it in a CDATA section, <br/> * eg. <code>&lt;![CDATA[Copyright 2005, &lt;a href="http://www.mycompany.com">MyCompany, Inc.&lt;a>]]&gt;</code> * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bottom">bottom</a>. * <br/> * * @parameter expression="${bottom}" * default-value="Copyright &#169; {inceptionYear}-{currentYear} {organizationName}. All Rights Reserved." */ private String bottom; /** * Specifies the HTML character set for this document. If not specificed, the charset value will be the value of * the <code>docencoding</code> parameter. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#charset">charset</a>. * <br/> * * @parameter expression="${charset}" */ private String charset; /** * Specifies the encoding of the generated HTML files. If not specificed, the docencoding value will be * <code>UTF-8</code>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docencoding">docencoding</a>. * * @parameter expression="${docencoding}" default-value="${project.reporting.outputEncoding}" */ private String docencoding; /** * Enables deep copying of the <code>&#42;&#42;/doc-files</code> directories and the specifc <code>resources</code> * directory from the <code>javadocDirectory</code> directory (for instance, * <code>src/main/javadoc/com/mycompany/myapp/doc-files</code> and <code>src/main/javadoc/resources</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docfilessubdirs"> * docfilessubdirs</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * See <a href="#javadocDirectory">javadocDirectory</a>. * <br/> * * @parameter expression="${docfilessubdirs}" default-value="false" * @see #excludedocfilessubdir * @see #javadocDirectory */ private boolean docfilessubdirs; /** * Specifies the title to be placed near the top of the overview summary file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#doctitle">doctitle</a>. * <br/> * * @parameter expression="${doctitle}" default-value="${project.name} ${project.version} API" */ private String doctitle; /** * Excludes any "doc-files" subdirectories with the given names. Multiple patterns can be excluded * by separating them with colons (<code>:</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#excludedocfilessubdir"> * excludedocfilessubdir</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${excludedocfilessubdir}" * @see #docfilessubdirs */ private String excludedocfilessubdir; /** * Specifies the footer text to be placed at the bottom of each output file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#footer">footer</a>. * * @parameter expression="${footer}" */ private String footer; /** * Separates packages on the overview page into whatever groups you specify, one group per table. The * packages pattern can be any package name, or can be the start of any package name followed by an asterisk * (<code>*</code>) meaning "match any characters". Multiple patterns can be included in a group * by separating them with colons (<code>:</code>). * <br/> * Example: * <pre> * &lt;groups&gt; * &nbsp;&nbsp;&lt;group&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Core Packages&lt;/title&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;!-- To includes java.lang, java.lang.ref, * &nbsp;&nbsp;&nbsp;&nbsp;java.lang.reflect and only java.util * &nbsp;&nbsp;&nbsp;&nbsp;(i.e. not java.util.jar) --&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;packages&gt;java.lang*:java.util&lt;/packages&gt; * &nbsp;&nbsp;&lt;/group&gt; * &nbsp;&nbsp;&lt;group&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Extension Packages&lt;/title&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;!-- To include javax.accessibility, * &nbsp;&nbsp;&nbsp;&nbsp;javax.crypto, ... (among others) --&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;packages&gt;javax.*&lt;/packages&gt; * &nbsp;&nbsp;&lt;/group&gt; * &lt;/groups&gt; * </pre> * <b>Note</b>: using <code>java.lang.*</code> for <code>packages</code> would omit the <code>java.lang</code> * package but using <code>java.lang*</code> will include it. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#group">group</a>. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Group.html">Javadoc</a>. * <br/> * * @parameter expression="${groups}" */ private Group[] groups; /** * Specifies the header text to be placed at the top of each output file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#header">header</a>. * * @parameter expression="${header}" */ private String header; /** * Specifies the path of an alternate help file path\filename that the HELP link in the top and bottom * navigation bars link to. * <br/> * <b>Note</b>: could be in conflict with &lt;nohelp/&gt;. * <br/> * The <code>helpfile</code> could be an absolute File path. * <br/> * Since 2.6, it could be also be a path from a resource in the current project source directories * (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies, for instance: * <pre> * &lt;helpfile&gt;path/to/your/resource/yourhelp-doc.html&lt;/helpfile&gt; * </pre> * Where <code>path/to/your/resource/yourhelp-doc.html</code> could be in <code>src/main/javadoc</code>. * <pre> * &lt;build&gt; * &nbsp;&nbsp;&lt;plugins&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;helpfile&gt;path/to/your/resource/yourhelp-doc.html&lt;/helpfile&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&lt;plugins&gt; * &lt;/build&gt; * </pre> * Where <code>path/to/your/resource/yourhelp-doc.html</code> is defined in the * <code>groupId:artifactId:version</code> javadoc plugin dependency. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#helpfile">helpfile</a>. * * @parameter expression="${helpfile}" */ private String helpfile; /** * Adds HTML meta keyword tags to the generated file for each class. * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#keywords">keywords</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * Java 1.4.2</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * Java 5.0</a>. * <br/> * * @since 2.1 * @parameter expression="${keywords}" default-value="false" */ private boolean keywords; /** * Creates links to existing javadoc-generated documentation of external referenced classes. * <br/> * <b>Notes</b>: * <ol> * <li>only used is {@link #isOffline} is set to <code>false</code>.</li> * <li>all given links should have a fetchable <code>/package-list</code> file. For instance: * <pre> * &lt;links&gt; * &nbsp;&nbsp;&lt;link&gt;http://java.sun.com/j2se/1.4.2/docs/api&lt;/link&gt; * &lt;links&gt; * </pre> * will be used because <code>http://java.sun.com/j2se/1.4.2/docs/api/package-list</code> exists.</li> * <li>if {@link #detectLinks} is defined, the links between the project dependencies are * automatically added.</li> * <li>if {@link #detectJavaApiLink} is defined, a Java API link, based on the Java verion of the * project's sources, will be added automatically.</li> * </ol> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#link">link</a>. * * @parameter expression="${links}" * @see #detectLinks * @see #detectJavaApiLink */ protected ArrayList links; /** * Creates an HTML version of each source file (with line numbers) and adds links to them from the standard * HTML documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#linksource">linksource</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${linksource}" default-value="false" */ private boolean linksource; /** * Suppress the entire comment body, including the main description and all tags, generating only declarations. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nocomment">nocomment</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${nocomment}" default-value="false" */ private boolean nocomment; /** * Prevents the generation of any deprecated API at all in the documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nodeprecated">nodeprecated</a>. * <br/> * * @parameter expression="${nodeprecated}" default-value="false" */ private boolean nodeprecated; /** * Prevents the generation of the file containing the list of deprecated APIs (deprecated-list.html) and the * link in the navigation bar to that page. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nodeprecatedlist"> * nodeprecatedlist</a>. * <br/> * * @parameter expression="${nodeprecatedlist}" default-value="false" */ private boolean nodeprecatedlist; /** * Omits the HELP link in the navigation bars at the top and bottom of each page of output. * <br/> * <b>Note</b>: could be in conflict with &lt;helpfile/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nohelp">nohelp</a>. * <br/> * * @parameter expression="${nohelp}" default-value="false" */ private boolean nohelp; /** * Omits the index from the generated docs. * <br/> * <b>Note</b>: could be in conflict with &lt;splitindex/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#noindex">noindex</a>. * <br/> * * @parameter expression="${noindex}" default-value="false" */ private boolean noindex; /** * Omits the navigation bar from the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nonavbar">nonavbar</a>. * <br/> * * @parameter expression="${nonavbar}" default-value="false" */ private boolean nonavbar; /** * Omits the entire overview page from the generated docs. * <br/> * <b>Note</b>: could be in conflict with &lt;overview/&gt;. * <br/> * Standard Doclet undocumented option. * <br/> * * @since 2.4 * @parameter expression="${nooverview}" default-value="false" */ private boolean nooverview; /** * Omits qualifying package name from ahead of class names in output. * Example: * <pre> * &lt;noqualifier&gt;all&lt;/noqualifier&gt; * or * &lt;noqualifier&gt;packagename1:packagename2&lt;/noqualifier&gt; * </pre> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#noqualifier">noqualifier</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${noqualifier}" */ private String noqualifier; /** * Omits from the generated docs the "Since" sections associated with the since tags. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nosince">nosince</a>. * <br/> * * @parameter expression="${nosince}" default-value="false" */ private boolean nosince; /** * Suppresses the timestamp, which is hidden in an HTML comment in the generated HTML near the top of each page. * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#notimestamp">notimestamp</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * Java 5.0</a>. * <br/> * * @since 2.1 * @parameter expression="${notimestamp}" default-value="false" */ private boolean notimestamp; /** * Omits the class/interface hierarchy pages from the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#notree">notree</a>. * <br/> * * @parameter expression="${notree}" default-value="false" */ private boolean notree; /** * This option is a variation of <code>-link</code>; they both create links to javadoc-generated documentation * for external referenced classes. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#linkoffline">linkoffline</a>. * <br/> * Example: * <pre> * &lt;offlineLinks&gt; * &nbsp;&nbsp;&lt;offlineLink&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;url&gt;http://java.sun.com/j2se/1.5.0/docs/api/&lt;/url&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;location&gt;../javadoc/jdk-5.0/&lt;/location&gt; * &nbsp;&nbsp;&lt;/offlineLink&gt; * &lt;/offlineLinks&gt; * </pre> * <br/> * <b>Note</b>: if {@link #detectOfflineLinks} is defined, the offline links between the project modules are * automatically added if the goal is calling in a non-aggregator way. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/OfflineLink.html">Javadoc</a>. * <br/> * * @parameter expression="${offlineLinks}" */ private OfflineLink[] offlineLinks; /** * Specifies the destination directory where javadoc saves the generated HTML files. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#d">d</a>. * <br/> * * @parameter expression="${destDir}" alias="destDir" default-value="${project.build.directory}/apidocs" * @required */ protected File outputDirectory; /** * Specify the text for upper left frame. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * Java 1.4.2</a>. * * @since 2.1 * @parameter expression="${packagesheader}" */ private String packagesheader; /** * Generates compile-time warnings for missing serial tags. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#serialwarn">serialwarn</a> * <br/> * * @parameter expression="${serialwarn}" default-value="false" */ private boolean serialwarn; /** * Specify the number of spaces each tab takes up in the source. If no tab is used in source, the default * space is used. * <br/> * Note: was <code>linksourcetab</code> in Java 1.4.2 (refer to bug ID * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4788919">4788919</a>). * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * 1.4.2</a>. * <br/> * Since Java 5.0. * * @since 2.1 * @parameter expression="${sourcetab}" alias="linksourcetab" */ private int sourcetab; /** * Splits the index file into multiple files, alphabetically, one file per letter, plus a file for any index * entries that start with non-alphabetical characters. * <br/> * <b>Note</b>: could be in conflict with &lt;noindex/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#splitindex">splitindex</a>. * <br/> * * @parameter expression="${splitindex}" default-value="false" */ private boolean splitindex; /** * Specifies whether the stylesheet to be used is the <code>maven</code>'s javadoc stylesheet or * <code>java</code>'s default stylesheet when a <i>stylesheetfile</i> parameter is not specified. * <br/> * Possible values: <code>maven<code> or <code>java</code>. * <br/> * * @parameter expression="${stylesheet}" default-value="java" */ private String stylesheet; /** * Specifies the path of an alternate HTML stylesheet file. * <br/> * The <code>stylesheetfile</code> could be an absolute File path. * <br/> * Since 2.6, it could be also be a path from a resource in the current project source directories * (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies, for instance: * <pre> * &lt;stylesheetfile&gt;path/to/your/resource/yourstylesheet.css&lt;/stylesheetfile&gt; * </pre> * Where <code>path/to/your/resource/yourstylesheet.css</code> could be in <code>src/main/javadoc</code>. * <pre> * &lt;build&gt; * &nbsp;&nbsp;&lt;plugins&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;stylesheetfile&gt;path/to/your/resource/yourstylesheet.css&lt;/stylesheetfile&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&lt;plugins&gt; * &lt;/build&gt; * </pre> * Where <code>path/to/your/resource/yourstylesheet.css</code> is defined in the * <code>groupId:artifactId:version</code> javadoc plugin dependency. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#stylesheetfile"> * stylesheetfile</a>. * * @parameter expression="${stylesheetfile}" */ private String stylesheetfile; /** * Specifies the class file that starts the taglet used in generating the documentation for that tag. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${taglet}" */ private String taglet; /** * Specifies the Taglet artifact containing the taglet class files (.class). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;taglets&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;com.sun.tools.doclets.ToDoTaglet&lt;/tagletClass&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;package.to.AnotherTagletClass&lt;/tagletClass&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &nbsp;&nbsp;... * &lt;/taglets&gt; * &lt;tagletArtifact&gt; * &nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &lt;/tagletArtifact&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/TagletArtifact.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${tagletArtifact}" */ private TagletArtifact tagletArtifact; /** * Specifies several Taglet artifacts containing the taglet class files (.class). These taglets class names will be * auto-detect and so no need to specify them. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;tagletArtifacts&gt; * &nbsp;&nbsp;&lt;tagletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &nbsp;&nbsp;&lt;/tagletArtifact&gt; * &nbsp;&nbsp;... * &lt;/tagletArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/TagletArtifact.html">Javadoc</a>. * <br/> * * @since 2.5 * @parameter expression="${tagletArtifacts}" */ private TagletArtifact[] tagletArtifacts; /** * Specifies the search paths for finding taglet class files (.class). The <code>tagletpath</code> can contain * multiple paths by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${tagletpath}" */ private String tagletpath; /** * Enables the Javadoc tool to interpret multiple taglets. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;taglets&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;com.sun.tools.doclets.ToDoTaglet&lt;/tagletClass&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&lt;tagletpath&gt;/home/taglets&lt;/tagletpath&gt;--&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/tagletArtifact&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &lt;/taglets&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Taglet.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${taglets}" */ private Taglet[] taglets; /** * Enables the Javadoc tool to interpret a simple, one-argument custom block tag tagname in doc comments. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tag">tag</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * Example: * <pre> * &lt;tags&gt; * &nbsp;&nbsp;&lt;tag&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;todo&lt;/name&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;placement&gt;a&lt;/placement&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;head&gt;To Do:&lt;/head&gt; * &nbsp;&nbsp;&lt;/tag&gt; * &lt;/tags&gt; * </pre> * <b>Note</b>: the placement should be a combinaison of Xaoptcmf letters: * <ul> * <li><b><code>X</code></b> (disable tag)</li> * <li><b><code>a</code></b> (all)</li> * <li><b><code>o</code></b> (overview)</li> * <li><b><code>p</code></b> (packages)</li> * <li><b><code>t</code></b> (types, that is classes and interfaces)</li> * <li><b><code>c</code></b> (constructors)</li> * <li><b><code>m</code></b> (methods)</li> * <li><b><code>f</code></b> (fields)</li> * </ul> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Tag.html">Javadoc</a>. * <br/> * * @parameter expression="${tags}" */ private Tag[] tags; /** * Specifies the top text to be placed at the top of each output file. * <br/> * See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6227616">6227616</a>. * <br/> * Since Java 6.0 * * @since 2.4 * @parameter expression="${top}" */ private String top; /** * Includes one "Use" page for each documented class and package. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#use">use</a>. * <br/> * * @parameter expression="${use}" default-value="true" */ private boolean use; /** * Includes the version text in the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#version">version</a>. * <br/> * * @parameter expression="${version}" default-value="true" */ private boolean version; /** * Specifies the title to be placed in the HTML title tag. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#windowtitle">windowtitle</a>. * <br/> * * @parameter expression="${windowtitle}" default-value="${project.name} ${project.version} API" */ private String windowtitle; // ---------------------------------------------------------------------- // static // ---------------------------------------------------------------------- static { DEFAULT_JAVA_API_LINKS.put( "api_1.3", "http://java.sun.com/j2se/1.3/docs/api" ); DEFAULT_JAVA_API_LINKS.put( "api_1.4", "http://java.sun.com/j2se/1.4.2/docs/api/" ); DEFAULT_JAVA_API_LINKS.put( "api_1.5", "http://java.sun.com/j2se/1.5.0/docs/api/" ); DEFAULT_JAVA_API_LINKS.put( "api_1.6", "http://java.sun.com/javase/6/docs/api/" ); } // ---------------------------------------------------------------------- // protected methods // ---------------------------------------------------------------------- /** * Indicates whether this goal is flagged with <code>@aggregator</code>. * * @return <code>true</code> if the goal is designed as an aggregator, <code>false</code> otherwise. * @see AggregatorJavadocReport * @see AggregatorTestJavadocReport */ protected boolean isAggregator() { return false; } /** * @return the output directory */ protected String getOutputDirectory() { return outputDirectory.getAbsoluteFile().toString(); } /** * @param p not null maven project * @return the list of directories where compiled classes are placed for the given project. These dirs are * added in the javadoc classpath. */ protected List getProjectBuildOutputDirs( MavenProject p ) { if ( StringUtils.isEmpty( p.getBuild().getOutputDirectory() ) ) { return Collections.EMPTY_LIST; } return Collections.singletonList( p.getBuild().getOutputDirectory() ); } /** * @param p not null maven project * @return the list of source paths for the given project */ protected List getProjectSourceRoots( MavenProject p ) { if ( "pom".equals( p.getPackaging().toLowerCase() ) ) { return Collections.EMPTY_LIST; } return ( p.getCompileSourceRoots() == null ? Collections.EMPTY_LIST : new LinkedList( p.getCompileSourceRoots() ) ); } /** * @param p not null maven project * @return the list of source paths for the execution project of the given project */ protected List getExecutionProjectSourceRoots( MavenProject p ) { if ( "pom".equals( p.getExecutionProject().getPackaging().toLowerCase() ) ) { return Collections.EMPTY_LIST; } return ( p.getExecutionProject().getCompileSourceRoots() == null ? Collections.EMPTY_LIST : new LinkedList( p.getExecutionProject().getCompileSourceRoots() ) ); } /** * @param p not null maven project * @return the list of artifacts for the given project */ protected List getProjectArtifacts( MavenProject p ) { return ( p.getCompileArtifacts() == null ? Collections.EMPTY_LIST : new LinkedList( p.getCompileArtifacts() ) ); } /** * @return the current javadoc directory */ protected File getJavadocDirectory() { return javadocDirectory; } /** * @return the title to be placed near the top of the overview summary file */ protected String getDoctitle() { return doctitle; } /** * @return the overview documentation file from the user parameter or from the <code>javadocdirectory</code> */ protected File getOverview() { return overview; } /** * @return the title to be placed in the HTML title tag */ protected String getWindowtitle() { return windowtitle; } /** * @return the charset attribute or the value of {@link #getDocencoding()} if <code>null</code>. */ private String getCharset() { return ( StringUtils.isEmpty( charset ) ) ? getDocencoding() : charset; } /** * @return the docencoding attribute or <code>UTF-8</code> if <code>null</code>. */ private String getDocencoding() { return ( StringUtils.isEmpty( docencoding ) ) ? ReaderFactory.UTF_8 : docencoding; } /** * @return the encoding attribute or the value of <code>file.encoding</code> system property if <code>null</code>. */ private String getEncoding() { return ( StringUtils.isEmpty( encoding ) ) ? ReaderFactory.FILE_ENCODING : encoding; } /** * The <a href="package-summary.html">package documentation</a> details the * Javadoc Options used by this Plugin. * * @param unusedLocale the wanted locale (actually unused). * @throws MavenReportException if any */ protected void executeReport( Locale unusedLocale ) throws MavenReportException { if ( skip ) { getLog().info( "Skipping javadoc generation" ); return; } if ( isAggregator() && !project.isExecutionRoot() ) { return; } if ( getLog().isDebugEnabled() ) { this.debug = true; } List sourcePaths = getSourcePaths(); List files = getFiles( sourcePaths ); if ( !canGenerateReport( files ) ) { return; } List packageNames = getPackageNames( sourcePaths, files ); List filesWithUnnamedPackages = getFilesWithUnnamedPackages( sourcePaths, files ); // ---------------------------------------------------------------------- // Find the javadoc executable and version // ---------------------------------------------------------------------- String jExecutable; try { jExecutable = getJavadocExecutable(); } catch ( IOException e ) { throw new MavenReportException( "Unable to find javadoc command: " + e.getMessage(), e ); } setFJavadocVersion( new File( jExecutable ) ); // ---------------------------------------------------------------------- // Javadoc output directory as File // ---------------------------------------------------------------------- File javadocOutputDirectory = new File( getOutputDirectory() ); if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.isDirectory() ) { throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not a directory." ); } if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.canWrite() ) { throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not writable." ); } javadocOutputDirectory.mkdirs(); // ---------------------------------------------------------------------- // Copy all resources // ---------------------------------------------------------------------- copyAllResources( javadocOutputDirectory ); // ---------------------------------------------------------------------- // Create command line for Javadoc // ---------------------------------------------------------------------- Commandline cmd = new Commandline(); cmd.getShell().setQuotedArgumentsEnabled( false ); // for Javadoc JVM args cmd.setWorkingDirectory( javadocOutputDirectory.getAbsolutePath() ); cmd.setExecutable( jExecutable ); // ---------------------------------------------------------------------- // Wrap Javadoc JVM args // ---------------------------------------------------------------------- addMemoryArg( cmd, "-Xmx", this.maxmemory ); addMemoryArg( cmd, "-Xms", this.minmemory ); addProxyArg( cmd ); if ( StringUtils.isNotEmpty( additionalJOption ) ) { cmd.createArg().setValue( additionalJOption ); } List arguments = new ArrayList(); // ---------------------------------------------------------------------- // Wrap Javadoc options // ---------------------------------------------------------------------- addJavadocOptions( arguments, sourcePaths ); // ---------------------------------------------------------------------- // Wrap Standard doclet Options // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( doclet ) || useStandardDocletOptions ) { addStandardDocletOptions( javadocOutputDirectory, arguments ); } // ---------------------------------------------------------------------- // Write options file and include it in the command line // ---------------------------------------------------------------------- if ( arguments.size() > 0 ) { addCommandLineOptions( cmd, arguments, javadocOutputDirectory ); } // ---------------------------------------------------------------------- // Write packages file and include it in the command line // ---------------------------------------------------------------------- if ( !packageNames.isEmpty() ) { addCommandLinePackages( cmd, javadocOutputDirectory, packageNames ); // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- if ( !filesWithUnnamedPackages.isEmpty() ) { addCommandLineArgFile( cmd, javadocOutputDirectory, filesWithUnnamedPackages ); } } else { // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- if ( !files.isEmpty() ) { addCommandLineArgFile( cmd, javadocOutputDirectory, files ); } } // ---------------------------------------------------------------------- // Execute command line // ---------------------------------------------------------------------- executeJavadocCommandLine( cmd, javadocOutputDirectory ); // delete generated javadoc files only if no error and no debug mode if ( !debug ) { for ( int i = 0; i < cmd.getArguments().length; i++) { String arg = cmd.getArguments()[i].trim(); if ( !arg.startsWith( "@" )) { continue; } File argFile = new File( javadocOutputDirectory, arg.substring( 1 ) ); if ( argFile.exists() ) { argFile.deleteOnExit(); } } File scriptFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); if ( scriptFile.exists() ) { scriptFile.deleteOnExit(); } } } /** * Method to get the files on the specified source paths * * @param sourcePaths a List that contains the paths to the source files * @return a List that contains the specific path for every source file */ protected List getFiles( List sourcePaths ) { List files = new ArrayList(); if ( StringUtils.isEmpty( subpackages ) ) { String[] excludedPackages = getExcludedPackages(); for ( Iterator i = sourcePaths.iterator(); i.hasNext(); ) { File sourceDirectory = new File( (String) i.next() ); JavadocUtil.addFilesFromSource( files, sourceDirectory, excludedPackages ); } } return files; } /** * Method to get the source paths. If no source path is specified in the parameter, the compile source roots * of the project will be used. * * @return a List of the project absolute source paths as <code>String</code> * @see JavadocUtil#pruneDirs(MavenProject, List) */ protected List getSourcePaths() { List sourcePaths; if ( StringUtils.isEmpty( sourcepath ) ) { sourcePaths = new ArrayList( JavadocUtil.pruneDirs( project, getProjectSourceRoots( project ) ) ); if ( project.getExecutionProject() != null ) { sourcePaths.addAll( JavadocUtil.pruneDirs( project, getExecutionProjectSourceRoots( project ) ) ); } /* * Should be after the source path (i.e. -sourcepath '.../src/main/java;.../src/main/javadoc') and * *not* the opposite. If not, the javadoc tool always copies doc files, even if -docfilessubdirs is * not setted. */ if ( getJavadocDirectory() != null ) { File javadocDir = getJavadocDirectory(); if ( javadocDir.exists() && javadocDir.isDirectory() ) { List l = JavadocUtil.pruneDirs( project, Collections.singletonList( getJavadocDirectory().getAbsolutePath() ) ); sourcePaths.addAll( l ); } } if ( isAggregator() && project.isExecutionRoot() ) { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { List sourceRoots = getProjectSourceRoots( subProject ); if ( subProject.getExecutionProject() != null ) { sourceRoots.addAll( getExecutionProjectSourceRoots( subProject ) ); } ArtifactHandler artifactHandler = subProject.getArtifact().getArtifactHandler(); if ( "java".equals( artifactHandler.getLanguage() ) ) { sourcePaths.addAll( JavadocUtil.pruneDirs( subProject, sourceRoots ) ); } String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getJavadocDirectory().getAbsolutePath() ); File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); if ( javadocDir.exists() && javadocDir.isDirectory() ) { List l = JavadocUtil.pruneDirs( subProject, Collections.singletonList( javadocDir.getAbsolutePath() ) ); sourcePaths.addAll( l ); } } } } } else { sourcePaths = new ArrayList( Arrays.asList( JavadocUtil.splitPath( sourcepath ) ) ); sourcePaths = JavadocUtil.pruneDirs( project, sourcePaths ); if ( getJavadocDirectory() != null ) { List l = JavadocUtil.pruneDirs( project, Collections.singletonList( getJavadocDirectory().getAbsolutePath() ) ); sourcePaths.addAll( l ); } } sourcePaths = JavadocUtil.pruneDirs( project, sourcePaths ); return sourcePaths; } /** * Method that indicates whether the javadoc can be generated or not. If the project does not contain any source * files and no subpackages are specified, the plugin will terminate. * * @param files the project files * @return a boolean that indicates whether javadoc report can be generated or not */ protected boolean canGenerateReport( List files ) { boolean canGenerate = true; if ( files.isEmpty() && StringUtils.isEmpty( subpackages ) ) { canGenerate = false; } return canGenerate; } /** * @param result not null * @return the compile artifacts from the result * @see JavadocUtil#getCompileArtifacts(Set, boolean) */ protected List getCompileArtifacts( ArtifactResolutionResult result ) { return JavadocUtil.getCompileArtifacts( result.getArtifacts(), false ); } // ---------------------------------------------------------------------- // private methods // ---------------------------------------------------------------------- /** * Method to get the excluded source files from the javadoc and create the argument string * that will be included in the javadoc commandline execution. * * @param sourcePaths the list of paths to the source files * @return a String that contains the exclude argument that will be used by javadoc */ private String getExcludedPackages( List sourcePaths ) { List excludedNames = null; if ( StringUtils.isNotEmpty( sourcepath ) && StringUtils.isNotEmpty( subpackages ) ) { String[] excludedPackages = getExcludedPackages(); String[] subpackagesList = subpackages.split( "[:]" ); excludedNames = JavadocUtil.getExcludedNames( sourcePaths, subpackagesList, excludedPackages ); } String excludeArg = ""; if ( StringUtils.isNotEmpty( subpackages ) && excludedNames != null ) { // add the excludedpackage names for ( Iterator it = excludedNames.iterator(); it.hasNext(); ) { String str = (String) it.next(); excludeArg = excludeArg + str; if ( it.hasNext() ) { excludeArg = excludeArg + ":"; } } } return excludeArg; } /** * Method to format the specified source paths that will be accepted by the javadoc tool. * * @param sourcePaths the list of paths to the source files that will be included in the javadoc. * @return a String that contains the formatted source path argument, separated by the System pathSeparator * string (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @see File#pathSeparator */ private String getSourcePath( List sourcePaths ) { String sourcePath = null; if ( StringUtils.isEmpty( subpackages ) || StringUtils.isNotEmpty( sourcepath ) ) { sourcePath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); } return sourcePath; } /** * Method to get the packages specified in the <code>excludePackageNames</code> parameter. The packages are split * with ',', ':', or ';' and then formatted. * * @return an array of String objects that contain the package names */ private String[] getExcludedPackages() { String[] excludePackages = {}; // for the specified excludePackageNames if ( excludePackageNames != null ) { excludePackages = excludePackageNames.split( "[,:;]" ); } for ( int i = 0; i < excludePackages.length; i++ ) { excludePackages[i] = excludePackages[i].replace( '.', File.separatorChar ); } return excludePackages; } /** * Method that sets the classpath elements that will be specified in the javadoc <code>-classpath</code> * parameter. * * @return a String that contains the concatenated classpath elements, separated by the System pathSeparator * string (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any. * @see File#pathSeparator */ private String getClasspath() throws MavenReportException { List classpathElements = new ArrayList(); Map compileArtifactMap = new HashMap(); classpathElements.addAll( getProjectBuildOutputDirs( project ) ); populateCompileArtifactMap( compileArtifactMap, getProjectArtifacts( project ) ); if ( isAggregator() && project.isExecutionRoot() ) { try { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { classpathElements.addAll( getProjectBuildOutputDirs( subProject ) ); Set dependencyArtifacts = subProject.createArtifacts( factory, null, null ); if ( !dependencyArtifacts.isEmpty() ) { ArtifactResolutionResult result = null; try { result = resolver.resolveTransitively( dependencyArtifacts, subProject.getArtifact(), subProject.getManagedVersionMap(), localRepository, subProject.getRemoteArtifactRepositories(), artifactMetadataSource ); } catch ( MultipleArtifactsNotFoundException e ) { if ( checkMissingArtifactsInReactor( dependencyArtifacts, e.getMissingArtifacts() ) ) { getLog().warn( "IGNORED to add some artifacts in the classpath. See above." ); } else { // we can't find all the artifacts in the reactor so bubble the exception up. throw new MavenReportException( e.getMessage(), e ); } } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( e.getMessage(), e ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( e.getMessage(), e ); } if ( result == null ) { continue; } populateCompileArtifactMap( compileArtifactMap, getCompileArtifacts( result ) ); if ( getLog().isDebugEnabled() ) { StringBuffer sb = new StringBuffer(); sb.append( "Compiled artifacts for " ); sb.append( subProject.getGroupId() ).append( ":" ); sb.append( subProject.getArtifactId() ).append( ":" ); sb.append( subProject.getVersion() ).append( '\n' ); for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); sb.append( a.getFile() ).append( '\n' ); } getLog().debug( sb.toString() ); } } } } } catch ( InvalidDependencyVersionException e ) { throw new MavenReportException( e.getMessage(), e ); } } for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); classpathElements.add( a.getFile() ); } return StringUtils.join( classpathElements.iterator(), File.pathSeparator ); } /** * TODO remove the part with ToolchainManager lookup once we depend on * 3.0.9 (have it as prerequisite). Define as regular component field then. * * @return Toolchain instance */ private Toolchain getToolchain() { Toolchain tc = null; if ( toolchainManager != null ) { tc = toolchainManager.getToolchainFromBuildContext( "jdk", session ); } return tc; } /** * Method to put the artifacts in the hashmap. * * @param compileArtifactMap the hashmap that will contain the artifacts * @param artifactList the list of artifacts that will be put in the map * @throws MavenReportException if any */ private void populateCompileArtifactMap( Map compileArtifactMap, Collection artifactList ) throws MavenReportException { if ( artifactList != null ) { for ( Iterator i = artifactList.iterator(); i.hasNext(); ) { Artifact newArtifact = (Artifact) i.next(); File file = newArtifact.getFile(); if ( file == null ) { throw new MavenReportException( "Error in plugin descriptor - " + "dependency was not resolved for artifact: " + newArtifact.getGroupId() + ":" + newArtifact.getArtifactId() + ":" + newArtifact.getVersion() ); } if ( compileArtifactMap.get( newArtifact.getDependencyConflictId() ) != null ) { Artifact oldArtifact = (Artifact) compileArtifactMap.get( newArtifact.getDependencyConflictId() ); ArtifactVersion oldVersion = new DefaultArtifactVersion( oldArtifact.getVersion() ); ArtifactVersion newVersion = new DefaultArtifactVersion( newArtifact.getVersion() ); if ( newVersion.compareTo( oldVersion ) > 0 ) { compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); } } else { compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); } } } } /** * Method that sets the bottom text that will be displayed on the bottom of the * javadocs. * * @return a String that contains the text that will be displayed at the bottom of the javadoc */ private String getBottomText() { int actualYear = Calendar.getInstance().get( Calendar.YEAR ); String year = String.valueOf( actualYear ); String inceptionYear = project.getInceptionYear(); String theBottom = StringUtils.replace( this.bottom, "{currentYear}", year ); if ( inceptionYear != null ) { if ( inceptionYear.equals( year ) ) { theBottom = StringUtils.replace( theBottom, "{inceptionYear}-", "" ); } else { theBottom = StringUtils.replace( theBottom, "{inceptionYear}", inceptionYear ); } } else { theBottom = StringUtils.replace( theBottom, "{inceptionYear}-", "" ); } if ( project.getOrganization() == null ) { theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); } else { if ( StringUtils.isNotEmpty( project.getOrganization().getName() ) ) { if ( StringUtils.isNotEmpty( project.getOrganization().getUrl() ) ) { theBottom = StringUtils.replace( theBottom, "{organizationName}", "<a href=\"" + project.getOrganization().getUrl() + "\">" + project.getOrganization().getName() + "</a>" ); } else { theBottom = StringUtils.replace( theBottom, "{organizationName}", project.getOrganization().getName() ); } } else { theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); } } return theBottom; } /** * Method to get the stylesheet path file to be used by the Javadoc Tool. * <br/> * If the {@link #stylesheetfile} is empty, return the file as String definded by {@link #stylesheet} value. * <br/> * If the {@link #stylesheetfile} is defined, return the file as String. * <br/> * Note: since 2.6, the {@link #stylesheetfile} could be a path from a resource in the project source * directories (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies. * * @param javadocOutputDirectory the output directory * @return the stylesheet file absolute path as String. * @see #getResource(List, String) */ private String getStylesheetFile( final File javadocOutputDirectory ) { if ( StringUtils.isEmpty( stylesheetfile ) ) { if ( "java".equalsIgnoreCase( stylesheet ) ) { // use the default Javadoc tool stylesheet return null; } // maven, see #copyDefaultStylesheet(File) return new File( javadocOutputDirectory, DEFAULT_CSS_NAME ).getAbsolutePath(); } if ( new File( stylesheetfile ).exists() ) { return new File( stylesheetfile ).getAbsolutePath(); } return getResource( new File( javadocOutputDirectory, DEFAULT_CSS_NAME ), stylesheetfile ); } /** * Method to get the help file to be used by the Javadoc Tool. * <br/> * Since 2.6, the {@link #helpfile} could be a path from a resource in the project source * directories (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies. * * @param javadocOutputDirectory the output directory. * @return the help file absolute path as String. * @since 2.6 * @see #getResource(File, String) */ private String getHelpFile( final File javadocOutputDirectory ) { if ( StringUtils.isEmpty( helpfile ) ) { return null; } if ( new File( helpfile ).exists() ) { return new File( helpfile ).getAbsolutePath(); } return getResource( new File( javadocOutputDirectory, "help-doc.html" ), helpfile ); } /** * Method to get the access level for the classes and members to be shown in the generated javadoc. * If the specified access level is not public, protected, package or private, the access level * is set to protected. * * @return the access level */ private String getAccessLevel() { String accessLevel; if ( "public".equalsIgnoreCase( show ) || "protected".equalsIgnoreCase( show ) || "package".equalsIgnoreCase( show ) || "private".equalsIgnoreCase( show ) ) { accessLevel = "-" + show; } else { if ( getLog().isErrorEnabled() ) { getLog().error( "Unrecognized access level to show '" + show + "'. Defaulting to protected." ); } accessLevel = "-protected"; } return accessLevel; } /** * Method to get the path of the bootclass artifacts used in the <code>-bootclasspath</code> option. * * @return a string that contains bootclass path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getBootclassPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( bootclasspathArtifacts != null ) { List bootclassPath = new ArrayList(); for ( int i = 0; i < bootclasspathArtifacts.length; i++ ) { BootclasspathArtifact aBootclasspathArtifact = bootclasspathArtifacts[i]; if ( ( StringUtils.isNotEmpty( aBootclasspathArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aBootclasspathArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aBootclasspathArtifact.getVersion() ) ) ) { bootclassPath.addAll( getArtifactsAbsolutePath( aBootclasspathArtifact ) ); } } bootclassPath = JavadocUtil.pruneFiles( bootclassPath ); path.append( StringUtils.join( bootclassPath.iterator(), File.pathSeparator ) ); } if ( StringUtils.isNotEmpty( bootclasspath ) ) { path.append( JavadocUtil.unifyPathSeparator( bootclasspath ) ); } return path.toString(); } /** * Method to get the path of the doclet artifacts used in the <code>-docletpath</code> option. * * Either docletArtifact or doclectArtifacts can be defined and used, not both, docletArtifact * takes precedence over doclectArtifacts. docletPath is always appended to any result path * definition. * * @return a string that contains doclet path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getDocletPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( !isDocletArtifactEmpty( docletArtifact ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( docletArtifact ).iterator(), File.pathSeparator ) ); } else if ( docletArtifacts != null ) { for ( int i = 0; i < docletArtifacts.length; i++ ) { if ( !isDocletArtifactEmpty( docletArtifacts[i] ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( docletArtifacts[i] ).iterator(), File.pathSeparator ) ); if ( i < docletArtifacts.length - 1 ) { path.append( File.pathSeparator ); } } } } if ( !StringUtils.isEmpty( docletPath ) ) { path.append( JavadocUtil.unifyPathSeparator( docletPath ) ); } if ( StringUtils.isEmpty( path.toString() ) && getLog().isWarnEnabled() ) { getLog().warn( "No docletpath option was found. Please review <docletpath/> or <docletArtifact/>" + " or <doclets/>." ); } return path.toString(); } /** * Verify if a doclet artifact is empty or not * * @param aDocletArtifact could be null * @return <code>true</code> if aDocletArtifact or the groupId/artifactId/version of the doclet artifact is null, * <code>false</code> otherwise. */ private boolean isDocletArtifactEmpty( DocletArtifact aDocletArtifact ) { if ( aDocletArtifact == null ) { return true; } return StringUtils.isEmpty( aDocletArtifact.getGroupId() ) && StringUtils.isEmpty( aDocletArtifact.getArtifactId() ) && StringUtils.isEmpty( aDocletArtifact.getVersion() ); } /** * Method to get the path of the taglet artifacts used in the <code>-tagletpath</code> option. * * @return a string that contains taglet path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getTagletPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( ( tagletArtifact != null ) && ( StringUtils.isNotEmpty( tagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( tagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( tagletArtifact.getVersion() ) ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( tagletArtifact ).iterator(), File.pathSeparator ) ); } if ( tagletArtifacts != null ) { List tagletsPath = new ArrayList(); for ( int i = 0; i < tagletArtifacts.length; i++ ) { TagletArtifact aTagletArtifact = tagletArtifacts[i]; if ( ( StringUtils.isNotEmpty( aTagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getVersion() ) ) ) { tagletsPath.addAll( getArtifactsAbsolutePath( aTagletArtifact ) ); } } tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); path.append( StringUtils.join( tagletsPath.iterator(), File.pathSeparator ) ); } if ( taglets != null ) { List tagletsPath = new ArrayList(); for ( int i = 0; i < taglets.length; i++ ) { Taglet current = taglets[i]; if ( current == null ) { continue; } if ( ( current.getTagletArtifact() != null ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getGroupId() ) ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getArtifactId() ) ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getVersion() ) ) ) { tagletsPath.addAll( getArtifactsAbsolutePath( current.getTagletArtifact() ) ); tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); } else if ( StringUtils.isNotEmpty( current.getTagletpath() ) ) { tagletsPath.add( current.getTagletpath() ); tagletsPath = JavadocUtil.pruneDirs( project, tagletsPath ); } } path.append( StringUtils.join( tagletsPath.iterator(), File.pathSeparator ) ); } if ( StringUtils.isNotEmpty( tagletpath ) ) { path.append( JavadocUtil.unifyPathSeparator( tagletpath ) ); } return path.toString(); } /** * Return the Javadoc artifact path and its transitive dependencies path from the local repository * * @param javadocArtifact not null * @return a list of locale artifacts absolute path * @throws MavenReportException if any */ private List getArtifactsAbsolutePath( JavadocPathArtifact javadocArtifact ) throws MavenReportException { if ( ( StringUtils.isEmpty( javadocArtifact.getGroupId() ) ) && ( StringUtils.isEmpty( javadocArtifact.getArtifactId() ) ) && ( StringUtils.isEmpty( javadocArtifact.getVersion() ) ) ) { return Collections.EMPTY_LIST; } List path = new ArrayList(); try { Artifact artifact = createAndResolveArtifact( javadocArtifact ); path.add( artifact.getFile().getAbsolutePath() ); // Find its transitive dependencies in the local repo MavenProject artifactProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); Set dependencyArtifacts = artifactProject.createArtifacts( factory, null, null ); if ( !dependencyArtifacts.isEmpty() ) { ArtifactResolutionResult result = resolver.resolveTransitively( dependencyArtifacts, artifactProject.getArtifact(), artifactProject.getRemoteArtifactRepositories(), localRepository, artifactMetadataSource ); Set artifacts = result.getArtifacts(); Map compileArtifactMap = new HashMap(); populateCompileArtifactMap( compileArtifactMap, artifacts ); for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); path.add( a.getFile().getAbsolutePath() ); } } return path; } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + javadocArtifact, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + javadocArtifact, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + javadocArtifact, e ); } catch ( InvalidDependencyVersionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + javadocArtifact, e ); } } /** * creates an {@link Artifact} representing the configured {@link JavadocPathArtifact} and resolves it. * * @param javadocArtifact the {@link JavadocPathArtifact} to resolve * @return a resolved {@link Artifact} * @throws ArtifactResolutionException if the resolution of the artifact failed. * @throws ArtifactNotFoundException if the artifact hasn't been found. * @throws ProjectBuildingException if the artifact POM could not be build. */ private Artifact createAndResolveArtifact( JavadocPathArtifact javadocArtifact ) throws ArtifactResolutionException, ArtifactNotFoundException, ProjectBuildingException { Artifact artifact = factory.createProjectArtifact( javadocArtifact.getGroupId(), javadocArtifact.getArtifactId(), javadocArtifact.getVersion(), Artifact.SCOPE_COMPILE ); if ( artifact.getFile() == null ) { MavenProject pluginProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); artifact = pluginProject.getArtifact(); resolver.resolve( artifact, remoteRepositories, localRepository ); } return artifact; } /** * Method that adds/sets the java memory parameters in the command line execution. * * @param cmd the command line execution object where the argument will be added * @param arg the argument parameter name * @param memory the JVM memory value to be set * @see JavadocUtil#parseJavadocMemory(String) */ private void addMemoryArg( Commandline cmd, String arg, String memory ) { if ( StringUtils.isNotEmpty( memory ) ) { try { cmd.createArg().setValue( "-J" + arg + JavadocUtil.parseJavadocMemory( memory ) ); } catch ( IllegalArgumentException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Malformed memory pattern for '" + arg + memory + "'. Ignore this option." ); } } } } /** * Method that adds/sets the javadoc proxy parameters in the command line execution. * * @param cmd the command line execution object where the argument will be added */ private void addProxyArg( Commandline cmd ) { // backward compatible if ( StringUtils.isNotEmpty( proxyHost ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "The Javadoc plugin parameter 'proxyHost' is deprecated since 2.4. " + "Please configure an active proxy in your settings.xml." ); } cmd.createArg().setValue( "-J-DproxyHost=" + proxyHost ); if ( proxyPort > 0 ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "The Javadoc plugin parameter 'proxyPort' is deprecated since 2.4. " + "Please configure an active proxy in your settings.xml." ); } cmd.createArg().setValue( "-J-DproxyPort=" + proxyPort ); } } if ( settings == null || settings.getActiveProxy() == null ) { return; } Proxy activeProxy = settings.getActiveProxy(); String protocol = StringUtils.isNotEmpty( activeProxy.getProtocol() ) ? activeProxy.getProtocol() + "." : ""; if ( StringUtils.isNotEmpty( activeProxy.getHost() ) ) { cmd.createArg().setValue( "-J-D" + protocol + "proxySet=true" ); cmd.createArg().setValue( "-J-D" + protocol + "proxyHost=" + activeProxy.getHost() ); if ( activeProxy.getPort() > 0 ) { cmd.createArg().setValue( "-J-D" + protocol + "proxyPort=" + activeProxy.getPort() ); } if ( StringUtils.isNotEmpty( activeProxy.getNonProxyHosts() ) ) { cmd.createArg().setValue( "-J-D" + protocol + "nonProxyHosts=\"" + activeProxy.getNonProxyHosts() + "\"" ); } if ( StringUtils.isNotEmpty( activeProxy.getUsername() ) ) { cmd.createArg().setValue( "-J-Dhttp.proxyUser=\"" + activeProxy.getUsername() + "\"" ); if ( StringUtils.isNotEmpty( activeProxy.getPassword() ) ) { cmd.createArg().setValue( "-J-Dhttp.proxyPassword=\"" + activeProxy.getPassword() + "\"" ); } } } } /** * Get the path of the Javadoc tool executable depending the user entry or try to find it depending the OS * or the <code>java.home</code> system property or the <code>JAVA_HOME</code> environment variable. * * @return the path of the Javadoc tool * @throws IOException if not found */ private String getJavadocExecutable() throws IOException { Toolchain tc = getToolchain(); if ( tc != null ) { getLog().info( "Toolchain in javadoc-plugin: " + tc ); if ( javadocExecutable != null ) { getLog().warn( "Toolchains are ignored, 'javadocExecutable' parameter is set to " + javadocExecutable ); } else { javadocExecutable = tc.findTool( "javadoc" ); } } String javadocCommand = "javadoc" + ( SystemUtils.IS_OS_WINDOWS ? ".exe" : "" ); File javadocExe; // ---------------------------------------------------------------------- // The javadoc executable is defined by the user // ---------------------------------------------------------------------- if ( StringUtils.isNotEmpty( javadocExecutable ) ) { javadocExe = new File( javadocExecutable ); if ( javadocExe.isDirectory() ) { javadocExe = new File( javadocExe, javadocCommand ); } if ( SystemUtils.IS_OS_WINDOWS && javadocExe.getName().indexOf( '.' ) < 0 ) { javadocExe = new File( javadocExe.getPath() + ".exe" ); } if ( !javadocExe.isFile() ) { throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. Verify the <javadocExecutable/> parameter." ); } return javadocExe.getAbsolutePath(); } // ---------------------------------------------------------------------- // Try to find javadocExe from System.getProperty( "java.home" ) // By default, System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME // should be in the JDK_HOME // ---------------------------------------------------------------------- // For IBM's JDK 1.2 if ( SystemUtils.IS_OS_AIX ) { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "sh", javadocCommand ); } else if ( SystemUtils.IS_OS_MAC_OSX ) { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand ); } else { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "bin", javadocCommand ); } // ---------------------------------------------------------------------- // Try to find javadocExe from JAVA_HOME environment variable // ---------------------------------------------------------------------- if ( !javadocExe.exists() || !javadocExe.isFile() ) { Properties env = CommandLineUtils.getSystemEnvVars(); String javaHome = env.getProperty( "JAVA_HOME" ); if ( StringUtils.isEmpty( javaHome ) ) { throw new IOException( "The environment variable JAVA_HOME is not correctly set." ); } if ( ( !new File( javaHome ).exists() ) || ( !new File( javaHome ).isDirectory() ) ) { throw new IOException( "The environment variable JAVA_HOME=" + javaHome + " doesn't exist or is not a valid directory." ); } javadocExe = new File( env.getProperty( "JAVA_HOME" ) + File.separator + "bin", javadocCommand ); } if ( !javadocExe.exists() || !javadocExe.isFile() ) { throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable." ); } return javadocExe.getAbsolutePath(); } /** * Set a new value for <code>fJavadocVersion</code> * * @param jExecutable not null * @throws MavenReportException if not found * @see JavadocUtil#getJavadocVersion(File) */ private void setFJavadocVersion( File jExecutable ) throws MavenReportException { float jVersion; try { jVersion = JavadocUtil.getJavadocVersion( jExecutable ); } catch ( IOException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } catch ( CommandLineException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java the version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } catch ( IllegalArgumentException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java the version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } if ( StringUtils.isNotEmpty( javadocVersion ) ) { try { fJavadocVersion = Float.parseFloat( javadocVersion ); } catch ( NumberFormatException e ) { throw new MavenReportException( "Unable to parse javadoc version: " + e.getMessage(), e ); } if ( fJavadocVersion != jVersion && getLog().isWarnEnabled() ) { getLog().warn( "Are you sure about the <javadocVersion/> parameter? It seems to be " + jVersion ); } } else { fJavadocVersion = jVersion; } } /** * Is the Javadoc version at least the requested version. * * @param requiredVersion the required version, for example 1.5f * @return <code>true</code> if the javadoc version is equal or greater than the * required version */ private boolean isJavaDocVersionAtLeast( float requiredVersion ) { return fJavadocVersion >= requiredVersion; } /** * Convenience method to add an argument to the <code>command line</code> * conditionally based on the given flag. * * @param arguments a list of arguments, not null * @param b the flag which controls if the argument is added or not. * @param value the argument value to be added. */ private void addArgIf( List arguments, boolean b, String value ) { if ( b ) { arguments.add( value ); } } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param b the flag which controls if the argument is added or not. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIf(java.util.List,boolean,String) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIf( List arguments, boolean b, String value, float requiredJavaVersion ) { if ( b ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIf( arguments, b, value ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( value + " option is not supported on Java version < " + requiredJavaVersion + ". Ignore this option." ); } } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @see #addArgIfNotEmpty(java.util.List,String,String,boolean) */ private void addArgIfNotEmpty( List arguments, String key, String value ) { addArgIfNotEmpty( arguments, key, value, false ); } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line * @param splitValue if <code>true</code> given value will be tokenized by comma * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIfNotEmpty(List, String, String, boolean, boolean) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, boolean splitValue, float requiredJavaVersion ) { if ( StringUtils.isNotEmpty( value ) ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIfNotEmpty( arguments, key, value, repeatKey, splitValue ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion + ". Ignore this option." ); } } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line * @param splitValue if <code>true</code> given value will be tokenized by comma */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, boolean splitValue ) { if ( StringUtils.isNotEmpty( value ) ) { if ( StringUtils.isNotEmpty( key ) ) { arguments.add( key ); } if ( splitValue ) { StringTokenizer token = new StringTokenizer( value, "," ); while ( token.hasMoreTokens() ) { String current = token.nextToken().trim(); if ( StringUtils.isNotEmpty( current ) ) { arguments.add( current ); if ( token.hasMoreTokens() && repeatKey ) { arguments.add( key ); } } } } else { arguments.add( value ); } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey ) { addArgIfNotEmpty( arguments, key, value, repeatKey, true ); } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIfNotEmpty(java.util.List, String, String, float, boolean) */ private void addArgIfNotEmpty( List arguments, String key, String value, float requiredJavaVersion ) { addArgIfNotEmpty( arguments, key, value, requiredJavaVersion, false ); } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @param repeatKey repeat or not the key in the command line * @see #addArgIfNotEmpty(java.util.List,String,String) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIfNotEmpty( List arguments, String key, String value, float requiredJavaVersion, boolean repeatKey ) { if ( StringUtils.isNotEmpty( value ) ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIfNotEmpty( arguments, key, value, repeatKey ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion ); } } } } /** * Convenience method to process {@link #offlineLinks} values as individual <code>-linkoffline</code> * javadoc options. * <br/> * If {@link #detectOfflineLinks}, try to add javadoc apidocs according Maven conventions for all modules given * in the project. * * @param arguments a list of arguments, not null * @throws MavenReportException if any * @see #offlineLinks * @see #getModulesLinks() * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package-list">package-list spec</a> */ private void addLinkofflineArguments( List arguments ) throws MavenReportException { List offlineLinksList = ( offlineLinks != null ? new ArrayList( Arrays.asList( offlineLinks ) ) : new ArrayList() ); offlineLinksList.addAll( getModulesLinks() ); if ( offlineLinksList != null ) { for ( int i = 0; i < offlineLinksList.size(); i++ ) { OfflineLink offlineLink = (OfflineLink) offlineLinksList.get( i ); String url = offlineLink.getUrl(); if ( StringUtils.isEmpty( url ) ) { continue; } url = cleanUrl( url ); String location = offlineLink.getLocation(); if ( StringUtils.isEmpty( location ) ) { continue; } if ( isValidJavadocLink( location ) ) { addArgIfNotEmpty( arguments, "-linkoffline", JavadocUtil.quotedPathArgument( url ) + " " + JavadocUtil.quotedPathArgument( location ), true ); } } } } /** * Convenience method to process {@link #links} values as individual <code>-link</code> javadoc options. * If {@link #detectLinks}, try to add javadoc apidocs according Maven conventions for all dependencies given * in the project. * <br/> * According the Javadoc documentation, all defined link should have <code>${link}/package-list</code> fetchable. * <br/> * <b>Note</b>: when a link is not fetchable: * <ul> * <li>Javadoc 1.4 and less throw an exception</li> * <li>Javadoc 1.5 and more display a warning</li> * </ul> * * @param arguments a list of arguments, not null * @see #detectLinks * @see #getDependenciesLinks() * @see JavadocUtil#fetchURL(Settings, URL) * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package-list">package-list spec</a> */ private void addLinkArguments( List arguments ) { if ( links == null ) { links = new ArrayList(); } String javaApiLink = getDefaultJavadocApiLink(); if ( javaApiLink != null ) { links.add( javaApiLink ); } links.addAll( getDependenciesLinks() ); for ( int i = 0; i < links.size(); i++ ) { String link = (String) links.get( i ); if ( StringUtils.isEmpty( link ) ) { continue; } while ( link.endsWith( "/" ) ) { link = link.substring( 0, link.lastIndexOf( "/" ) ); } if ( isValidJavadocLink( link ) ) { addArgIfNotEmpty( arguments, "-link", JavadocUtil.quotedPathArgument( link ), true ); } } } /** * Coppy all resources to the output directory * * @param javadocOutputDirectory not null * @throws MavenReportException if any * @see #copyDefaultStylesheet(File) * @see #copyJavadocResources(File) * @see #copyAdditionalJavadocResources(File) */ private void copyAllResources( File javadocOutputDirectory ) throws MavenReportException { // ---------------------------------------------------------------------- // Copy default resources // ---------------------------------------------------------------------- try { copyDefaultStylesheet( javadocOutputDirectory ); } catch ( IOException e ) { throw new MavenReportException( "Unable to copy default stylesheet: " + e.getMessage(), e ); } // ---------------------------------------------------------------------- // Copy javadoc resources // ---------------------------------------------------------------------- if ( docfilessubdirs ) { /* * Workaround since -docfilessubdirs doesn't seem to be used correctly by the javadoc tool * (see other note about -sourcepath). Take care of the -excludedocfilessubdir option. */ try { copyJavadocResources( javadocOutputDirectory ); } catch ( IOException e ) { throw new MavenReportException( "Unable to copy javadoc resources: " + e.getMessage(), e ); } } // ---------------------------------------------------------------------- // Copy additional javadoc resources in artifacts // ---------------------------------------------------------------------- copyAdditionalJavadocResources( javadocOutputDirectory ); } /** * Copies the {@link #DEFAULT_CSS_NAME} css file from the current class * loader to the <code>outputDirectory</code> only if {@link #stylesheetfile} is empty and * {@link #stylesheet} is equals to <code>maven</code>. * * @param anOutputDirectory the output directory * @throws java.io.IOException if any * @see #DEFAULT_CSS_NAME * @see JavadocUtil#copyResource(File, URL) */ private void copyDefaultStylesheet( File anOutputDirectory ) throws IOException { if ( StringUtils.isNotEmpty( stylesheetfile ) ) { return; } if ( !stylesheet.equalsIgnoreCase( "maven" ) ) { return; } URL url = getClass().getClassLoader().getResource( RESOURCE_CSS_DIR + "/" + DEFAULT_CSS_NAME ); File outFile = new File( anOutputDirectory, DEFAULT_CSS_NAME ); JavadocUtil.copyResource( url, outFile ); } /** * Method that copy all <code>doc-files</code> directories from <code>javadocDirectory</code> of * the current projet or of the projects in the reactor to the <code>outputDirectory</code>. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.2.html#docfiles">Reference * Guide, Copies new "doc-files" directory for holding images and examples</a> * @see #docfilessubdirs * * @param anOutputDirectory the output directory * @throws java.io.IOException if any */ private void copyJavadocResources( File anOutputDirectory ) throws IOException { if ( anOutputDirectory == null || !anOutputDirectory.exists() ) { throw new IOException( "The outputDirectory " + anOutputDirectory + " doesn't exists." ); } if ( getJavadocDirectory() != null ) { JavadocUtil.copyJavadocResources( anOutputDirectory, getJavadocDirectory(), excludedocfilessubdir ); } if ( isAggregator() && project.isExecutionRoot() ) { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getJavadocDirectory().getAbsolutePath() ); File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); JavadocUtil.copyJavadocResources( anOutputDirectory, javadocDir, excludedocfilessubdir ); } } } } /** * Method that copy additional Javadoc resources from given artifacts. * * @see #resourcesArtifacts * @param anOutputDirectory the output directory * @throws MavenReportException if any */ private void copyAdditionalJavadocResources( File anOutputDirectory ) throws MavenReportException { if ( resourcesArtifacts == null || resourcesArtifacts.length == 0 ) { return; } UnArchiver unArchiver; try { unArchiver = archiverManager.getUnArchiver( "jar" ); } catch ( NoSuchArchiverException e ) { throw new MavenReportException( "Unable to extract resources artifact. " + "No archiver for 'jar' available.", e ); } for ( int i = 0; i < resourcesArtifacts.length; i++ ) { ResourcesArtifact item = resourcesArtifacts[i]; Artifact artifact; try { artifact = createAndResolveArtifact( item ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + item, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + item, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + item, e ); } unArchiver.setSourceFile( artifact.getFile() ); unArchiver.setDestDirectory( anOutputDirectory ); // remove the META-INF directory from resource artifact IncludeExcludeFileSelector[] selectors = new IncludeExcludeFileSelector[] { new IncludeExcludeFileSelector() }; selectors[0].setExcludes( new String[] { "META-INF/**" } ); unArchiver.setFileSelectors( selectors ); getLog().info( "Extracting contents of resources artifact: " + artifact.getArtifactId() ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MavenReportException( "Extraction of resources failed. Artifact that failed was: " + artifact.getArtifactId(), e ); } } } /** * @param sourcePaths could be null * @param files not null * @return the list of package names for files in the sourcePaths */ private List getPackageNames( List sourcePaths, List files ) { return getPackageNamesOrFilesWithUnnamedPackages( sourcePaths, files, true ); } /** * @param sourcePaths could be null * @param files not null * @return a list files with unnamed package names for files in the sourecPaths */ private List getFilesWithUnnamedPackages( List sourcePaths, List files ) { return getPackageNamesOrFilesWithUnnamedPackages( sourcePaths, files, false ); } /** * @param sourcePaths not null, containing absolute and relative paths * @param files not null, containing list of quoted files * @param onlyPackageName boolean for only package name * @return a list of package names or files with unnamed package names, depending the value of the unnamed flag * @see #getFiles(List) * @see #getSourcePaths() */ private List getPackageNamesOrFilesWithUnnamedPackages( List sourcePaths, List files, boolean onlyPackageName ) { List returnList = new ArrayList(); if ( !StringUtils.isEmpty( sourcepath ) ) { return returnList; } for ( Iterator it = files.iterator(); it.hasNext(); ) { String currentFile = (String) it.next(); currentFile = currentFile.replace( '\\', '/' ); for ( Iterator it2 = sourcePaths.iterator(); it2.hasNext(); ) { String currentSourcePath = (String) it2.next(); currentSourcePath = currentSourcePath.replace( '\\', '/' ); if ( !currentSourcePath.endsWith( "/" ) ) { currentSourcePath += "/"; } if ( currentFile.indexOf( currentSourcePath ) != -1 ) { String packagename = currentFile.substring( currentSourcePath.length() + 1 ); /* * Remove the miscellaneous files * http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ if ( packagename.indexOf( "doc-files" ) != -1 ) { continue; } if ( onlyPackageName && packagename.lastIndexOf( "/" ) != -1 ) { packagename = packagename.substring( 0, packagename.lastIndexOf( "/" ) ); packagename = packagename.replace( '/', '.' ); if ( !returnList.contains( packagename ) ) { returnList.add( packagename ); } } if ( !onlyPackageName && packagename.lastIndexOf( "/" ) == -1 ) { returnList.add( currentFile ); } } } } return returnList; } /** * Generate an <code>options</code> file for all options and arguments and add the <code>@options</code> in the * command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files</a> * * @param cmd not null * @param arguments not null * @param javadocOutputDirectory not null * @throws MavenReportException if any * @see #OPTIONS_FILE_NAME */ private void addCommandLineOptions( Commandline cmd, List arguments, File javadocOutputDirectory ) throws MavenReportException { File optionsFile = new File( javadocOutputDirectory, OPTIONS_FILE_NAME ); StringBuffer options = new StringBuffer(); options.append( StringUtils.join( arguments.toArray( new String[0] ), SystemUtils.LINE_SEPARATOR ) ); try { FileUtils.fileWrite( optionsFile.getAbsolutePath(), options.toString() ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + optionsFile.getName() + "' temporary file for command execution", e ); } cmd.createArg().setValue( "@" + OPTIONS_FILE_NAME ); } /** * Generate a file called <code>argfile</code> (or <code>files</code>, depending the JDK) to hold files and add * the <code>@argfile</code> (or <code>@file</code>, depending the JDK) in the command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files * </a> * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#runningjavadoc"> * What s New in Javadoc 1.4 * </a> * * @param cmd not null * @param javadocOutputDirectory not null * @param files not null * @throws MavenReportException if any * @see #isJavaDocVersionAtLeast(float) * @see #ARGFILE_FILE_NAME * @see #FILES_FILE_NAME */ private void addCommandLineArgFile( Commandline cmd, File javadocOutputDirectory, List files ) throws MavenReportException { File argfileFile; if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { argfileFile = new File( javadocOutputDirectory, ARGFILE_FILE_NAME ); } else { argfileFile = new File( javadocOutputDirectory, FILES_FILE_NAME ); } try { FileUtils.fileWrite( argfileFile.getAbsolutePath(), StringUtils.join( files.iterator(), SystemUtils.LINE_SEPARATOR ) ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + argfileFile.getName() + "' temporary file for command execution", e ); } if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { cmd.createArg().setValue( "@" + ARGFILE_FILE_NAME ); } else { cmd.createArg().setValue( "@" + FILES_FILE_NAME ); } } /** * Generate a file called <code>packages</code> to hold all package names and add the <code>@packages</code> in * the command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files</a> * * @param cmd not null * @param javadocOutputDirectory not null * @param packageNames not null * @throws MavenReportException if any * @see #PACKAGES_FILE_NAME */ private void addCommandLinePackages( Commandline cmd, File javadocOutputDirectory, List packageNames ) throws MavenReportException { File packagesFile = new File( javadocOutputDirectory, PACKAGES_FILE_NAME ); try { FileUtils.fileWrite( packagesFile.getAbsolutePath(), StringUtils.join( packageNames.toArray( new String[0] ), SystemUtils.LINE_SEPARATOR ) ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + packagesFile.getName() + "' temporary file for command execution", e ); } cmd.createArg().setValue( "@" + PACKAGES_FILE_NAME ); } /** * Checks for the validity of the Javadoc options used by the user. * * @throws MavenReportException if error */ private void validateJavadocOptions() throws MavenReportException { // encoding if ( StringUtils.isNotEmpty( getEncoding() ) && !JavadocUtil.validateEncoding( getEncoding() ) ) { throw new MavenReportException( "Unsupported option <encoding/> '" + getEncoding() + "'" ); } // locale if ( StringUtils.isNotEmpty( this.locale ) ) { StringTokenizer tokenizer = new StringTokenizer( this.locale, "_" ); final int maxTokens = 3; if ( tokenizer.countTokens() > maxTokens ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant." ); } Locale localeObject = null; if ( tokenizer.hasMoreTokens() ) { String language = tokenizer.nextToken().toLowerCase( Locale.ENGLISH ); if ( !Arrays.asList( Locale.getISOLanguages() ).contains( language ) ) { throw new MavenReportException( "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'" ); } localeObject = new Locale( language ); if ( tokenizer.hasMoreTokens() ) { String country = tokenizer.nextToken().toUpperCase( Locale.ENGLISH ); if ( !Arrays.asList( Locale.getISOCountries() ).contains( country ) ) { throw new MavenReportException( "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'" ); } localeObject = new Locale( language, country ); if ( tokenizer.hasMoreTokens() ) { String variant = tokenizer.nextToken(); localeObject = new Locale( language, country, variant ); } } } if ( localeObject == null ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant." ); } this.locale = localeObject.toString(); final List availableLocalesList = Arrays.asList( Locale.getAvailableLocales() ); if ( StringUtils.isNotEmpty( localeObject.getVariant() ) && !availableLocalesList.contains( localeObject ) ) { StringBuffer sb = new StringBuffer(); sb.append( "Unsupported option <locale/> with variant '" ).append( this.locale ); sb.append( "'" ); localeObject = new Locale( localeObject.getLanguage(), localeObject.getCountry() ); this.locale = localeObject.toString(); sb.append( ", trying to use <locale/> without variant, i.e. '" ).append( this.locale ).append( "'" ); if ( getLog().isWarnEnabled() ) { getLog().warn( sb.toString() ); } } if ( !availableLocalesList.contains( localeObject ) ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "'" ); } } } /** * Checks for the validity of the Standard Doclet options. * <br/> * For example, throw an exception if &lt;nohelp/&gt; and &lt;helpfile/&gt; options are used together. * * @throws MavenReportException if error or conflict found */ private void validateStandardDocletOptions() throws MavenReportException { // docencoding if ( StringUtils.isNotEmpty( getDocencoding() ) && !JavadocUtil.validateEncoding( getDocencoding() ) ) { throw new MavenReportException( "Unsupported option <docencoding/> '" + getDocencoding() + "'" ); } // charset if ( StringUtils.isNotEmpty( getCharset() ) && !JavadocUtil.validateEncoding( getCharset() ) ) { throw new MavenReportException( "Unsupported option <charset/> '" + getCharset() + "'" ); } // helpfile if ( StringUtils.isNotEmpty( helpfile ) && nohelp ) { throw new MavenReportException( "Option <nohelp/> conflicts with <helpfile/>" ); } // overview if ( ( getOverview() != null ) && nooverview ) { throw new MavenReportException( "Option <nooverview/> conflicts with <overview/>" ); } // index if ( splitindex && noindex ) { throw new MavenReportException( "Option <noindex/> conflicts with <splitindex/>" ); } // stylesheet if ( StringUtils.isNotEmpty( stylesheet ) && !( stylesheet.equalsIgnoreCase( "maven" ) || stylesheet.equalsIgnoreCase( "java" ) ) ) { throw new MavenReportException( "Option <stylesheet/> supports only \"maven\" or \"java\" value." ); } // default java api links if ( javaApiLinks == null || javaApiLinks.size() == 0 ) { javaApiLinks = DEFAULT_JAVA_API_LINKS; } } /** * This method is checking to see if the artifacts that can't be resolved are all * part of this reactor. This is done to prevent a chicken or egg scenario with * fresh projects. See MJAVADOC-116 for more info. * * @param dependencyArtifacts the sibling projects in the reactor * @param missing the artifacts that can't be found * @return true if ALL missing artifacts are found in the reactor. * @see DefaultPluginManager#checkRequiredMavenVersion( plugin, localRepository, remoteRepositories ) */ private boolean checkMissingArtifactsInReactor( Collection dependencyArtifacts, Collection missing ) { Set foundInReactor = new HashSet(); Iterator iter = missing.iterator(); while ( iter.hasNext() ) { Artifact mArtifact = (Artifact) iter.next(); Iterator pIter = reactorProjects.iterator(); while ( pIter.hasNext() ) { MavenProject p = (MavenProject) pIter.next(); if ( p.getArtifactId().equals( mArtifact.getArtifactId() ) && p.getGroupId().equals( mArtifact.getGroupId() ) && p.getVersion().equals( mArtifact.getVersion() ) ) { getLog().warn( "The dependency: [" + p.getId() + "] can't be resolved but has been found in the reactor (probably snapshots).\n" + "This dependency has been excluded from the Javadoc classpath. " + "You should rerun javadoc after executing mvn install." ); // found it, move on. foundInReactor.add( p ); break; } } } // if all of them have been found, we can continue. return foundInReactor.size() == missing.size(); } /** * Add Standard Javadoc Options. * <br/> * The <a href="package-summary.html#Standard_Javadoc_Options">package documentation</a> details the * Standard Javadoc Options wrapped by this Plugin. * * @param arguments not null * @param sourcePaths not null * @throws MavenReportException if any * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#javadocoptions">http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#javadocoptions</a> */ private void addJavadocOptions( List arguments, List sourcePaths ) throws MavenReportException { validateJavadocOptions(); // see com.sun.tools.javadoc.Start#parseAndExecute(String argv[]) addArgIfNotEmpty( arguments, "-locale", JavadocUtil.quotedArgument( this.locale ) ); // all options in alphabetical order if ( old && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Javadoc 1.4+ doesn't support the -1.1 switch anymore. Ignore this option." ); } } else { addArgIf( arguments, old, "-1.1" ); } addArgIfNotEmpty( arguments, "-bootclasspath", JavadocUtil.quotedPathArgument( getBootclassPath() ) ); if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_5 ); } addArgIfNotEmpty( arguments, "-classpath", JavadocUtil.quotedPathArgument( getClasspath() ) ); if ( StringUtils.isNotEmpty( doclet ) ) { addArgIfNotEmpty( arguments, "-doclet", JavadocUtil.quotedArgument( doclet ) ); addArgIfNotEmpty( arguments, "-docletpath", JavadocUtil.quotedPathArgument( getDocletPath() ) ); } if ( StringUtils.isEmpty( encoding ) ) { getLog().warn( "Source files encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!" ); } addArgIfNotEmpty( arguments, "-encoding", JavadocUtil.quotedArgument( getEncoding() ) ); addArgIfNotEmpty( arguments, "-exclude", getExcludedPackages( sourcePaths ), SINCE_JAVADOC_1_4 ); addArgIfNotEmpty( arguments, "-extdirs", JavadocUtil.quotedPathArgument( JavadocUtil.unifyPathSeparator( extdirs ) ) ); if ( ( getOverview() != null ) && ( getOverview().exists() ) ) { addArgIfNotEmpty( arguments, "-overview", JavadocUtil.quotedPathArgument( getOverview().getAbsolutePath() ) ); } arguments.add( getAccessLevel() ); if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_5 ); } addArgIfNotEmpty( arguments, "-source", JavadocUtil.quotedArgument( source ), SINCE_JAVADOC_1_4 ); if ( ( StringUtils.isEmpty( sourcepath ) ) && ( StringUtils.isNotEmpty( subpackages ) ) ) { sourcepath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); } addArgIfNotEmpty( arguments, "-sourcepath", JavadocUtil.quotedPathArgument( getSourcePath( sourcePaths ) ) ); if ( StringUtils.isNotEmpty( sourcepath ) && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_5 ); } addArgIf( arguments, verbose, "-verbose" ); addArgIfNotEmpty( arguments, null, additionalparam ); } /** * Add Standard Doclet Options. * <br/> * The <a href="package-summary.html#Standard_Doclet_Options">package documentation</a> details the * Standard Doclet Options wrapped by this Plugin. * * @param javadocOutputDirectory not null * @param arguments not null * @throws MavenReportException if any * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard"> * http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard</a> */ private void addStandardDocletOptions( File javadocOutputDirectory, List arguments ) throws MavenReportException { validateStandardDocletOptions(); // all options in alphabetical order addArgIf( arguments, author, "-author" ); addArgIfNotEmpty( arguments, "-bottom", JavadocUtil.quotedArgument( getBottomText() ), false, false ); if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-charset", JavadocUtil.quotedArgument( getCharset() ) ); addArgIfNotEmpty( arguments, "-d", JavadocUtil.quotedPathArgument( javadocOutputDirectory.toString() ) ); addArgIfNotEmpty( arguments, "-docencoding", JavadocUtil.quotedArgument( getDocencoding() ) ); addArgIf( arguments, docfilessubdirs, "-docfilessubdirs", SINCE_JAVADOC_1_4 ); addArgIfNotEmpty( arguments, "-doctitle", JavadocUtil.quotedArgument( getDoctitle() ), false, false ); if ( docfilessubdirs ) { addArgIfNotEmpty( arguments, "-excludedocfilessubdir", JavadocUtil.quotedPathArgument( excludedocfilessubdir ), SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-footer", JavadocUtil.quotedArgument( footer ), false, false ); addGroups( arguments ); addArgIfNotEmpty( arguments, "-header", JavadocUtil.quotedArgument( header ), false, false ); addArgIfNotEmpty( arguments, "-helpfile", JavadocUtil.quotedPathArgument( getHelpFile( javadocOutputDirectory ) ) ); addArgIf( arguments, keywords, "-keywords", SINCE_JAVADOC_1_4_2 ); if ( !isOffline ) { addLinkArguments( arguments ); } addLinkofflineArguments( arguments ); addArgIf( arguments, linksource, "-linksource", SINCE_JAVADOC_1_4 ); if ( sourcetab > 0 ) { if ( fJavadocVersion == SINCE_JAVADOC_1_4_2 ) { addArgIfNotEmpty( arguments, "-linksourcetab", String.valueOf( sourcetab ) ); } addArgIfNotEmpty( arguments, "-sourcetab", String.valueOf( sourcetab ), SINCE_JAVADOC_1_5 ); } addArgIf( arguments, nocomment, "-nocomment", SINCE_JAVADOC_1_4 ); addArgIf( arguments, nodeprecated, "-nodeprecated" ); addArgIf( arguments, nodeprecatedlist, "-nodeprecatedlist" ); addArgIf( arguments, nohelp, "-nohelp" ); addArgIf( arguments, noindex, "-noindex" ); addArgIf( arguments, nonavbar, "-nonavbar" ); addArgIf( arguments, nooverview, "-nooverview" ); addArgIfNotEmpty( arguments, "-noqualifier", JavadocUtil.quotedArgument( noqualifier ), SINCE_JAVADOC_1_4 ); addArgIf( arguments, nosince, "-nosince" ); addArgIf( arguments, notimestamp, "-notimestamp", SINCE_JAVADOC_1_5 ); addArgIf( arguments, notree, "-notree" ); addArgIfNotEmpty( arguments, "-packagesheader", JavadocUtil.quotedArgument( packagesheader ), SINCE_JAVADOC_1_4_2 ); if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) // Sun bug: 4714350 { addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_4 ); } addArgIf( arguments, serialwarn, "-serialwarn" ); addArgIf( arguments, splitindex, "-splitindex" ); addArgIfNotEmpty( arguments, "-stylesheetfile", JavadocUtil.quotedPathArgument( getStylesheetFile( javadocOutputDirectory ) ) ); if ( StringUtils.isNotEmpty( sourcepath ) && !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglet ), SINCE_JAVADOC_1_4 ); addTaglets( arguments ); addTagletsFromTagletArtifacts( arguments ); addArgIfNotEmpty( arguments, "-tagletpath", JavadocUtil.quotedPathArgument( getTagletPath() ), SINCE_JAVADOC_1_4 ); addTags( arguments ); addArgIfNotEmpty( arguments, "-top", JavadocUtil.quotedArgument( top ), false, false, SINCE_JAVADOC_1_6 ); addArgIf( arguments, use, "-use" ); addArgIf( arguments, version, "-version" ); addArgIfNotEmpty( arguments, "-windowtitle", JavadocUtil.quotedArgument( getWindowtitle() ), false, false ); } /** * Add <code>groups</code> parameter to arguments. * * @param arguments not null */ private void addGroups( List arguments ) { if ( groups == null ) { return; } for ( int i = 0; i < groups.length; i++ ) { if ( groups[i] == null || StringUtils.isEmpty( groups[i].getTitle() ) || StringUtils.isEmpty( groups[i].getPackages() ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A group option is empty. Ignore this option." ); } } else { String groupTitle = StringUtils.replace( groups[i].getTitle(), ",", "&#44;" ); addArgIfNotEmpty( arguments, "-group", JavadocUtil.quotedArgument( groupTitle ) + " " + JavadocUtil.quotedArgument( groups[i].getPackages() ), true ); } } } /** * Add <code>tags</code> parameter to arguments. * * @param arguments not null */ private void addTags( List arguments ) { if ( tags == null ) { return; } for ( int i = 0; i < tags.length; i++ ) { if ( StringUtils.isEmpty( tags[i].getName() ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A tag name is empty. Ignore this option." ); } } else { String value = "\"" + tags[i].getName(); if ( StringUtils.isNotEmpty( tags[i].getPlacement() ) ) { value += ":" + tags[i].getPlacement(); if ( StringUtils.isNotEmpty( tags[i].getHead() ) ) { value += ":" + tags[i].getHead(); } } value += "\""; addArgIfNotEmpty( arguments, "-tag", value, SINCE_JAVADOC_1_4 ); } } } /** * Add <code>taglets</code> parameter to arguments. * * @param arguments not null */ private void addTaglets( List arguments ) { if ( taglets == null ) { return; } for ( int i = 0; i < taglets.length; i++ ) { if ( ( taglets[i] == null ) || ( StringUtils.isEmpty( taglets[i].getTagletClass() ) ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A taglet option is empty. Ignore this option." ); } } else { addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglets[i].getTagletClass() ), SINCE_JAVADOC_1_4 ); } } } /** * Auto-detect taglets class name from <code>tagletArtifacts</code> and add them to arguments. * * @param arguments not null * @throws MavenReportException if any * @see JavadocUtil#getTagletClassNames(File) */ private void addTagletsFromTagletArtifacts( List arguments ) throws MavenReportException { if ( tagletArtifacts == null ) { return; } List tagletsPath = new ArrayList(); for ( int i = 0; i < tagletArtifacts.length; i++ ) { TagletArtifact aTagletArtifact = tagletArtifacts[i]; if ( ( StringUtils.isNotEmpty( aTagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getVersion() ) ) ) { Artifact artifact; try { artifact = createAndResolveArtifact( aTagletArtifact ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + aTagletArtifact, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + aTagletArtifact, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + aTagletArtifact, e ); } tagletsPath.add( artifact.getFile().getAbsolutePath() ); } } tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); for ( Iterator it = tagletsPath.iterator(); it.hasNext(); ) { String tagletJar = (String) it.next(); if ( !tagletJar.toLowerCase( Locale.ENGLISH ).endsWith( ".jar" ) ) { continue; } List tagletClasses; try { tagletClasses = JavadocUtil.getTagletClassNames( new File( tagletJar ) ); } catch ( IOException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "IOException: " + e.getMessage(), e ); } continue; } catch ( ClassNotFoundException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "ClassNotFoundException: " + e.getMessage(), e ); } continue; } catch ( NoClassDefFoundError e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "NoClassDefFoundError: " + e.getMessage(), e ); } continue; } if ( tagletClasses != null && !tagletClasses.isEmpty() ) { for ( Iterator it2 = tagletClasses.iterator(); it2.hasNext(); ) { String tagletClass = (String) it2.next(); addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( tagletClass ), SINCE_JAVADOC_1_4 ); } } } } /** * Execute the Javadoc command line * * @param cmd not null * @param javadocOutputDirectory not null * @throws MavenReportException if any errors occur */ private void executeJavadocCommandLine( Commandline cmd, File javadocOutputDirectory ) throws MavenReportException { if ( getLog().isDebugEnabled() ) { // no quoted arguments getLog().debug( CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ) ); } String cmdLine = null; if ( debug ) { cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); cmdLine = JavadocUtil.hideProxyPassword( cmdLine, settings ); writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); } CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); try { int exitCode = CommandLineUtils.executeCommandLine( cmd, out, err ); String output = ( StringUtils.isEmpty( out.getOutput() ) ? null : '\n' + out.getOutput().trim() ); if ( exitCode != 0 ) { if ( cmdLine == null ) { cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); cmdLine = JavadocUtil.hideProxyPassword( cmdLine, settings ); } writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); if ( StringUtils.isNotEmpty( output ) && StringUtils.isEmpty( err.getOutput() ) && isJavadocVMInitError( output ) ) { StringBuffer msg = new StringBuffer(); msg.append( output ); msg.append( '\n' ).append( '\n' ); msg.append( JavadocUtil.ERROR_INIT_VM ).append( '\n' ); msg.append( "Or, try to reduce the Java heap size for the Javadoc goal using " ); msg.append( "-Dminmemory=<size> and -Dmaxmemory=<size>." ).append( '\n' ).append( '\n' ); msg.append( "Command line was: " ).append( cmdLine ).append( '\n' ).append( '\n' ); msg.append( "Refer to the generated Javadoc files in '" ).append( javadocOutputDirectory ) .append( "' dir.\n" ); throw new MavenReportException( msg.toString() ); } if ( StringUtils.isNotEmpty( output ) ) { getLog().info( output ); } StringBuffer msg = new StringBuffer( "\nExit code: " ); msg.append( exitCode ); if ( StringUtils.isNotEmpty( err.getOutput() ) ) { msg.append( " - " ).append( err.getOutput() ); } msg.append( '\n' ); msg.append( "Command line was: " ).append( cmdLine ).append( '\n' ).append( '\n' ); msg.append( "Refer to the generated Javadoc files in '" ).append( javadocOutputDirectory ) .append( "' dir.\n" ); throw new MavenReportException( msg.toString() ); } if ( StringUtils.isNotEmpty( output ) ) { getLog().info( output ); } } catch ( CommandLineException e ) { throw new MavenReportException( "Unable to execute javadoc command: " + e.getMessage(), e ); } // ---------------------------------------------------------------------- // Handle Javadoc warnings // ---------------------------------------------------------------------- if ( StringUtils.isNotEmpty( err.getOutput() ) && getLog().isWarnEnabled() ) { getLog().warn( "Javadoc Warnings" ); StringTokenizer token = new StringTokenizer( err.getOutput(), "\n" ); while ( token.hasMoreTokens() ) { String current = token.nextToken().trim(); getLog().warn( current ); } } } /** * @param outputFile not nul * @param inputResourceName a not null resource in <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code> * or in the Javadoc plugin dependencies. * @return the resource file absolute path as String * @since 2.6 */ private String getResource( File outputFile, String inputResourceName ) { if ( inputResourceName.startsWith( "/" ) ) { inputResourceName = inputResourceName.replaceFirst( "//*", "" ); } List classPath = new ArrayList(); classPath.add( project.getBuild().getSourceDirectory() ); URL resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main src directory of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } classPath.clear(); for ( Iterator it = project.getBuild().getResources().iterator(); it.hasNext(); ) { Resource resource = (Resource) it.next(); classPath.add( resource.getDirectory() ); } resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main resources directories of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } if ( javadocDirectory.exists() ) { classPath.clear(); classPath.add( javadocDirectory.getAbsolutePath() ); resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main javadoc directory of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } } classPath.clear(); final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; Plugin javadocPlugin = getPlugin( project, pluginId ); if ( javadocPlugin != null && javadocPlugin.getDependencies() != null ) { for ( Iterator it = javadocPlugin.getDependencies().iterator(); it.hasNext(); ) { Dependency dependency = (Dependency) it.next(); JavadocPathArtifact javadocPathArtifact = new JavadocPathArtifact(); javadocPathArtifact.setGroupId( dependency.getGroupId() ); javadocPathArtifact.setArtifactId( dependency.getArtifactId() ); javadocPathArtifact.setVersion( dependency.getVersion() ); Artifact artifact = null; try { artifact = createAndResolveArtifact( javadocPathArtifact ); } catch ( Exception e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "Unable to retrieve the dependency: " + dependency + ". Ignored.", e ); } else { getLog().error( "Unable to retrieve the dependency: " + dependency + ". Ignored." ); } } if ( artifact != null && artifact.getFile().exists() ) { classPath.add( artifact.getFile().getAbsolutePath() ); } } resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in javadoc plugin dependencies." ); try { JavadocUtil.copyResource( resourceURL, outputFile ); return outputFile.getAbsolutePath(); } catch ( IOException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "IOException: " + e.getMessage(), e ); } else { getLog().error( "IOException: " + e.getMessage() ); } } } } getLog() .warn( "Unable to find the resource '" + inputResourceName + "'. Using default Javadoc resources." ); return null; } /** * @param classPath a not null String list of files where resource will be look up. * @param resource a not null ressource to find in the class path. * @return the resource from the given classpath or null if not found * @see ClassLoader#getResource(String) * @since 2.6 */ private URL getResource( final List classPath, final String resource ) { List urls = new ArrayList( classPath.size() ); Iterator iter = classPath.iterator(); while ( iter.hasNext() ) { try { urls.add( new File( ( (String) iter.next() ) ).toURL() ); } catch ( MalformedURLException e ) { getLog().error( "MalformedURLException: " + e.getMessage() ); } } ClassLoader javadocClassLoader = new URLClassLoader( (URL[]) urls.toArray( new URL[urls.size()] ), null ); return javadocClassLoader.getResource( resource ); } /** * Load the plugin pom.properties to get the current plugin version. * * @return <code>org.apache.maven.plugins:maven-javadoc-plugin:CURRENT_VERSION:javadoc</code> */ private String getFullJavadocGoal() { String javadocPluginVersion = null; InputStream resourceAsStream = null; try { String resource = "META-INF/maven/org.apache.maven.plugins/maven-javadoc-plugin/pom.properties"; resourceAsStream = AbstractJavadocMojo.class.getClassLoader().getResourceAsStream( resource ); if ( resourceAsStream != null ) { Properties properties = new Properties(); properties.load( resourceAsStream ); if ( StringUtils.isNotEmpty( properties.getProperty( "version" ) ) ) { javadocPluginVersion = properties.getProperty( "version" ); } } } catch ( IOException e ) { // nop } finally { IOUtil.close( resourceAsStream ); } StringBuffer sb = new StringBuffer(); sb.append( "org.apache.maven.plugins" ).append( ":" ); sb.append( "maven-javadoc-plugin" ).append( ":" ); if ( StringUtils.isNotEmpty( javadocPluginVersion ) ) { sb.append( javadocPluginVersion ).append( ":" ); } if ( TestJavadocReport.class.isAssignableFrom( getClass() ) ) { sb.append( "test-javadoc" ); } else { sb.append( "javadoc" ); } return sb.toString(); } /** * Using Maven, a Javadoc link is given by <code>${project.url}/apidocs</code>. * * @return the detected Javadoc links using the Maven conventions for all modules defined in the current project * or an empty list. * @throws MavenReportException if any * @see #detectOfflineLinks * @see #reactorProjects * @since 2.6 */ private List getModulesLinks() throws MavenReportException { if ( !( detectOfflineLinks && !isAggregator() && reactorProjects != null ) ) { return Collections.EMPTY_LIST; } getLog().debug( "Try to add links for modules..." ); List modulesLinks = new ArrayList(); String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getOutputDirectory() ); for ( Iterator it = reactorProjects.iterator(); it.hasNext(); ) { MavenProject p = (MavenProject) it.next(); if ( p.getPackaging().equals( "pom" ) ) { continue; } if ( p.getId().equals( project.getId() ) ) { continue; } File location = new File( p.getBasedir(), javadocDirRelative ); if ( p.getUrl() != null ) { if ( !location.exists() ) { String javadocGoal = getFullJavadocGoal(); getLog().info( "The goal '" + javadocGoal + "' has not be previously called for the project: '" + p.getId() + "'. Trying to invoke it..." ); File invokerDir = new File( project.getBuild().getDirectory(), "invoker" ); invokerDir.mkdirs(); File invokerLogFile = FileUtils.createTempFile( "maven-javadoc-plugin", ".txt", invokerDir ); try { JavadocUtil.invokeMaven( getLog(), new File( localRepository.getBasedir() ), p.getFile(), Collections.singletonList( javadocGoal ), null, invokerLogFile ); } catch ( MavenInvocationException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "MavenInvocationException: " + e.getMessage(), e ); } else { getLog().error( "MavenInvocationException: " + e.getMessage() ); } String invokerLogContent = JavadocUtil.readFile( invokerLogFile, "UTF-8" ); if ( invokerLogContent != null && invokerLogContent.indexOf( JavadocUtil.ERROR_INIT_VM ) == -1 ) { throw new MavenReportException( e.getMessage(), e ); } } finally { // just create the directory to prevent repeated invokations.. if ( !location.exists() ) { location.mkdirs(); } } } if ( location.exists() ) { String url = getJavadocLink( p ); OfflineLink ol = new OfflineLink(); ol.setUrl( url ); ol.setLocation( location.getAbsolutePath() ); if ( getLog().isDebugEnabled() ) { getLog().debug( "Added Javadoc link: " + url + " for the project: " + p.getId() ); } modulesLinks.add( ol ); } } } return modulesLinks; } /** * Using Maven, a Javadoc link is given by <code>${project.url}/apidocs</code>. * * @return the detected Javadoc links using the Maven conventions for all dependencies defined in the current * project or an empty list. * @see #detectLinks * @since 2.6 */ private List getDependenciesLinks() { if ( !detectLinks ) { return Collections.EMPTY_LIST; } getLog().debug( "Try to add links for dependencies..." ); List dependenciesLinks = new ArrayList(); for ( Iterator it = project.getDependencyArtifacts().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); if ( artifact != null && artifact.getFile() != null && artifact.getFile().exists() ) { try { MavenProject artifactProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); if ( StringUtils.isNotEmpty( artifactProject.getUrl() ) ) { String url = getJavadocLink( artifactProject ); if ( getLog().isDebugEnabled() ) { getLog().debug( "Added Javadoc link: " + url + " for the project: " + artifactProject.getId() ); } dependenciesLinks.add( url ); } } catch ( ProjectBuildingException e ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "Error when building the artifact: " + artifact.toString() + ". Ignored to add Javadoc link." ); getLog().error( "ProjectBuildingException: " + e.getMessage(), e ); } else { getLog().error( "ProjectBuildingException: " + e.getMessage() ); } } } } return dependenciesLinks; } /** * @return if {@link #detectJavaApiLink}, the Java API link based on the {@link #javaApiLinks} properties and the * value of the <code>source</code> parameter in the <code>org.apache.maven.plugins:maven-compiler-plugin</code> * defined in <code>${project.build.plugins}</code> or in <code>${project.build.pluginManagement}</code>, * or the {@link #fJavadocVersion}, or <code>null</code> if not defined. * @since 2.6 * @see #detectJavaApiLink * @see #javaApiLinks * @see #DEFAULT_JAVA_API_LINKS * @see <a href="http://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#source">source parameter</a> */ private String getDefaultJavadocApiLink() { if ( !detectJavaApiLink ) { return null; } final String pluginId = "org.apache.maven.plugins:maven-compiler-plugin"; float sourceVersion = fJavadocVersion; String sourceConfigured = getPluginParameter( project, pluginId, "source" ); if ( sourceConfigured != null ) { try { sourceVersion = Float.parseFloat( sourceConfigured ); } catch ( NumberFormatException e ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "NumberFormatException for the source parameter in the maven-compiler-plugin. " + "Ignored it", e ); } } } else { if ( getLog().isDebugEnabled() ) { getLog().debug( "No maven-compiler-plugin defined in ${build.plugins} or in " + "${project.build.pluginManagement} for the " + project.getId() + ". Added Javadoc API link according the javadoc executable version i.e.: " + fJavadocVersion ); } } String javaApiLink = null; if ( sourceVersion >= 1.3f && sourceVersion < 1.4f && javaApiLinks.getProperty( "api_1.3" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.3" ).toString(); } else if ( sourceVersion >= 1.4f && sourceVersion < 1.5f && javaApiLinks.getProperty( "api_1.4" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.4" ).toString(); } else if ( sourceVersion >= 1.5f && sourceVersion < 1.6f && javaApiLinks.getProperty( "api_1.5" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.5" ).toString(); } else if ( sourceVersion >= 1.6f && javaApiLinks.getProperty( "api_1.6" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.6" ).toString(); } if ( StringUtils.isNotEmpty( javaApiLink ) ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "Found Java API link: " + javaApiLink ); } } else { if ( getLog().isDebugEnabled() ) { getLog().debug( "No Java API link found." ); } } return javaApiLink; } /** * @param link not null * @return <code>true</code> if the link has a <code>/package-list</code>, <code>false</code> otherwise. * @since 2.6 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/javadoc.html#package-list"> * package-list spec</a> */ private boolean isValidJavadocLink( String link ) { try { URI linkUri; if ( link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "http" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "https" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "ftp" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "file" ) ) { linkUri = new URI( link + "/package-list" ); } else { // links can be relative paths or files File dir = new File( link ); if ( !dir.isAbsolute() ) { dir = new File( getOutputDirectory(), link ); } if ( !dir.isDirectory() ) { getLog().error( "The given File link: " + dir + " is not a dir." ); } linkUri = new File( dir, "package-list" ).toURI(); } JavadocUtil.fetchURL( settings, linkUri.toURL() ); return true; } catch ( URISyntaxException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Malformed link: " + link + "/package-list. Ignored it." ); } return false; } catch ( IOException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Error fetching link: " + link + "/package-list. Ignored it." ); } return false; } } /** * Write a debug javadoc script in case of command line error or in debug mode. * * @param cmdLine the current command line as string, not null. * @param javadocOutputDirectory the output dir, not null. * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6 */ private void writeDebugJavadocScript( String cmdLine, File javadocOutputDirectory ) { File commandLineFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); commandLineFile.getParentFile().mkdirs(); try { FileUtils.fileWrite( commandLineFile.getAbsolutePath(), "UTF-8", cmdLine ); if ( !SystemUtils.IS_OS_WINDOWS ) { Runtime.getRuntime().exec( new String[] { "chmod", "a+x", commandLineFile.getAbsolutePath() } ); } } catch ( IOException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "Unable to write '" + commandLineFile.getName() + "' debug script file", e ); } else { getLog().error( "Unable to write '" + commandLineFile.getName() + "' debug script file" ); } } } /** * Check if the Javadoc JVM is correctly started or not. * * @param output the command line output, not null. * @return <code>true</code> if Javadoc output command line contains Javadoc word, <code>false</code> otherwise. * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6.1 */ private boolean isJavadocVMInitError( String output ) { /* * see main.usage and main.Building_tree keys from * com.sun.tools.javadoc.resources.javadoc bundle in tools.jar */ if ( output.indexOf( "Javadoc" ) != -1 || output.indexOf( "javadoc" ) != -1 ) { return false; } return true; } // ---------------------------------------------------------------------- // Static methods // ---------------------------------------------------------------------- /** * @param p not null * @return the javadoc link based on the project url i.e. <code>${project.url}/${destDir}</code> where * <code>destDir</code> is configued in the Javadoc plugin configuration (<code>apidocs</code> by default). * @since 2.6 */ private static String getJavadocLink( MavenProject p ) { if ( p.getUrl() == null ) { return null; } String url = cleanUrl( p.getUrl() ); String destDir = "apidocs"; // see JavadocReport#destDir final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; String destDirConfigured = getPluginParameter( p, pluginId, "destDir" ); if ( destDirConfigured != null ) { destDir = destDirConfigured; } return url + "/" + destDir; } /** * @param url could be null. * @return the url cleaned or empty if url was null. * @since 2.6 */ private static String cleanUrl( String url ) { if ( url == null ) { return ""; } url = url.trim(); while ( url.endsWith( "/" ) ) { url = url.substring( 0, url.lastIndexOf( "/" ) ); } return url; } /** * @param p not null * @param pluginId not null key of the plugin defined in {@link org.apache.maven.model.Build#getPluginsAsMap()} * or in {@link org.apache.maven.model.PluginManagement#getPluginsAsMap()} * @return the Maven plugin defined in <code>${project.build.plugins}</code> or in * <code>${project.build.pluginManagement}</code>, or <code>null</code> if not defined. * @since 2.6 */ private static Plugin getPlugin( MavenProject p, String pluginId ) { Plugin plugin = null; if ( p.getBuild() != null && p.getBuild().getPluginsAsMap() != null ) { plugin = (Plugin) p.getBuild().getPluginsAsMap().get( pluginId ); if ( plugin == null ) { if ( p.getBuild().getPluginManagement() != null && p.getBuild().getPluginManagement().getPluginsAsMap() != null ) { plugin = (Plugin) p.getBuild().getPluginManagement().getPluginsAsMap().get( pluginId ); } } } return plugin; } /** * @param p not null * @param pluginId not null * @param param not null * @return the simple parameter as String defined in the plugin configuration by <code>param</code> key * or <code>null</code> if not found. * @since 2.6 */ private static String getPluginParameter( MavenProject p, String pluginId, String param ) { // p.getGoalConfiguration( pluginGroupId, pluginArtifactId, executionId, goalId ); Plugin plugin = getPlugin( p, pluginId ); if ( plugin != null ) { Xpp3Dom xpp3Dom = (Xpp3Dom) plugin.getConfiguration(); if ( xpp3Dom != null && xpp3Dom.getChild( param ) != null && StringUtils.isNotEmpty( xpp3Dom.getChild( param ).getValue() ) ) { return xpp3Dom.getChild( param ).getValue(); } } return null; } }
maven-javadoc-plugin/src/main/java/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.java
package org.apache.maven.plugin.javadoc; /* * 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. */ import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import org.apache.commons.lang.ClassUtils; import org.apache.commons.lang.SystemUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.repository.ArtifactRepository; 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.ArtifactResolver; import org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException; import org.apache.maven.artifact.versioning.ArtifactVersion; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.model.Plugin; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.javadoc.options.BootclasspathArtifact; import org.apache.maven.plugin.javadoc.options.DocletArtifact; import org.apache.maven.plugin.javadoc.options.Group; import org.apache.maven.plugin.javadoc.options.JavadocPathArtifact; import org.apache.maven.plugin.javadoc.options.OfflineLink; import org.apache.maven.plugin.javadoc.options.ResourcesArtifact; import org.apache.maven.plugin.javadoc.options.Tag; import org.apache.maven.plugin.javadoc.options.Taglet; import org.apache.maven.plugin.javadoc.options.TagletArtifact; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.artifact.InvalidDependencyVersionException; import org.apache.maven.reporting.MavenReportException; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Settings; import org.apache.maven.shared.invoker.MavenInvocationException; import org.apache.maven.toolchain.Toolchain; import org.apache.maven.toolchain.ToolchainManager; import org.apache.maven.wagon.PathUtils; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; import org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.cli.CommandLineException; import org.codehaus.plexus.util.cli.CommandLineUtils; import org.codehaus.plexus.util.cli.Commandline; import org.codehaus.plexus.util.xml.Xpp3Dom; /** * Base class with majority of Javadoc functionalities. * * @author <a href="mailto:[email protected]">Brett Porter</a> * @author <a href="mailto:[email protected]">Vincent Siveton</a> * @version $Id$ * @since 2.0 * @requiresDependencyResolution compile * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html"> * The Java API Documentation Generator, 1.4.2</a> */ public abstract class AbstractJavadocMojo extends AbstractMojo { /** * The default Javadoc API urls according the * <a href="http://java.sun.com/reference/api/index.html">Sun API Specifications</a>: * <pre> * &lt;javaApiLinks&gt; * &lt;property&gt; * &lt;name&gt;api_1.3&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.3/docs/api&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.4&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.4.2/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.5&lt;/name&gt; * &lt;value&gt;http://java.sun.com/j2se/1.5.0/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;property&gt; * &lt;name&gt;api_1.6&lt;/name&gt; * &lt;value&gt;http://java.sun.com/javase/6/docs/api/&lt;/value&gt; * &lt;/property&gt; * &lt;/javaApiLinks&gt; * </pre> * * @since 2.6 */ public static final Properties DEFAULT_JAVA_API_LINKS = new Properties(); /** The Javadoc script file name when <code>debug</code> parameter is on, i.e. javadoc.bat or javadoc.sh */ protected static final String DEBUG_JAVADOC_SCRIPT_NAME = "javadoc." + ( SystemUtils.IS_OS_WINDOWS ? "bat" : "sh" ); /** The <code>options</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String OPTIONS_FILE_NAME = "options"; /** The <code>packages</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String PACKAGES_FILE_NAME = "packages"; /** The <code>argfile</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String ARGFILE_FILE_NAME = "argfile"; /** The <code>files</code> file name in the output directory when calling: * <code>javadoc.exe(or .sh) &#x40;options &#x40;packages | &#x40;argfile | &#x40;files</code> */ protected static final String FILES_FILE_NAME = "files"; /** The current class directory */ private static final String RESOURCE_DIR = ClassUtils.getPackageName( JavadocReport.class ).replace( '.', '/' ); /** Default css file name */ private static final String DEFAULT_CSS_NAME = "stylesheet.css"; /** Default location for css */ private static final String RESOURCE_CSS_DIR = RESOURCE_DIR + "/css"; /** * For Javadoc options appears since Java 1.4. * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary"> * What's New in Javadoc 1.4</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_4 = 1.4f; /** * For Javadoc options appears since Java 1.4.2. * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * What's New in Javadoc 1.4.2</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_4_2 = 1.42f; /** * For Javadoc options appears since Java 5.0. * See <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * What's New in Javadoc 5.0</a> * @since 2.1 */ private static final float SINCE_JAVADOC_1_5 = 1.5f; /** * For Javadoc options appears since Java 6.0. * See <a href="http://java.sun.com/javase/6/docs/technotes/guides/javadoc/index.html"> * Javadoc Technology</a> * @since 2.4 */ private static final float SINCE_JAVADOC_1_6 = 1.6f; // ---------------------------------------------------------------------- // Mojo components // ---------------------------------------------------------------------- /** * Archiver manager * * @since 2.5 * @component */ private ArchiverManager archiverManager; /** * Factory for creating artifact objects * * @component */ private ArtifactFactory factory; /** * Used to resolve artifacts of aggregated modules * * @since 2.1 * @component */ private ArtifactMetadataSource artifactMetadataSource; /** * Used for resolving artifacts * * @component */ private ArtifactResolver resolver; /** * Project builder * * @since 2.5 * @component */ private MavenProjectBuilder mavenProjectBuilder; /** @component */ private ToolchainManager toolchainManager; // ---------------------------------------------------------------------- // Mojo parameters // ---------------------------------------------------------------------- /** * The current build session instance. This is used for * toolchain manager API calls. * * @parameter expression="${session}" * @required * @readonly */ private MavenSession session; /** * The Maven Settings. * * @since 2.3 * @parameter default-value="${settings}" * @required * @readonly */ private Settings settings; /** * The Maven Project Object * * @parameter expression="${project}" * @required * @readonly */ protected MavenProject project; /** * Specify if the Javadoc should operate in offline mode. * * @parameter default-value="${settings.offline}" * @required * @readonly */ private boolean isOffline; /** * Specifies the Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). * <br/> * Could be used in addition of <code>docfilessubdirs</code> parameter. * <br/> * See <a href="#docfilessubdirs">docfilessubdirs</a>. * * @since 2.1 * @parameter expression="${basedir}/src/main/javadoc" * @see #docfilessubdirs */ private File javadocDirectory; /** * Set an additional parameter(s) on the command line. This value should include quotes as necessary for * parameters that include spaces. Useful for a custom doclet. * * @parameter expression="${additionalparam}" */ private String additionalparam; /** * Set an additional Javadoc option(s) (i.e. JVM options) on the command line. * Example: * <pre> * &lt;additionalJOption&gt;-J-Xss128m&lt;/additionalJOption&gt; * </pre> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#J">Jflag</a>. * <br/> * See <a href="http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp">vmoptions</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/guide/net/properties.html">Networking Properties</a>. * * @since 2.3 * @parameter expression="${additionalJOption}" */ private String additionalJOption; /** * A list of artifacts containing resources which should be copied into the * Javadoc output directory (like stylesheets, icons, etc.). * <br/> * Example: * <pre> * &lt;resourcesArtifacts&gt; * &nbsp;&nbsp;&lt;resourcesArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;external.group.id&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;external-resources&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.0&lt;/version&gt; * &nbsp;&nbsp;&lt;/resourcesArtifact&gt; * &lt;/resourcesArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/ResourcesArtifact.html">Javadoc</a>. * <br/> * * @since 2.5 * @parameter expression="${resourcesArtifacts}" */ private ResourcesArtifact[] resourcesArtifacts; /** * The local repository where the artifacts are located. * * @parameter expression="${localRepository}" */ private ArtifactRepository localRepository; /** * The remote repositories where artifacts are located. * * @parameter expression="${project.remoteArtifactRepositories}" */ private List remoteRepositories; /** * The projects in the reactor for aggregation report. * * @parameter expression="${reactorProjects}" * @readonly */ private List reactorProjects; /** * Whether to build an aggregated report at the root, or build individual reports. * * @parameter expression="${aggregate}" default-value="false" * @deprecated since 2.5. Use the goals <code>javadoc:aggregate</code> and <code>javadoc:test-aggregate</code> instead. */ protected boolean aggregate; /** * Set this to <code>true</code> to debug the Javadoc plugin. With this, <code>javadoc.bat(or.sh)</code>, * <code>options</code>, <code>@packages</code> or <code>argfile</code> files are provided in the output directory. * <br/> * * @since 2.1 * @parameter expression="${debug}" default-value="false" */ private boolean debug; /** * Sets the absolute path of the Javadoc Tool executable to use. Since version 2.5, a mere directory specification * is sufficient to have the plugin use "javadoc" or "javadoc.exe" respectively from this directory. * * @since 2.3 * @parameter expression="${javadocExecutable}" */ private String javadocExecutable; /** * Version of the Javadoc Tool executable to use, ex. "1.3", "1.5". * * @since 2.3 * @parameter expression="${javadocVersion}" */ private String javadocVersion; /** * Version of the Javadoc Tool executable to use as float. */ private float fJavadocVersion = 0.0f; /** * Specifies whether the Javadoc generation should be skipped. * * @since 2.5 * @parameter expression="${maven.javadoc.skip}" default-value="false" */ protected boolean skip; /** * Specifies whether the build will continue even if there are errors. * * @parameter expression="${maven.javadoc.failOnError}" default-value="true" * @since 2.5 */ protected boolean failOnError; /** * Specifies to use the <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard"> * options provided by the Standard Doclet</a> for a custom doclet. * <br/> * Example: * <pre> * &lt;docletArtifacts&gt; * &nbsp;&nbsp;&lt;docletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &nbsp;&nbsp;&lt;/docletArtifact&gt; * &lt;/docletArtifacts&gt; * &lt;useStandardDocletOptions&gt;true&lt;/useStandardDocletOptions&gt; * </pre> * * @parameter expression="${useStandardDocletOptions}" default-value="true" * @since 2.5 */ protected boolean useStandardDocletOptions; /** * Detect the Javadoc links for all dependencies defined in the project. The detection is based on the default * Maven conventions, i.e.: <code>${project.url}/apidocs</code>. * <br/> * For instance, if the project has a dependency to * <a href="http://commons.apache.org/lang/">Apache Commons Lang</a> i.e.: * <pre> * &lt;dependency&gt; * &lt;groupId&gt;commons-lang&lt;/groupId&gt; * &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; * &lt;/dependency&gt; * </pre> * The added Javadoc <code>-link</code> parameter will be <code>http://commons.apache.org/lang/apidocs</code>. * * @parameter expression="${detectLinks}" default-value="false" * @see #links * @since 2.6 */ private boolean detectLinks; /** * Detect the links for all modules defined in the project. * <br/> * If {@link #reactorProjects} is defined in a non-aggregator way, it generates default offline links * between modules based on the defined project's urls. For instance, if a parent project has two projects * <code>module1</code> and <code>module2</code>, the <code>-linkoffline</code> will be: * <br/> * The added Javadoc <code>-linkoffline</code> parameter for <b>module1</b> will be * <code>/absolute/path/to/</code><b>module2</b><code>/target/site/apidocs</code> * <br/> * The added Javadoc <code>-linkoffline</code> parameter for <b>module2</b> will be * <code>/absolute/path/to/</code><b>module1</b><code>/target/site/apidocs</code> * * @parameter expression="${detectOfflineLinks}" default-value="true" * @see #offlineLinks * @since 2.6 */ private boolean detectOfflineLinks; /** * Detect the Java API link for the current build, i.e. <code>http://java.sun.com/j2se/1.4.2/docs/api</code> * for Java source 1.4. * <br/> * By default, the goal detects the Javadoc API link depending the value of the <code>source</code> * parameter in the <code>org.apache.maven.plugins:maven-compiler-plugin</code> * (defined in <code>${project.build.plugins}</code> or in <code>${project.build.pluginManagement}</code>), * or try to compute it from the {@link #javadocExecutable} version. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.html#DEFAULT_JAVA_API_LINKS">Javadoc</a> for the default values. * <br/> * * @parameter expression="${detectJavaApiLink}" default-value="true" * @see #links * @see #javaApiLinks * @see #DEFAULT_JAVA_API_LINKS * @since 2.6 */ private boolean detectJavaApiLink; /** * Use this parameter <b>only</b> if the <a href="http://java.sun.com/reference/api/index.html">Sun Javadoc API</a> * urls have been changed or to use custom urls for Javadoc API url. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.html#DEFAULT_JAVA_API_LINKS">Javadoc</a> * for the default values. * <br/> * * @parameter expression="${javaApiLinks}" * @see #DEFAULT_JAVA_API_LINKS * @since 2.6 */ private Properties javaApiLinks; // ---------------------------------------------------------------------- // Javadoc Options - all alphabetical // ---------------------------------------------------------------------- /** * Specifies the paths where the boot classes reside. The <code>bootclasspath</code> can contain multiple paths * by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bootclasspath">bootclasspath</a>. * <br/> * * @parameter expression="${bootclasspath}" * @since 2.5 */ private String bootclasspath; /** * Specifies the artifacts where the boot classes reside. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bootclasspath">bootclasspath</a>. * <br/> * Example: * <pre> * &lt;bootclasspathArtifacts&gt; * &nbsp;&nbsp;&lt;bootclasspathArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;my-groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;my-artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;my-version&lt;/version&gt; * &nbsp;&nbsp;&lt;/bootclasspathArtifact&gt; * &lt;/bootclasspathArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/BootclasspathArtifact.html">Javadoc</a>. * <br/> * * @parameter expression="${bootclasspathArtifacts}" * @since 2.5 */ private BootclasspathArtifact[] bootclasspathArtifacts; /** * Uses the sentence break iterator to determine the end of the first sentence. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#breakiterator">breakiterator</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${breakiterator}" default-value="false" */ private boolean breakiterator; /** * Specifies the class file that starts the doclet used in generating the documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#doclet">doclet</a>. * * @parameter expression="${doclet}" */ private String doclet; /** * Specifies the artifact containing the doclet starting class file (specified with the <code>-doclet</code> * option). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * <br/> * Example: * <pre> * &lt;docletArtifact&gt; * &nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &lt;/docletArtifact&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/DocletArtifact.html">Javadoc</a>. * <br/> * * @parameter expression="${docletArtifact}" */ private DocletArtifact docletArtifact; /** * Specifies multiple artifacts containing the path for the doclet starting class file (specified with the * <code>-doclet</code> option). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * <br/> * Example: * <pre> * &lt;docletArtifacts&gt; * &nbsp;&nbsp;&lt;docletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;com.sun.tools.doclets&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;doccheck&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;1.2b2&lt;/version&gt; * &nbsp;&nbsp;&lt;/docletArtifact&gt; * &lt;/docletArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/DocletArtifact.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${docletArtifacts}" */ private DocletArtifact[] docletArtifacts; /** * Specifies the path to the doclet starting class file (specified with the <code>-doclet</code> option) and * any jar files it depends on. The <code>docletPath</code> can contain multiple paths by separating them with * a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docletpath">docletpath</a>. * * @parameter expression="${docletPath}" */ private String docletPath; /** * Specifies the encoding name of the source files. If not specificed, the encoding value will be the value of the * <code>file.encoding</code> system property. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#encoding">encoding</a>. * <br/> * <b>Note</b>: In 2.4, the default value was locked to <code>ISO-8859-1</code> to ensure reproducing build, but * this was reverted in 2.5. * <br/> * * @parameter expression="${encoding}" default-value="${project.build.sourceEncoding}" */ private String encoding; /** * Unconditionally excludes the specified packages and their subpackages from the list formed by * <code>-subpackages</code>. Multiple packages can be separated by commas (<code>,</code>), colons (<code>:</code>) * or semicolons (<code>;</code>). * <br/> * Example: * <pre> * &lt;excludePackageNames&gt;*.internal:org.acme.exclude1.*:org.acme.exclude2&lt;/excludePackageNames&gt; * </pre> * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#exclude">exclude</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${excludePackageNames}" */ private String excludePackageNames; /** * Specifies the directories where extension classes reside. Separate directories in <code>extdirs</code> with a * colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#extdirs">extdirs</a>. * * @parameter expression="${extdirs}" */ private String extdirs; /** * Specifies the locale that javadoc uses when generating documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#locale">locale</a>. * * @parameter expression="${locale}" */ private String locale; /** * Specifies the maximum Java heap size to be used when launching the Javadoc tool. * JVMs refer to this property as the <code>-Xmx</code> parameter. Example: '512' or '512m'. * The memory unit depends on the JVM used. The units supported could be: <code>k</code>, <code>kb</code>, * <code>m</code>, <code>mb</code>, <code>g</code>, <code>gb</code>, <code>t</code>, <code>tb</code>. * If no unit specified, the default unit is <code>m</code>. * * @parameter expression="${maxmemory}" */ private String maxmemory; /** * Specifies the minimum Java heap size to be used when launching the Javadoc tool. * JVMs refer to this property as the <code>-Xms</code> parameter. Example: '512' or '512m'. * The memory unit depends on the JVM used. The units supported could be: <code>k</code>, <code>kb</code>, * <code>m</code>, <code>mb</code>, <code>g</code>, <code>gb</code>, <code>t</code>, <code>tb</code>. * If no unit specified, the default unit is <code>m</code>. * * @parameter expression="${minmemory}" */ private String minmemory; /** * This option creates documentation with the appearance and functionality of documentation generated by * Javadoc 1.1. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#1.1">1.1</a>. * <br/> * * @parameter expression="${old}" default-value="false" */ private boolean old; /** * Specifies that javadoc should retrieve the text for the overview documentation from the "source" file * specified by path/filename and place it on the Overview page (overview-summary.html). * <br/> * <b>Note</b>: could be in conflict with &lt;nooverview/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#overview">overview</a>. * <br/> * * @parameter expression="${overview}" default-value="${basedir}/src/main/javadoc/overview.html" */ private File overview; /** * Specifies the proxy host where the javadoc web access in <code>-link</code> would pass through. * It defaults to the proxy host of the active proxy set in the <code>settings.xml</code>, otherwise it gets the * proxy configuration set in the pom. * <br/> * * @parameter expression="${proxyHost}" * @deprecated since 2.4. Instead of, configure an active proxy host in <code>settings.xml</code>. */ private String proxyHost; /** * Specifies the proxy port where the javadoc web access in <code>-link</code> would pass through. * It defaults to the proxy port of the active proxy set in the <code>settings.xml</code>, otherwise it gets the * proxy configuration set in the pom. * <br/> * * @parameter expression="${proxyPort}" * @deprecated since 2.4. Instead of, configure an active proxy port in <code>settings.xml</code>. */ private int proxyPort; /** * Shuts off non-error and non-warning messages, leaving only the warnings and errors appear, making them * easier to view. * <br/> * Note: was a standard doclet in Java 1.4.2 (refer to bug ID * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4714350">4714350</a>). * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#quiet">quiet</a>. * <br/> * Since Java 5.0. * <br/> * * @parameter expression="${quiet}" default-value="false" */ private boolean quiet; /** * Specifies the access level for classes and members to show in the Javadocs. * Possible values are: * <ul> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#public">public</a> * (shows only public classes and members)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#protected">protected</a> * (shows only public and protected classes and members)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package">package</a> * (shows all classes and members not marked private)</li> * <li><a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#private">private</a> * (shows all classes and members)</li> * </ul> * <br/> * * @parameter expression="${show}" default-value="protected" */ private String show; /** * Necessary to enable javadoc to handle assertions present in J2SE v 1.4 source code. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#source">source</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${source}" */ private String source; /** * Specifies the source paths where the subpackages are located. The <code>sourcepath</code> can contain * multiple paths by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#sourcepath">sourcepath</a>. * * @parameter expression="${sourcepath}" */ private String sourcepath; /** * Specifies the package directory where javadoc will be executed. Multiple packages can be separated by * colons (<code>:</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#subpackages">subpackages</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${subpackages}" */ private String subpackages; /** * Provides more detailed messages while javadoc is running. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#verbose">verbose</a>. * <br/> * * @parameter expression="${verbose}" default-value="false" */ private boolean verbose; // ---------------------------------------------------------------------- // Standard Doclet Options - all alphabetical // ---------------------------------------------------------------------- /** * Specifies whether or not the author text is included in the generated Javadocs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#author">author</a>. * <br/> * * @parameter expression="${author}" default-value="true" */ private boolean author; /** * Specifies the text to be placed at the bottom of each output file.<br/> * If you want to use html you have to put it in a CDATA section, <br/> * eg. <code>&lt;![CDATA[Copyright 2005, &lt;a href="http://www.mycompany.com">MyCompany, Inc.&lt;a>]]&gt;</code> * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#bottom">bottom</a>. * <br/> * * @parameter expression="${bottom}" * default-value="Copyright &#169; {inceptionYear}-{currentYear} {organizationName}. All Rights Reserved." */ private String bottom; /** * Specifies the HTML character set for this document. If not specificed, the charset value will be the value of * the <code>docencoding</code> parameter. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#charset">charset</a>. * <br/> * * @parameter expression="${charset}" */ private String charset; /** * Specifies the encoding of the generated HTML files. If not specificed, the docencoding value will be * <code>UTF-8</code>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docencoding">docencoding</a>. * * @parameter expression="${docencoding}" default-value="${project.reporting.outputEncoding}" */ private String docencoding; /** * Enables deep copying of the <code>&#42;&#42;/doc-files</code> directories and the specifc <code>resources</code> * directory from the <code>javadocDirectory</code> directory (for instance, * <code>src/main/javadoc/com/mycompany/myapp/doc-files</code> and <code>src/main/javadoc/resources</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#docfilessubdirs"> * docfilessubdirs</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * See <a href="#javadocDirectory">javadocDirectory</a>. * <br/> * * @parameter expression="${docfilessubdirs}" default-value="false" * @see #excludedocfilessubdir * @see #javadocDirectory */ private boolean docfilessubdirs; /** * Specifies the title to be placed near the top of the overview summary file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#doctitle">doctitle</a>. * <br/> * * @parameter expression="${doctitle}" default-value="${project.name} ${project.version} API" */ private String doctitle; /** * Excludes any "doc-files" subdirectories with the given names. Multiple patterns can be excluded * by separating them with colons (<code>:</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#excludedocfilessubdir"> * excludedocfilessubdir</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${excludedocfilessubdir}" * @see #docfilessubdirs */ private String excludedocfilessubdir; /** * Specifies the footer text to be placed at the bottom of each output file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#footer">footer</a>. * * @parameter expression="${footer}" */ private String footer; /** * Separates packages on the overview page into whatever groups you specify, one group per table. The * packages pattern can be any package name, or can be the start of any package name followed by an asterisk * (<code>*</code>) meaning "match any characters". Multiple patterns can be included in a group * by separating them with colons (<code>:</code>). * <br/> * Example: * <pre> * &lt;groups&gt; * &nbsp;&nbsp;&lt;group&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Core Packages&lt;/title&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;!-- To includes java.lang, java.lang.ref, * &nbsp;&nbsp;&nbsp;&nbsp;java.lang.reflect and only java.util * &nbsp;&nbsp;&nbsp;&nbsp;(i.e. not java.util.jar) --&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;packages&gt;java.lang*:java.util&lt;/packages&gt; * &nbsp;&nbsp;&lt;/group&gt; * &nbsp;&nbsp;&lt;group&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;title&gt;Extension Packages&lt;/title&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;!-- To include javax.accessibility, * &nbsp;&nbsp;&nbsp;&nbsp;javax.crypto, ... (among others) --&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;packages&gt;javax.*&lt;/packages&gt; * &nbsp;&nbsp;&lt;/group&gt; * &lt;/groups&gt; * </pre> * <b>Note</b>: using <code>java.lang.*</code> for <code>packages</code> would omit the <code>java.lang</code> * package but using <code>java.lang*</code> will include it. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#group">group</a>. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Group.html">Javadoc</a>. * <br/> * * @parameter expression="${groups}" */ private Group[] groups; /** * Specifies the header text to be placed at the top of each output file. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#header">header</a>. * * @parameter expression="${header}" */ private String header; /** * Specifies the path of an alternate help file path\filename that the HELP link in the top and bottom * navigation bars link to. * <br/> * <b>Note</b>: could be in conflict with &lt;nohelp/&gt;. * <br/> * The <code>helpfile</code> could be an absolute File path. * <br/> * Since 2.6, it could be also be a path from a resource in the current project source directories * (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies, for instance: * <pre> * &lt;helpfile&gt;path/to/your/resource/yourhelp-doc.html&lt;/helpfile&gt; * </pre> * Where <code>path/to/your/resource/yourhelp-doc.html</code> could be in <code>src/main/javadoc</code>. * <pre> * &lt;build&gt; * &nbsp;&nbsp;&lt;plugins&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;helpfile&gt;path/to/your/resource/yourhelp-doc.html&lt;/helpfile&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&lt;plugins&gt; * &lt;/build&gt; * </pre> * Where <code>path/to/your/resource/yourhelp-doc.html</code> is defined in the * <code>groupId:artifactId:version</code> javadoc plugin dependency. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#helpfile">helpfile</a>. * * @parameter expression="${helpfile}" */ private String helpfile; /** * Adds HTML meta keyword tags to the generated file for each class. * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#keywords">keywords</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * Java 1.4.2</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * Java 5.0</a>. * <br/> * * @since 2.1 * @parameter expression="${keywords}" default-value="false" */ private boolean keywords; /** * Creates links to existing javadoc-generated documentation of external referenced classes. * <br/> * <b>Notes</b>: * <ol> * <li>only used is {@link #isOffline} is set to <code>false</code>.</li> * <li>all given links should have a fetchable <code>/package-list</code> file. For instance: * <pre> * &lt;links&gt; * &nbsp;&nbsp;&lt;link&gt;http://java.sun.com/j2se/1.4.2/docs/api&lt;/link&gt; * &lt;links&gt; * </pre> * will be used because <code>http://java.sun.com/j2se/1.4.2/docs/api/package-list</code> exists.</li> * <li>if {@link #detectLinks} is defined, the links between the project dependencies are * automatically added.</li> * <li>if {@link #detectJavaApiLink} is defined, a Java API link, based on the Java verion of the * project's sources, will be added automatically.</li> * </ol> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#link">link</a>. * * @parameter expression="${links}" * @see #detectLinks * @see #detectJavaApiLink */ protected ArrayList links; /** * Creates an HTML version of each source file (with line numbers) and adds links to them from the standard * HTML documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#linksource">linksource</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${linksource}" default-value="false" */ private boolean linksource; /** * Suppress the entire comment body, including the main description and all tags, generating only declarations. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nocomment">nocomment</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * * @parameter expression="${nocomment}" default-value="false" */ private boolean nocomment; /** * Prevents the generation of any deprecated API at all in the documentation. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nodeprecated">nodeprecated</a>. * <br/> * * @parameter expression="${nodeprecated}" default-value="false" */ private boolean nodeprecated; /** * Prevents the generation of the file containing the list of deprecated APIs (deprecated-list.html) and the * link in the navigation bar to that page. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nodeprecatedlist"> * nodeprecatedlist</a>. * <br/> * * @parameter expression="${nodeprecatedlist}" default-value="false" */ private boolean nodeprecatedlist; /** * Omits the HELP link in the navigation bars at the top and bottom of each page of output. * <br/> * <b>Note</b>: could be in conflict with &lt;helpfile/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nohelp">nohelp</a>. * <br/> * * @parameter expression="${nohelp}" default-value="false" */ private boolean nohelp; /** * Omits the index from the generated docs. * <br/> * <b>Note</b>: could be in conflict with &lt;splitindex/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#noindex">noindex</a>. * <br/> * * @parameter expression="${noindex}" default-value="false" */ private boolean noindex; /** * Omits the navigation bar from the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nonavbar">nonavbar</a>. * <br/> * * @parameter expression="${nonavbar}" default-value="false" */ private boolean nonavbar; /** * Omits the entire overview page from the generated docs. * <br/> * <b>Note</b>: could be in conflict with &lt;overview/&gt;. * <br/> * Standard Doclet undocumented option. * <br/> * * @since 2.4 * @parameter expression="${nooverview}" default-value="false" */ private boolean nooverview; /** * Omits qualifying package name from ahead of class names in output. * Example: * <pre> * &lt;noqualifier&gt;all&lt;/noqualifier&gt; * or * &lt;noqualifier&gt;packagename1:packagename2&lt;/noqualifier&gt; * </pre> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#noqualifier">noqualifier</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${noqualifier}" */ private String noqualifier; /** * Omits from the generated docs the "Since" sections associated with the since tags. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#nosince">nosince</a>. * <br/> * * @parameter expression="${nosince}" default-value="false" */ private boolean nosince; /** * Suppresses the timestamp, which is hidden in an HTML comment in the generated HTML near the top of each page. * <br/> * See <a href="http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/javadoc.html#notimestamp">notimestamp</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.5.0/docs/guide/javadoc/whatsnew-1.5.0.html#commandlineoptions"> * Java 5.0</a>. * <br/> * * @since 2.1 * @parameter expression="${notimestamp}" default-value="false" */ private boolean notimestamp; /** * Omits the class/interface hierarchy pages from the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#notree">notree</a>. * <br/> * * @parameter expression="${notree}" default-value="false" */ private boolean notree; /** * This option is a variation of <code>-link</code>; they both create links to javadoc-generated documentation * for external referenced classes. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#linkoffline">linkoffline</a>. * <br/> * Example: * <pre> * &lt;offlineLinks&gt; * &nbsp;&nbsp;&lt;offlineLink&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;url&gt;http://java.sun.com/j2se/1.5.0/docs/api/&lt;/url&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;location&gt;../javadoc/jdk-5.0/&lt;/location&gt; * &nbsp;&nbsp;&lt;/offlineLink&gt; * &lt;/offlineLinks&gt; * </pre> * <br/> * <b>Note</b>: if {@link #detectOfflineLinks} is defined, the offline links between the project modules are * automatically added if the goal is calling in a non-aggregator way. * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/OfflineLink.html">Javadoc</a>. * <br/> * * @parameter expression="${offlineLinks}" */ private OfflineLink[] offlineLinks; /** * Specifies the destination directory where javadoc saves the generated HTML files. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#d">d</a>. * <br/> * * @parameter expression="${destDir}" alias="destDir" default-value="${project.build.directory}/apidocs" * @required */ protected File outputDirectory; /** * Specify the text for upper left frame. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * Java 1.4.2</a>. * * @since 2.1 * @parameter expression="${packagesheader}" */ private String packagesheader; /** * Generates compile-time warnings for missing serial tags. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#serialwarn">serialwarn</a> * <br/> * * @parameter expression="${serialwarn}" default-value="false" */ private boolean serialwarn; /** * Specify the number of spaces each tab takes up in the source. If no tab is used in source, the default * space is used. * <br/> * Note: was <code>linksourcetab</code> in Java 1.4.2 (refer to bug ID * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4788919">4788919</a>). * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.2.html#commandlineoptions"> * 1.4.2</a>. * <br/> * Since Java 5.0. * * @since 2.1 * @parameter expression="${sourcetab}" alias="linksourcetab" */ private int sourcetab; /** * Splits the index file into multiple files, alphabetically, one file per letter, plus a file for any index * entries that start with non-alphabetical characters. * <br/> * <b>Note</b>: could be in conflict with &lt;noindex/&gt;. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#splitindex">splitindex</a>. * <br/> * * @parameter expression="${splitindex}" default-value="false" */ private boolean splitindex; /** * Specifies whether the stylesheet to be used is the <code>maven</code>'s javadoc stylesheet or * <code>java</code>'s default stylesheet when a <i>stylesheetfile</i> parameter is not specified. * <br/> * Possible values: <code>maven<code> or <code>java</code>. * <br/> * * @parameter expression="${stylesheet}" default-value="java" */ private String stylesheet; /** * Specifies the path of an alternate HTML stylesheet file. * <br/> * The <code>stylesheetfile</code> could be an absolute File path. * <br/> * Since 2.6, it could be also be a path from a resource in the current project source directories * (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies, for instance: * <pre> * &lt;stylesheetfile&gt;path/to/your/resource/yourstylesheet.css&lt;/stylesheetfile&gt; * </pre> * Where <code>path/to/your/resource/yourstylesheet.css</code> could be in <code>src/main/javadoc</code>. * <pre> * &lt;build&gt; * &nbsp;&nbsp;&lt;plugins&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;maven-javadoc-plugin&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;stylesheetfile&gt;path/to/your/resource/yourstylesheet.css&lt;/stylesheetfile&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/configuration&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;groupId&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifactId&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependency&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;/dependencies&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/plugin&gt; * &nbsp;&nbsp;&nbsp;&nbsp;... * &nbsp;&nbsp;&lt;plugins&gt; * &lt;/build&gt; * </pre> * Where <code>path/to/your/resource/yourstylesheet.css</code> is defined in the * <code>groupId:artifactId:version</code> javadoc plugin dependency. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#stylesheetfile"> * stylesheetfile</a>. * * @parameter expression="${stylesheetfile}" */ private String stylesheetfile; /** * Specifies the class file that starts the taglet used in generating the documentation for that tag. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${taglet}" */ private String taglet; /** * Specifies the Taglet artifact containing the taglet class files (.class). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;taglets&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;com.sun.tools.doclets.ToDoTaglet&lt;/tagletClass&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;package.to.AnotherTagletClass&lt;/tagletClass&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &nbsp;&nbsp;... * &lt;/taglets&gt; * &lt;tagletArtifact&gt; * &nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &lt;/tagletArtifact&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/TagletArtifact.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${tagletArtifact}" */ private TagletArtifact tagletArtifact; /** * Specifies several Taglet artifacts containing the taglet class files (.class). These taglets class names will be * auto-detect and so no need to specify them. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;tagletArtifacts&gt; * &nbsp;&nbsp;&lt;tagletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &nbsp;&nbsp;&lt;/tagletArtifact&gt; * &nbsp;&nbsp;... * &lt;/tagletArtifacts&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/TagletArtifact.html">Javadoc</a>. * <br/> * * @since 2.5 * @parameter expression="${tagletArtifacts}" */ private TagletArtifact[] tagletArtifacts; /** * Specifies the search paths for finding taglet class files (.class). The <code>tagletpath</code> can contain * multiple paths by separating them with a colon (<code>:</code>) or a semi-colon (<code>;</code>). * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * * @parameter expression="${tagletpath}" */ private String tagletpath; /** * Enables the Javadoc tool to interpret multiple taglets. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#taglet">taglet</a>. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tagletpath">tagletpath</a>. * <br/> * Example: * <pre> * &lt;taglets&gt; * &nbsp;&nbsp;&lt;taglet&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletClass&gt;com.sun.tools.doclets.ToDoTaglet&lt;/tagletClass&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;!--&lt;tagletpath&gt;/home/taglets&lt;/tagletpath&gt;--&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;tagletArtifact&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;groupId&gt;group-Taglet&lt;/groupId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;artifactId&gt;artifact-Taglet&lt;/artifactId&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;version&gt;version-Taglet&lt;/version&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;/tagletArtifact&gt; * &nbsp;&nbsp;&lt;/taglet&gt; * &lt;/taglets&gt; * </pre> * <br/> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Taglet.html">Javadoc</a>. * <br/> * * @since 2.1 * @parameter expression="${taglets}" */ private Taglet[] taglets; /** * Enables the Javadoc tool to interpret a simple, one-argument custom block tag tagname in doc comments. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#tag">tag</a>. * <br/> * Since <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#summary">Java 1.4</a>. * <br/> * Example: * <pre> * &lt;tags&gt; * &nbsp;&nbsp;&lt;tag&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;name&gt;todo&lt;/name&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;placement&gt;a&lt;/placement&gt; * &nbsp;&nbsp;&nbsp;&nbsp;&lt;head&gt;To Do:&lt;/head&gt; * &nbsp;&nbsp;&lt;/tag&gt; * &lt;/tags&gt; * </pre> * <b>Note</b>: the placement should be a combinaison of Xaoptcmf letters: * <ul> * <li><b><code>X</code></b> (disable tag)</li> * <li><b><code>a</code></b> (all)</li> * <li><b><code>o</code></b> (overview)</li> * <li><b><code>p</code></b> (packages)</li> * <li><b><code>t</code></b> (types, that is classes and interfaces)</li> * <li><b><code>c</code></b> (constructors)</li> * <li><b><code>m</code></b> (methods)</li> * <li><b><code>f</code></b> (fields)</li> * </ul> * See <a href="./apidocs/org/apache/maven/plugin/javadoc/options/Tag.html">Javadoc</a>. * <br/> * * @parameter expression="${tags}" */ private Tag[] tags; /** * Specifies the top text to be placed at the top of each output file. * <br/> * See <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6227616">6227616</a>. * <br/> * Since Java 6.0 * * @since 2.4 * @parameter expression="${top}" */ private String top; /** * Includes one "Use" page for each documented class and package. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#use">use</a>. * <br/> * * @parameter expression="${use}" default-value="true" */ private boolean use; /** * Includes the version text in the generated docs. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#version">version</a>. * <br/> * * @parameter expression="${version}" default-value="true" */ private boolean version; /** * Specifies the title to be placed in the HTML title tag. * <br/> * See <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#windowtitle">windowtitle</a>. * <br/> * * @parameter expression="${windowtitle}" default-value="${project.name} ${project.version} API" */ private String windowtitle; // ---------------------------------------------------------------------- // static // ---------------------------------------------------------------------- static { DEFAULT_JAVA_API_LINKS.put( "api_1.3", "http://java.sun.com/j2se/1.3/docs/api" ); DEFAULT_JAVA_API_LINKS.put( "api_1.4", "http://java.sun.com/j2se/1.4.2/docs/api/" ); DEFAULT_JAVA_API_LINKS.put( "api_1.5", "http://java.sun.com/j2se/1.5.0/docs/api/" ); DEFAULT_JAVA_API_LINKS.put( "api_1.6", "http://java.sun.com/javase/6/docs/api/" ); } // ---------------------------------------------------------------------- // protected methods // ---------------------------------------------------------------------- /** * Indicates whether this goal is flagged with <code>@aggregator</code>. * * @return <code>true</code> if the goal is designed as an aggregator, <code>false</code> otherwise. * @see AggregatorJavadocReport * @see AggregatorTestJavadocReport */ protected boolean isAggregator() { return false; } /** * @return the output directory */ protected String getOutputDirectory() { return outputDirectory.getAbsoluteFile().toString(); } /** * @param p not null maven project * @return the list of directories where compiled classes are placed for the given project. These dirs are * added in the javadoc classpath. */ protected List getProjectBuildOutputDirs( MavenProject p ) { if ( StringUtils.isEmpty( p.getBuild().getOutputDirectory() ) ) { return Collections.EMPTY_LIST; } return Collections.singletonList( p.getBuild().getOutputDirectory() ); } /** * @param p not null maven project * @return the list of source paths for the given project */ protected List getProjectSourceRoots( MavenProject p ) { if ( "pom".equals( p.getPackaging().toLowerCase() ) ) { return Collections.EMPTY_LIST; } return ( p.getCompileSourceRoots() == null ? Collections.EMPTY_LIST : new LinkedList( p.getCompileSourceRoots() ) ); } /** * @param p not null maven project * @return the list of source paths for the execution project of the given project */ protected List getExecutionProjectSourceRoots( MavenProject p ) { if ( "pom".equals( p.getExecutionProject().getPackaging().toLowerCase() ) ) { return Collections.EMPTY_LIST; } return ( p.getExecutionProject().getCompileSourceRoots() == null ? Collections.EMPTY_LIST : new LinkedList( p.getExecutionProject().getCompileSourceRoots() ) ); } /** * @param p not null maven project * @return the list of artifacts for the given project */ protected List getProjectArtifacts( MavenProject p ) { return ( p.getCompileArtifacts() == null ? Collections.EMPTY_LIST : new LinkedList( p.getCompileArtifacts() ) ); } /** * @return the current javadoc directory */ protected File getJavadocDirectory() { return javadocDirectory; } /** * @return the title to be placed near the top of the overview summary file */ protected String getDoctitle() { return doctitle; } /** * @return the overview documentation file from the user parameter or from the <code>javadocdirectory</code> */ protected File getOverview() { return overview; } /** * @return the title to be placed in the HTML title tag */ protected String getWindowtitle() { return windowtitle; } /** * @return the charset attribute or the value of {@link #getDocencoding()} if <code>null</code>. */ private String getCharset() { return ( StringUtils.isEmpty( charset ) ) ? getDocencoding() : charset; } /** * @return the docencoding attribute or <code>UTF-8</code> if <code>null</code>. */ private String getDocencoding() { return ( StringUtils.isEmpty( docencoding ) ) ? ReaderFactory.UTF_8 : docencoding; } /** * @return the encoding attribute or the value of <code>file.encoding</code> system property if <code>null</code>. */ private String getEncoding() { return ( StringUtils.isEmpty( encoding ) ) ? ReaderFactory.FILE_ENCODING : encoding; } /** * The <a href="package-summary.html">package documentation</a> details the * Javadoc Options used by this Plugin. * * @param unusedLocale the wanted locale (actually unused). * @throws MavenReportException if any */ protected void executeReport( Locale unusedLocale ) throws MavenReportException { if ( skip ) { getLog().info( "Skipping javadoc generation" ); return; } if ( isAggregator() && !project.isExecutionRoot() ) { return; } if ( getLog().isDebugEnabled() ) { this.debug = true; } List sourcePaths = getSourcePaths(); List files = getFiles( sourcePaths ); if ( !canGenerateReport( files ) ) { return; } List packageNames = getPackageNames( sourcePaths, files ); List filesWithUnnamedPackages = getFilesWithUnnamedPackages( sourcePaths, files ); // ---------------------------------------------------------------------- // Find the javadoc executable and version // ---------------------------------------------------------------------- String jExecutable; try { jExecutable = getJavadocExecutable(); } catch ( IOException e ) { throw new MavenReportException( "Unable to find javadoc command: " + e.getMessage(), e ); } setFJavadocVersion( new File( jExecutable ) ); // ---------------------------------------------------------------------- // Javadoc output directory as File // ---------------------------------------------------------------------- File javadocOutputDirectory = new File( getOutputDirectory() ); if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.isDirectory() ) { throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not a directory." ); } if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.canWrite() ) { throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not writable." ); } javadocOutputDirectory.mkdirs(); // ---------------------------------------------------------------------- // Copy all resources // ---------------------------------------------------------------------- copyAllResources( javadocOutputDirectory ); // ---------------------------------------------------------------------- // Create command line for Javadoc // ---------------------------------------------------------------------- Commandline cmd = new Commandline(); cmd.getShell().setQuotedArgumentsEnabled( false ); // for Javadoc JVM args cmd.setWorkingDirectory( javadocOutputDirectory.getAbsolutePath() ); cmd.setExecutable( jExecutable ); // ---------------------------------------------------------------------- // Wrap Javadoc JVM args // ---------------------------------------------------------------------- addMemoryArg( cmd, "-Xmx", this.maxmemory ); addMemoryArg( cmd, "-Xms", this.minmemory ); addProxyArg( cmd ); if ( StringUtils.isNotEmpty( additionalJOption ) ) { cmd.createArg().setValue( additionalJOption ); } List arguments = new ArrayList(); // ---------------------------------------------------------------------- // Wrap Javadoc options // ---------------------------------------------------------------------- addJavadocOptions( arguments, sourcePaths ); // ---------------------------------------------------------------------- // Wrap Standard doclet Options // ---------------------------------------------------------------------- if ( StringUtils.isEmpty( doclet ) || useStandardDocletOptions ) { addStandardDocletOptions( javadocOutputDirectory, arguments ); } // ---------------------------------------------------------------------- // Write options file and include it in the command line // ---------------------------------------------------------------------- if ( arguments.size() > 0 ) { addCommandLineOptions( cmd, arguments, javadocOutputDirectory ); } // ---------------------------------------------------------------------- // Write packages file and include it in the command line // ---------------------------------------------------------------------- if ( !packageNames.isEmpty() ) { addCommandLinePackages( cmd, javadocOutputDirectory, packageNames ); // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- if ( !filesWithUnnamedPackages.isEmpty() ) { addCommandLineArgFile( cmd, javadocOutputDirectory, filesWithUnnamedPackages ); } } else { // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- if ( !files.isEmpty() ) { addCommandLineArgFile( cmd, javadocOutputDirectory, files ); } } // ---------------------------------------------------------------------- // Execute command line // ---------------------------------------------------------------------- executeJavadocCommandLine( cmd, javadocOutputDirectory ); // delete generated javadoc files only if no error and no debug mode if ( !debug ) { for ( int i = 0; i < cmd.getArguments().length; i++) { String arg = cmd.getArguments()[i].trim(); if ( !arg.startsWith( "@" )) { continue; } File argFile = new File( javadocOutputDirectory, arg.substring( 1 ) ); if ( argFile.exists() ) { argFile.deleteOnExit(); } } File scriptFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); if ( scriptFile.exists() ) { scriptFile.deleteOnExit(); } } } /** * Method to get the files on the specified source paths * * @param sourcePaths a List that contains the paths to the source files * @return a List that contains the specific path for every source file */ protected List getFiles( List sourcePaths ) { List files = new ArrayList(); if ( StringUtils.isEmpty( subpackages ) ) { String[] excludedPackages = getExcludedPackages(); for ( Iterator i = sourcePaths.iterator(); i.hasNext(); ) { File sourceDirectory = new File( (String) i.next() ); JavadocUtil.addFilesFromSource( files, sourceDirectory, excludedPackages ); } } return files; } /** * Method to get the source paths. If no source path is specified in the parameter, the compile source roots * of the project will be used. * * @return a List of the project absolute source paths as <code>String</code> * @see JavadocUtil#pruneDirs(MavenProject, List) */ protected List getSourcePaths() { List sourcePaths; if ( StringUtils.isEmpty( sourcepath ) ) { sourcePaths = new ArrayList( JavadocUtil.pruneDirs( project, getProjectSourceRoots( project ) ) ); if ( project.getExecutionProject() != null ) { sourcePaths.addAll( JavadocUtil.pruneDirs( project, getExecutionProjectSourceRoots( project ) ) ); } /* * Should be after the source path (i.e. -sourcepath '.../src/main/java;.../src/main/javadoc') and * *not* the opposite. If not, the javadoc tool always copies doc files, even if -docfilessubdirs is * not setted. */ if ( getJavadocDirectory() != null ) { File javadocDir = getJavadocDirectory(); if ( javadocDir.exists() && javadocDir.isDirectory() ) { List l = JavadocUtil.pruneDirs( project, Collections.singletonList( getJavadocDirectory().getAbsolutePath() ) ); sourcePaths.addAll( l ); } } if ( isAggregator() && project.isExecutionRoot() ) { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { List sourceRoots = getProjectSourceRoots( subProject ); if ( subProject.getExecutionProject() != null ) { sourceRoots.addAll( getExecutionProjectSourceRoots( subProject ) ); } ArtifactHandler artifactHandler = subProject.getArtifact().getArtifactHandler(); if ( "java".equals( artifactHandler.getLanguage() ) ) { sourcePaths.addAll( JavadocUtil.pruneDirs( subProject, sourceRoots ) ); } String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getJavadocDirectory().getAbsolutePath() ); File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); if ( javadocDir.exists() && javadocDir.isDirectory() ) { List l = JavadocUtil.pruneDirs( subProject, Collections.singletonList( javadocDir.getAbsolutePath() ) ); sourcePaths.addAll( l ); } } } } } else { sourcePaths = new ArrayList( Arrays.asList( JavadocUtil.splitPath( sourcepath ) ) ); sourcePaths = JavadocUtil.pruneDirs( project, sourcePaths ); if ( getJavadocDirectory() != null ) { List l = JavadocUtil.pruneDirs( project, Collections.singletonList( getJavadocDirectory().getAbsolutePath() ) ); sourcePaths.addAll( l ); } } sourcePaths = JavadocUtil.pruneDirs( project, sourcePaths ); return sourcePaths; } /** * Method that indicates whether the javadoc can be generated or not. If the project does not contain any source * files and no subpackages are specified, the plugin will terminate. * * @param files the project files * @return a boolean that indicates whether javadoc report can be generated or not */ protected boolean canGenerateReport( List files ) { boolean canGenerate = true; if ( files.isEmpty() && StringUtils.isEmpty( subpackages ) ) { canGenerate = false; } return canGenerate; } /** * @param result not null * @return the compile artifacts from the result * @see JavadocUtil#getCompileArtifacts(Set, boolean) */ protected List getCompileArtifacts( ArtifactResolutionResult result ) { return JavadocUtil.getCompileArtifacts( result.getArtifacts(), false ); } // ---------------------------------------------------------------------- // private methods // ---------------------------------------------------------------------- /** * Method to get the excluded source files from the javadoc and create the argument string * that will be included in the javadoc commandline execution. * * @param sourcePaths the list of paths to the source files * @return a String that contains the exclude argument that will be used by javadoc */ private String getExcludedPackages( List sourcePaths ) { List excludedNames = null; if ( StringUtils.isNotEmpty( sourcepath ) && StringUtils.isNotEmpty( subpackages ) ) { String[] excludedPackages = getExcludedPackages(); String[] subpackagesList = subpackages.split( "[:]" ); excludedNames = JavadocUtil.getExcludedNames( sourcePaths, subpackagesList, excludedPackages ); } String excludeArg = ""; if ( StringUtils.isNotEmpty( subpackages ) && excludedNames != null ) { // add the excludedpackage names for ( Iterator it = excludedNames.iterator(); it.hasNext(); ) { String str = (String) it.next(); excludeArg = excludeArg + str; if ( it.hasNext() ) { excludeArg = excludeArg + ":"; } } } return excludeArg; } /** * Method to format the specified source paths that will be accepted by the javadoc tool. * * @param sourcePaths the list of paths to the source files that will be included in the javadoc. * @return a String that contains the formatted source path argument, separated by the System pathSeparator * string (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @see File#pathSeparator */ private String getSourcePath( List sourcePaths ) { String sourcePath = null; if ( StringUtils.isEmpty( subpackages ) || StringUtils.isNotEmpty( sourcepath ) ) { sourcePath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); } return sourcePath; } /** * Method to get the packages specified in the <code>excludePackageNames</code> parameter. The packages are split * with ',', ':', or ';' and then formatted. * * @return an array of String objects that contain the package names */ private String[] getExcludedPackages() { String[] excludePackages = {}; // for the specified excludePackageNames if ( excludePackageNames != null ) { excludePackages = excludePackageNames.split( "[,:;]" ); } for ( int i = 0; i < excludePackages.length; i++ ) { excludePackages[i] = excludePackages[i].replace( '.', File.separatorChar ); } return excludePackages; } /** * Method that sets the classpath elements that will be specified in the javadoc <code>-classpath</code> * parameter. * * @return a String that contains the concatenated classpath elements, separated by the System pathSeparator * string (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any. * @see File#pathSeparator */ private String getClasspath() throws MavenReportException { List classpathElements = new ArrayList(); Map compileArtifactMap = new HashMap(); classpathElements.addAll( getProjectBuildOutputDirs( project ) ); populateCompileArtifactMap( compileArtifactMap, getProjectArtifacts( project ) ); if ( isAggregator() && project.isExecutionRoot() ) { try { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { classpathElements.addAll( getProjectBuildOutputDirs( subProject ) ); Set dependencyArtifacts = subProject.createArtifacts( factory, null, null ); if ( !dependencyArtifacts.isEmpty() ) { ArtifactResolutionResult result = null; try { result = resolver.resolveTransitively( dependencyArtifacts, subProject.getArtifact(), subProject.getManagedVersionMap(), localRepository, subProject.getRemoteArtifactRepositories(), artifactMetadataSource ); } catch ( MultipleArtifactsNotFoundException e ) { if ( checkMissingArtifactsInReactor( dependencyArtifacts, e.getMissingArtifacts() ) ) { getLog().warn( "IGNORED to add some artifacts in the classpath. See above." ); } else { // we can't find all the artifacts in the reactor so bubble the exception up. throw new MavenReportException( e.getMessage(), e ); } } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( e.getMessage(), e ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( e.getMessage(), e ); } if ( result == null ) { continue; } populateCompileArtifactMap( compileArtifactMap, getCompileArtifacts( result ) ); if ( getLog().isDebugEnabled() ) { StringBuffer sb = new StringBuffer(); sb.append( "Compiled artifacts for " ); sb.append( subProject.getGroupId() ).append( ":" ); sb.append( subProject.getArtifactId() ).append( ":" ); sb.append( subProject.getVersion() ).append( '\n' ); for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); sb.append( a.getFile() ).append( '\n' ); } getLog().debug( sb.toString() ); } } } } } catch ( InvalidDependencyVersionException e ) { throw new MavenReportException( e.getMessage(), e ); } } for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); classpathElements.add( a.getFile() ); } return StringUtils.join( classpathElements.iterator(), File.pathSeparator ); } /** * TODO remove the part with ToolchainManager lookup once we depend on * 3.0.9 (have it as prerequisite). Define as regular component field then. * * @return Toolchain instance */ private Toolchain getToolchain() { Toolchain tc = null; if ( toolchainManager != null ) { tc = toolchainManager.getToolchainFromBuildContext( "jdk", session ); } return tc; } /** * Method to put the artifacts in the hashmap. * * @param compileArtifactMap the hashmap that will contain the artifacts * @param artifactList the list of artifacts that will be put in the map * @throws MavenReportException if any */ private void populateCompileArtifactMap( Map compileArtifactMap, Collection artifactList ) throws MavenReportException { if ( artifactList != null ) { for ( Iterator i = artifactList.iterator(); i.hasNext(); ) { Artifact newArtifact = (Artifact) i.next(); File file = newArtifact.getFile(); if ( file == null ) { throw new MavenReportException( "Error in plugin descriptor - " + "dependency was not resolved for artifact: " + newArtifact.getGroupId() + ":" + newArtifact.getArtifactId() + ":" + newArtifact.getVersion() ); } if ( compileArtifactMap.get( newArtifact.getDependencyConflictId() ) != null ) { Artifact oldArtifact = (Artifact) compileArtifactMap.get( newArtifact.getDependencyConflictId() ); ArtifactVersion oldVersion = new DefaultArtifactVersion( oldArtifact.getVersion() ); ArtifactVersion newVersion = new DefaultArtifactVersion( newArtifact.getVersion() ); if ( newVersion.compareTo( oldVersion ) > 0 ) { compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); } } else { compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); } } } } /** * Method that sets the bottom text that will be displayed on the bottom of the * javadocs. * * @return a String that contains the text that will be displayed at the bottom of the javadoc */ private String getBottomText() { int actualYear = Calendar.getInstance().get( Calendar.YEAR ); String year = String.valueOf( actualYear ); String inceptionYear = project.getInceptionYear(); String theBottom = StringUtils.replace( this.bottom, "{currentYear}", year ); if ( inceptionYear != null ) { if ( inceptionYear.equals( year ) ) { theBottom = StringUtils.replace( theBottom, "{inceptionYear}-", "" ); } else { theBottom = StringUtils.replace( theBottom, "{inceptionYear}", inceptionYear ); } } else { theBottom = StringUtils.replace( theBottom, "{inceptionYear}-", "" ); } if ( project.getOrganization() == null ) { theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); } else { if ( StringUtils.isNotEmpty( project.getOrganization().getName() ) ) { if ( StringUtils.isNotEmpty( project.getOrganization().getUrl() ) ) { theBottom = StringUtils.replace( theBottom, "{organizationName}", "<a href=\"" + project.getOrganization().getUrl() + "\">" + project.getOrganization().getName() + "</a>" ); } else { theBottom = StringUtils.replace( theBottom, "{organizationName}", project.getOrganization().getName() ); } } else { theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); } } return theBottom; } /** * Method to get the stylesheet path file to be used by the Javadoc Tool. * <br/> * If the {@link #stylesheetfile} is empty, return the file as String definded by {@link #stylesheet} value. * <br/> * If the {@link #stylesheetfile} is defined, return the file as String. * <br/> * Note: since 2.6, the {@link #stylesheetfile} could be a path from a resource in the project source * directories (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies. * * @param javadocOutputDirectory the output directory * @return the stylesheet file absolute path as String. * @see #getResource(List, String) */ private String getStylesheetFile( final File javadocOutputDirectory ) { if ( StringUtils.isEmpty( stylesheetfile ) ) { if ( "java".equalsIgnoreCase( stylesheet ) ) { // use the default Javadoc tool stylesheet return null; } // maven, see #copyDefaultStylesheet(File) return new File( javadocOutputDirectory, DEFAULT_CSS_NAME ).getAbsolutePath(); } if ( new File( stylesheetfile ).exists() ) { return new File( stylesheetfile ).getAbsolutePath(); } return getResource( new File( javadocOutputDirectory, DEFAULT_CSS_NAME ), stylesheetfile ); } /** * Method to get the help file to be used by the Javadoc Tool. * <br/> * Since 2.6, the {@link #helpfile} could be a path from a resource in the project source * directories (i.e. <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code>) * or from a resource in the Javadoc plugin dependencies. * * @param javadocOutputDirectory the output directory. * @return the help file absolute path as String. * @since 2.6 * @see #getResource(File, String) */ private String getHelpFile( final File javadocOutputDirectory ) { if ( StringUtils.isEmpty( helpfile ) ) { return null; } if ( new File( helpfile ).exists() ) { return new File( helpfile ).getAbsolutePath(); } return getResource( new File( javadocOutputDirectory, "help-doc.html" ), helpfile ); } /** * Method to get the access level for the classes and members to be shown in the generated javadoc. * If the specified access level is not public, protected, package or private, the access level * is set to protected. * * @return the access level */ private String getAccessLevel() { String accessLevel; if ( "public".equalsIgnoreCase( show ) || "protected".equalsIgnoreCase( show ) || "package".equalsIgnoreCase( show ) || "private".equalsIgnoreCase( show ) ) { accessLevel = "-" + show; } else { if ( getLog().isErrorEnabled() ) { getLog().error( "Unrecognized access level to show '" + show + "'. Defaulting to protected." ); } accessLevel = "-protected"; } return accessLevel; } /** * Method to get the path of the bootclass artifacts used in the <code>-bootclasspath</code> option. * * @return a string that contains bootclass path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getBootclassPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( bootclasspathArtifacts != null ) { List bootclassPath = new ArrayList(); for ( int i = 0; i < bootclasspathArtifacts.length; i++ ) { BootclasspathArtifact aBootclasspathArtifact = bootclasspathArtifacts[i]; if ( ( StringUtils.isNotEmpty( aBootclasspathArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aBootclasspathArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aBootclasspathArtifact.getVersion() ) ) ) { bootclassPath.addAll( getArtifactsAbsolutePath( aBootclasspathArtifact ) ); } } bootclassPath = JavadocUtil.pruneFiles( bootclassPath ); path.append( StringUtils.join( bootclassPath.iterator(), File.pathSeparator ) ); } if ( StringUtils.isNotEmpty( bootclasspath ) ) { path.append( JavadocUtil.unifyPathSeparator( bootclasspath ) ); } return path.toString(); } /** * Method to get the path of the doclet artifacts used in the <code>-docletpath</code> option. * * Either docletArtifact or doclectArtifacts can be defined and used, not both, docletArtifact * takes precedence over doclectArtifacts. docletPath is always appended to any result path * definition. * * @return a string that contains doclet path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getDocletPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( !isDocletArtifactEmpty( docletArtifact ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( docletArtifact ).iterator(), File.pathSeparator ) ); } else if ( docletArtifacts != null ) { for ( int i = 0; i < docletArtifacts.length; i++ ) { if ( !isDocletArtifactEmpty( docletArtifacts[i] ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( docletArtifacts[i] ).iterator(), File.pathSeparator ) ); if ( i < docletArtifacts.length - 1 ) { path.append( File.pathSeparator ); } } } } if ( !StringUtils.isEmpty( docletPath ) ) { path.append( JavadocUtil.unifyPathSeparator( docletPath ) ); } if ( StringUtils.isEmpty( path.toString() ) && getLog().isWarnEnabled() ) { getLog().warn( "No docletpath option was found. Please review <docletpath/> or <docletArtifact/>" + " or <doclets/>." ); } return path.toString(); } /** * Verify if a doclet artifact is empty or not * * @param aDocletArtifact could be null * @return <code>true</code> if aDocletArtifact or the groupId/artifactId/version of the doclet artifact is null, * <code>false</code> otherwise. */ private boolean isDocletArtifactEmpty( DocletArtifact aDocletArtifact ) { if ( aDocletArtifact == null ) { return true; } return StringUtils.isEmpty( aDocletArtifact.getGroupId() ) && StringUtils.isEmpty( aDocletArtifact.getArtifactId() ) && StringUtils.isEmpty( aDocletArtifact.getVersion() ); } /** * Method to get the path of the taglet artifacts used in the <code>-tagletpath</code> option. * * @return a string that contains taglet path, separated by the System pathSeparator string * (colon (<code>:</code>) on Solaris or semi-colon (<code>;</code>) on Windows). * @throws MavenReportException if any * @see File#pathSeparator */ private String getTagletPath() throws MavenReportException { StringBuffer path = new StringBuffer(); if ( ( tagletArtifact != null ) && ( StringUtils.isNotEmpty( tagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( tagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( tagletArtifact.getVersion() ) ) ) { path.append( StringUtils.join( getArtifactsAbsolutePath( tagletArtifact ).iterator(), File.pathSeparator ) ); } if ( tagletArtifacts != null ) { List tagletsPath = new ArrayList(); for ( int i = 0; i < tagletArtifacts.length; i++ ) { TagletArtifact aTagletArtifact = tagletArtifacts[i]; if ( ( StringUtils.isNotEmpty( aTagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getVersion() ) ) ) { tagletsPath.addAll( getArtifactsAbsolutePath( aTagletArtifact ) ); } } tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); path.append( StringUtils.join( tagletsPath.iterator(), File.pathSeparator ) ); } if ( taglets != null ) { List tagletsPath = new ArrayList(); for ( int i = 0; i < taglets.length; i++ ) { Taglet current = taglets[i]; if ( current == null ) { continue; } if ( ( current.getTagletArtifact() != null ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getGroupId() ) ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getArtifactId() ) ) && ( StringUtils.isNotEmpty( current.getTagletArtifact().getVersion() ) ) ) { tagletsPath.addAll( getArtifactsAbsolutePath( current.getTagletArtifact() ) ); tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); } else if ( StringUtils.isNotEmpty( current.getTagletpath() ) ) { tagletsPath.add( current.getTagletpath() ); tagletsPath = JavadocUtil.pruneDirs( project, tagletsPath ); } } path.append( StringUtils.join( tagletsPath.iterator(), File.pathSeparator ) ); } if ( StringUtils.isNotEmpty( tagletpath ) ) { path.append( JavadocUtil.unifyPathSeparator( tagletpath ) ); } return path.toString(); } /** * Return the Javadoc artifact path and its transitive dependencies path from the local repository * * @param javadocArtifact not null * @return a list of locale artifacts absolute path * @throws MavenReportException if any */ private List getArtifactsAbsolutePath( JavadocPathArtifact javadocArtifact ) throws MavenReportException { if ( ( StringUtils.isEmpty( javadocArtifact.getGroupId() ) ) && ( StringUtils.isEmpty( javadocArtifact.getArtifactId() ) ) && ( StringUtils.isEmpty( javadocArtifact.getVersion() ) ) ) { return Collections.EMPTY_LIST; } List path = new ArrayList(); try { Artifact artifact = createAndResolveArtifact( javadocArtifact ); path.add( artifact.getFile().getAbsolutePath() ); // Find its transitive dependencies in the local repo MavenProject artifactProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); Set dependencyArtifacts = artifactProject.createArtifacts( factory, null, null ); if ( !dependencyArtifacts.isEmpty() ) { ArtifactResolutionResult result = resolver.resolveTransitively( dependencyArtifacts, artifactProject.getArtifact(), artifactProject.getRemoteArtifactRepositories(), localRepository, artifactMetadataSource ); Set artifacts = result.getArtifacts(); Map compileArtifactMap = new HashMap(); populateCompileArtifactMap( compileArtifactMap, artifacts ); for ( Iterator it = compileArtifactMap.keySet().iterator(); it.hasNext(); ) { String key = it.next().toString(); Artifact a = (Artifact) compileArtifactMap.get( key ); path.add( a.getFile().getAbsolutePath() ); } } return path; } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + javadocArtifact, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + javadocArtifact, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + javadocArtifact, e ); } catch ( InvalidDependencyVersionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + javadocArtifact, e ); } } /** * creates an {@link Artifact} representing the configured {@link JavadocPathArtifact} and resolves it. * * @param javadocArtifact the {@link JavadocPathArtifact} to resolve * @return a resolved {@link Artifact} * @throws ArtifactResolutionException if the resolution of the artifact failed. * @throws ArtifactNotFoundException if the artifact hasn't been found. * @throws ProjectBuildingException if the artifact POM could not be build. */ private Artifact createAndResolveArtifact( JavadocPathArtifact javadocArtifact ) throws ArtifactResolutionException, ArtifactNotFoundException, ProjectBuildingException { Artifact artifact = factory.createProjectArtifact( javadocArtifact.getGroupId(), javadocArtifact.getArtifactId(), javadocArtifact.getVersion(), Artifact.SCOPE_COMPILE ); if ( artifact.getFile() == null ) { MavenProject pluginProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); artifact = pluginProject.getArtifact(); resolver.resolve( artifact, remoteRepositories, localRepository ); } return artifact; } /** * Method that adds/sets the java memory parameters in the command line execution. * * @param cmd the command line execution object where the argument will be added * @param arg the argument parameter name * @param memory the JVM memory value to be set * @see JavadocUtil#parseJavadocMemory(String) */ private void addMemoryArg( Commandline cmd, String arg, String memory ) { if ( StringUtils.isNotEmpty( memory ) ) { try { cmd.createArg().setValue( "-J" + arg + JavadocUtil.parseJavadocMemory( memory ) ); } catch ( IllegalArgumentException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Malformed memory pattern for '" + arg + memory + "'. Ignore this option." ); } } } } /** * Method that adds/sets the javadoc proxy parameters in the command line execution. * * @param cmd the command line execution object where the argument will be added */ private void addProxyArg( Commandline cmd ) { // backward compatible if ( StringUtils.isNotEmpty( proxyHost ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "The Javadoc plugin parameter 'proxyHost' is deprecated since 2.4. " + "Please configure an active proxy in your settings.xml." ); } cmd.createArg().setValue( "-J-DproxyHost=" + proxyHost ); if ( proxyPort > 0 ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "The Javadoc plugin parameter 'proxyPort' is deprecated since 2.4. " + "Please configure an active proxy in your settings.xml." ); } cmd.createArg().setValue( "-J-DproxyPort=" + proxyPort ); } } if ( settings == null || settings.getActiveProxy() == null ) { return; } Proxy activeProxy = settings.getActiveProxy(); String protocol = StringUtils.isNotEmpty( activeProxy.getProtocol() ) ? activeProxy.getProtocol() + "." : ""; if ( StringUtils.isNotEmpty( activeProxy.getHost() ) ) { cmd.createArg().setValue( "-J-D" + protocol + "proxySet=true" ); cmd.createArg().setValue( "-J-D" + protocol + "proxyHost=" + activeProxy.getHost() ); if ( activeProxy.getPort() > 0 ) { cmd.createArg().setValue( "-J-D" + protocol + "proxyPort=" + activeProxy.getPort() ); } if ( StringUtils.isNotEmpty( activeProxy.getNonProxyHosts() ) ) { cmd.createArg().setValue( "-J-D" + protocol + "nonProxyHosts=\"" + activeProxy.getNonProxyHosts() + "\"" ); } if ( StringUtils.isNotEmpty( activeProxy.getUsername() ) ) { cmd.createArg().setValue( "-J-Dhttp.proxyUser=\"" + activeProxy.getUsername() + "\"" ); if ( StringUtils.isNotEmpty( activeProxy.getPassword() ) ) { cmd.createArg().setValue( "-J-Dhttp.proxyPassword=\"" + activeProxy.getPassword() + "\"" ); } } } } /** * Get the path of the Javadoc tool executable depending the user entry or try to find it depending the OS * or the <code>java.home</code> system property or the <code>JAVA_HOME</code> environment variable. * * @return the path of the Javadoc tool * @throws IOException if not found */ private String getJavadocExecutable() throws IOException { Toolchain tc = getToolchain(); if ( tc != null ) { getLog().info( "Toolchain in javadoc-plugin: " + tc ); if ( javadocExecutable != null ) { getLog().warn( "Toolchains are ignored, 'javadocExecutable' parameter is set to " + javadocExecutable ); } else { javadocExecutable = tc.findTool( "javadoc" ); } } String javadocCommand = "javadoc" + ( SystemUtils.IS_OS_WINDOWS ? ".exe" : "" ); File javadocExe; // ---------------------------------------------------------------------- // The javadoc executable is defined by the user // ---------------------------------------------------------------------- if ( StringUtils.isNotEmpty( javadocExecutable ) ) { javadocExe = new File( javadocExecutable ); if ( javadocExe.isDirectory() ) { javadocExe = new File( javadocExe, javadocCommand ); } if ( SystemUtils.IS_OS_WINDOWS && javadocExe.getName().indexOf( '.' ) < 0 ) { javadocExe = new File( javadocExe.getPath() + ".exe" ); } if ( !javadocExe.isFile() ) { throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. Verify the <javadocExecutable/> parameter." ); } return javadocExe.getAbsolutePath(); } // ---------------------------------------------------------------------- // Try to find javadocExe from System.getProperty( "java.home" ) // By default, System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME // should be in the JDK_HOME // ---------------------------------------------------------------------- // For IBM's JDK 1.2 if ( SystemUtils.IS_OS_AIX ) { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "sh", javadocCommand ); } else if ( SystemUtils.IS_OS_MAC_OSX ) { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand ); } else { javadocExe = new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "bin", javadocCommand ); } // ---------------------------------------------------------------------- // Try to find javadocExe from JAVA_HOME environment variable // ---------------------------------------------------------------------- if ( !javadocExe.exists() || !javadocExe.isFile() ) { Properties env = CommandLineUtils.getSystemEnvVars(); String javaHome = env.getProperty( "JAVA_HOME" ); if ( StringUtils.isEmpty( javaHome ) ) { throw new IOException( "The environment variable JAVA_HOME is not correctly set." ); } if ( ( !new File( javaHome ).exists() ) || ( !new File( javaHome ).isDirectory() ) ) { throw new IOException( "The environment variable JAVA_HOME=" + javaHome + " doesn't exist or is not a valid directory." ); } javadocExe = new File( env.getProperty( "JAVA_HOME" ) + File.separator + "bin", javadocCommand ); } if ( !javadocExe.exists() || !javadocExe.isFile() ) { throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable." ); } return javadocExe.getAbsolutePath(); } /** * Set a new value for <code>fJavadocVersion</code> * * @param jExecutable not null * @throws MavenReportException if not found * @see JavadocUtil#getJavadocVersion(File) */ private void setFJavadocVersion( File jExecutable ) throws MavenReportException { float jVersion; try { jVersion = JavadocUtil.getJavadocVersion( jExecutable ); } catch ( IOException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } catch ( CommandLineException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java the version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } catch ( IllegalArgumentException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); getLog().warn( "Using the Java the version instead of, i.e. " + SystemUtils.JAVA_VERSION_FLOAT ); } jVersion = SystemUtils.JAVA_VERSION_FLOAT; } if ( StringUtils.isNotEmpty( javadocVersion ) ) { try { fJavadocVersion = Float.parseFloat( javadocVersion ); } catch ( NumberFormatException e ) { throw new MavenReportException( "Unable to parse javadoc version: " + e.getMessage(), e ); } if ( fJavadocVersion != jVersion && getLog().isWarnEnabled() ) { getLog().warn( "Are you sure about the <javadocVersion/> parameter? It seems to be " + jVersion ); } } else { fJavadocVersion = jVersion; } } /** * Is the Javadoc version at least the requested version. * * @param requiredVersion the required version, for example 1.5f * @return <code>true</code> if the javadoc version is equal or greater than the * required version */ private boolean isJavaDocVersionAtLeast( float requiredVersion ) { return fJavadocVersion >= requiredVersion; } /** * Convenience method to add an argument to the <code>command line</code> * conditionally based on the given flag. * * @param arguments a list of arguments, not null * @param b the flag which controls if the argument is added or not. * @param value the argument value to be added. */ private void addArgIf( List arguments, boolean b, String value ) { if ( b ) { arguments.add( value ); } } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param b the flag which controls if the argument is added or not. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIf(java.util.List,boolean,String) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIf( List arguments, boolean b, String value, float requiredJavaVersion ) { if ( b ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIf( arguments, b, value ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( value + " option is not supported on Java version < " + requiredJavaVersion + ". Ignore this option." ); } } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @see #addArgIfNotEmpty(java.util.List,String,String,boolean) */ private void addArgIfNotEmpty( List arguments, String key, String value ) { addArgIfNotEmpty( arguments, key, value, false ); } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line * @param splitValue if <code>true</code> given value will be tokenized by comma * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIfNotEmpty(List, String, String, boolean, boolean) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, boolean splitValue, float requiredJavaVersion ) { if ( StringUtils.isNotEmpty( value ) ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIfNotEmpty( arguments, key, value, repeatKey, splitValue ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion + ". Ignore this option." ); } } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line * @param splitValue if <code>true</code> given value will be tokenized by comma */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, boolean splitValue ) { if ( StringUtils.isNotEmpty( value ) ) { if ( StringUtils.isNotEmpty( key ) ) { arguments.add( key ); } if ( splitValue ) { StringTokenizer token = new StringTokenizer( value, "," ); while ( token.hasMoreTokens() ) { String current = token.nextToken().trim(); if ( StringUtils.isNotEmpty( current ) ) { arguments.add( current ); if ( token.hasMoreTokens() && repeatKey ) { arguments.add( key ); } } } } else { arguments.add( value ); } } } /** * Convenience method to add an argument to the <code>command line</code> * if the the value is not null or empty. * <p/> * Moreover, the value could be comma separated. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line */ private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey ) { addArgIfNotEmpty( arguments, key, value, repeatKey, true ); } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIfNotEmpty(java.util.List, String, String, float, boolean) */ private void addArgIfNotEmpty( List arguments, String key, String value, float requiredJavaVersion ) { addArgIfNotEmpty( arguments, key, value, requiredJavaVersion, false ); } /** * Convenience method to add an argument to the <code>command line</code> * regarding the requested Java version. * * @param arguments a list of arguments, not null * @param key the argument name. * @param value the argument value to be added. * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @param repeatKey repeat or not the key in the command line * @see #addArgIfNotEmpty(java.util.List,String,String) * @see #isJavaDocVersionAtLeast(float) */ private void addArgIfNotEmpty( List arguments, String key, String value, float requiredJavaVersion, boolean repeatKey ) { if ( StringUtils.isNotEmpty( value ) ) { if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) { addArgIfNotEmpty( arguments, key, value, repeatKey ); } else { if ( getLog().isWarnEnabled() ) { getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion ); } } } } /** * Convenience method to process {@link #offlineLinks} values as individual <code>-linkoffline</code> * javadoc options. * <br/> * If {@link #detectOfflineLinks}, try to add javadoc apidocs according Maven conventions for all modules given * in the project. * * @param arguments a list of arguments, not null * @throws MavenReportException if any * @see #offlineLinks * @see #getModulesLinks() * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package-list">package-list spec</a> */ private void addLinkofflineArguments( List arguments ) throws MavenReportException { List offlineLinksList = ( offlineLinks != null ? new ArrayList( Arrays.asList( offlineLinks ) ) : new ArrayList() ); offlineLinksList.addAll( getModulesLinks() ); if ( offlineLinksList != null ) { for ( int i = 0; i < offlineLinksList.size(); i++ ) { OfflineLink offlineLink = (OfflineLink) offlineLinksList.get( i ); String url = offlineLink.getUrl(); if ( StringUtils.isEmpty( url ) ) { continue; } url = cleanUrl( url ); String location = offlineLink.getLocation(); if ( StringUtils.isEmpty( location ) ) { continue; } if ( isValidJavadocLink( location ) ) { addArgIfNotEmpty( arguments, "-linkoffline", JavadocUtil.quotedPathArgument( url ) + " " + JavadocUtil.quotedPathArgument( location ), true ); } } } } /** * Convenience method to process {@link #links} values as individual <code>-link</code> javadoc options. * If {@link #detectLinks}, try to add javadoc apidocs according Maven conventions for all dependencies given * in the project. * <br/> * According the Javadoc documentation, all defined link should have <code>${link}/package-list</code> fetchable. * <br/> * <b>Note</b>: when a link is not fetchable: * <ul> * <li>Javadoc 1.4 and less throw an exception</li> * <li>Javadoc 1.5 and more display a warning</li> * </ul> * * @param arguments a list of arguments, not null * @see #detectLinks * @see #getDependenciesLinks() * @see JavadocUtil#fetchURL(Settings, URL) * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#package-list">package-list spec</a> */ private void addLinkArguments( List arguments ) { if ( links == null ) { links = new ArrayList(); } String javaApiLink = getDefaultJavadocApiLink(); if ( javaApiLink != null ) { links.add( javaApiLink ); } links.addAll( getDependenciesLinks() ); for ( int i = 0; i < links.size(); i++ ) { String link = (String) links.get( i ); if ( StringUtils.isEmpty( link ) ) { continue; } while ( link.endsWith( "/" ) ) { link = link.substring( 0, link.lastIndexOf( "/" ) ); } if ( isValidJavadocLink( link ) ) { addArgIfNotEmpty( arguments, "-link", JavadocUtil.quotedPathArgument( link ), true ); } } } /** * Coppy all resources to the output directory * * @param javadocOutputDirectory not null * @throws MavenReportException if any * @see #copyDefaultStylesheet(File) * @see #copyJavadocResources(File) * @see #copyAdditionalJavadocResources(File) */ private void copyAllResources( File javadocOutputDirectory ) throws MavenReportException { // ---------------------------------------------------------------------- // Copy default resources // ---------------------------------------------------------------------- try { copyDefaultStylesheet( javadocOutputDirectory ); } catch ( IOException e ) { throw new MavenReportException( "Unable to copy default stylesheet: " + e.getMessage(), e ); } // ---------------------------------------------------------------------- // Copy javadoc resources // ---------------------------------------------------------------------- if ( docfilessubdirs ) { /* * Workaround since -docfilessubdirs doesn't seem to be used correctly by the javadoc tool * (see other note about -sourcepath). Take care of the -excludedocfilessubdir option. */ try { copyJavadocResources( javadocOutputDirectory ); } catch ( IOException e ) { throw new MavenReportException( "Unable to copy javadoc resources: " + e.getMessage(), e ); } } // ---------------------------------------------------------------------- // Copy additional javadoc resources in artifacts // ---------------------------------------------------------------------- copyAdditionalJavadocResources( javadocOutputDirectory ); } /** * Copies the {@link #DEFAULT_CSS_NAME} css file from the current class * loader to the <code>outputDirectory</code> only if {@link #stylesheetfile} is empty and * {@link #stylesheet} is equals to <code>maven</code>. * * @param anOutputDirectory the output directory * @throws java.io.IOException if any * @see #DEFAULT_CSS_NAME * @see JavadocUtil#copyResource(File, URL) */ private void copyDefaultStylesheet( File anOutputDirectory ) throws IOException { if ( StringUtils.isNotEmpty( stylesheetfile ) ) { return; } if ( !stylesheet.equalsIgnoreCase( "maven" ) ) { return; } URL url = getClass().getClassLoader().getResource( RESOURCE_CSS_DIR + "/" + DEFAULT_CSS_NAME ); File outFile = new File( anOutputDirectory, DEFAULT_CSS_NAME ); JavadocUtil.copyResource( url, outFile ); } /** * Method that copy all <code>doc-files</code> directories from <code>javadocDirectory</code> of * the current projet or of the projects in the reactor to the <code>outputDirectory</code>. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.2.html#docfiles">Reference * Guide, Copies new "doc-files" directory for holding images and examples</a> * @see #docfilessubdirs * * @param anOutputDirectory the output directory * @throws java.io.IOException if any */ private void copyJavadocResources( File anOutputDirectory ) throws IOException { if ( anOutputDirectory == null || !anOutputDirectory.exists() ) { throw new IOException( "The outputDirectory " + anOutputDirectory + " doesn't exists." ); } if ( getJavadocDirectory() != null ) { JavadocUtil.copyJavadocResources( anOutputDirectory, getJavadocDirectory(), excludedocfilessubdir ); } if ( isAggregator() && project.isExecutionRoot() ) { for ( Iterator i = reactorProjects.iterator(); i.hasNext(); ) { MavenProject subProject = (MavenProject) i.next(); if ( subProject != project ) { String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getJavadocDirectory().getAbsolutePath() ); File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); JavadocUtil.copyJavadocResources( anOutputDirectory, javadocDir, excludedocfilessubdir ); } } } } /** * Method that copy additional Javadoc resources from given artifacts. * * @see #resourcesArtifacts * @param anOutputDirectory the output directory * @throws MavenReportException if any */ private void copyAdditionalJavadocResources( File anOutputDirectory ) throws MavenReportException { if ( resourcesArtifacts == null || resourcesArtifacts.length == 0 ) { return; } UnArchiver unArchiver; try { unArchiver = archiverManager.getUnArchiver( "jar" ); } catch ( NoSuchArchiverException e ) { throw new MavenReportException( "Unable to extract resources artifact. " + "No archiver for 'jar' available.", e ); } for ( int i = 0; i < resourcesArtifacts.length; i++ ) { ResourcesArtifact item = resourcesArtifacts[i]; Artifact artifact; try { artifact = createAndResolveArtifact( item ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + item, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + item, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + item, e ); } unArchiver.setSourceFile( artifact.getFile() ); unArchiver.setDestDirectory( anOutputDirectory ); // remove the META-INF directory from resource artifact IncludeExcludeFileSelector[] selectors = new IncludeExcludeFileSelector[] { new IncludeExcludeFileSelector() }; selectors[0].setExcludes( new String[] { "META-INF/**" } ); unArchiver.setFileSelectors( selectors ); getLog().info( "Extracting contents of resources artifact: " + artifact.getArtifactId() ); try { unArchiver.extract(); } catch ( ArchiverException e ) { throw new MavenReportException( "Extraction of resources failed. Artifact that failed was: " + artifact.getArtifactId(), e ); } } } /** * @param sourcePaths could be null * @param files not null * @return the list of package names for files in the sourcePaths */ private List getPackageNames( List sourcePaths, List files ) { return getPackageNamesOrFilesWithUnnamedPackages( sourcePaths, files, true ); } /** * @param sourcePaths could be null * @param files not null * @return a list files with unnamed package names for files in the sourecPaths */ private List getFilesWithUnnamedPackages( List sourcePaths, List files ) { return getPackageNamesOrFilesWithUnnamedPackages( sourcePaths, files, false ); } /** * @param sourcePaths not null, containing absolute and relative paths * @param files not null, containing list of quoted files * @param onlyPackageName boolean for only package name * @return a list of package names or files with unnamed package names, depending the value of the unnamed flag * @see #getFiles(List) * @see #getSourcePaths() */ private List getPackageNamesOrFilesWithUnnamedPackages( List sourcePaths, List files, boolean onlyPackageName ) { List returnList = new ArrayList(); if ( !StringUtils.isEmpty( sourcepath ) ) { return returnList; } for ( Iterator it = files.iterator(); it.hasNext(); ) { String currentFile = (String) it.next(); currentFile = currentFile.replace( '\\', '/' ); for ( Iterator it2 = sourcePaths.iterator(); it2.hasNext(); ) { String currentSourcePath = (String) it2.next(); currentSourcePath = currentSourcePath.replace( '\\', '/' ); if ( !currentSourcePath.endsWith( "/" ) ) { currentSourcePath += "/"; } if ( currentFile.indexOf( currentSourcePath ) != -1 ) { String packagename = currentFile.substring( currentSourcePath.length() + 1 ); /* * Remove the miscellaneous files * http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ if ( packagename.indexOf( "doc-files" ) != -1 ) { continue; } if ( onlyPackageName && packagename.lastIndexOf( "/" ) != -1 ) { packagename = packagename.substring( 0, packagename.lastIndexOf( "/" ) ); packagename = packagename.replace( '/', '.' ); if ( !returnList.contains( packagename ) ) { returnList.add( packagename ); } } if ( !onlyPackageName && packagename.lastIndexOf( "/" ) == -1 ) { returnList.add( currentFile ); } } } } return returnList; } /** * Generate an <code>options</code> file for all options and arguments and add the <code>@options</code> in the * command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files</a> * * @param cmd not null * @param arguments not null * @param javadocOutputDirectory not null * @throws MavenReportException if any * @see #OPTIONS_FILE_NAME */ private void addCommandLineOptions( Commandline cmd, List arguments, File javadocOutputDirectory ) throws MavenReportException { File optionsFile = new File( javadocOutputDirectory, OPTIONS_FILE_NAME ); StringBuffer options = new StringBuffer(); options.append( StringUtils.join( arguments.toArray( new String[0] ), SystemUtils.LINE_SEPARATOR ) ); try { FileUtils.fileWrite( optionsFile.getAbsolutePath(), options.toString() ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + optionsFile.getName() + "' temporary file for command execution", e ); } cmd.createArg().setValue( "@" + OPTIONS_FILE_NAME ); } /** * Generate a file called <code>argfile</code> (or <code>files</code>, depending the JDK) to hold files and add * the <code>@argfile</code> (or <code>@file</code>, depending the JDK) in the command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files * </a> * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/javadoc/whatsnew-1.4.html#runningjavadoc"> * What s New in Javadoc 1.4 * </a> * * @param cmd not null * @param javadocOutputDirectory not null * @param files not null * @throws MavenReportException if any * @see #isJavaDocVersionAtLeast(float) * @see #ARGFILE_FILE_NAME * @see #FILES_FILE_NAME */ private void addCommandLineArgFile( Commandline cmd, File javadocOutputDirectory, List files ) throws MavenReportException { File argfileFile; if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { argfileFile = new File( javadocOutputDirectory, ARGFILE_FILE_NAME ); } else { argfileFile = new File( javadocOutputDirectory, FILES_FILE_NAME ); } try { FileUtils.fileWrite( argfileFile.getAbsolutePath(), StringUtils.join( files.iterator(), SystemUtils.LINE_SEPARATOR ) ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + argfileFile.getName() + "' temporary file for command execution", e ); } if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { cmd.createArg().setValue( "@" + ARGFILE_FILE_NAME ); } else { cmd.createArg().setValue( "@" + FILES_FILE_NAME ); } } /** * Generate a file called <code>packages</code> to hold all package names and add the <code>@packages</code> in * the command line. * * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#argumentfiles"> * Reference Guide, Command line argument files</a> * * @param cmd not null * @param javadocOutputDirectory not null * @param packageNames not null * @throws MavenReportException if any * @see #PACKAGES_FILE_NAME */ private void addCommandLinePackages( Commandline cmd, File javadocOutputDirectory, List packageNames ) throws MavenReportException { File packagesFile = new File( javadocOutputDirectory, PACKAGES_FILE_NAME ); try { FileUtils.fileWrite( packagesFile.getAbsolutePath(), StringUtils.join( packageNames.toArray( new String[0] ), SystemUtils.LINE_SEPARATOR ) ); } catch ( IOException e ) { throw new MavenReportException( "Unable to write '" + packagesFile.getName() + "' temporary file for command execution", e ); } cmd.createArg().setValue( "@" + PACKAGES_FILE_NAME ); } /** * Checks for the validity of the Javadoc options used by the user. * * @throws MavenReportException if error */ private void validateJavadocOptions() throws MavenReportException { // encoding if ( StringUtils.isNotEmpty( getEncoding() ) && !JavadocUtil.validateEncoding( getEncoding() ) ) { throw new MavenReportException( "Unsupported option <encoding/> '" + getEncoding() + "'" ); } // locale if ( StringUtils.isNotEmpty( this.locale ) ) { StringTokenizer tokenizer = new StringTokenizer( this.locale, "_" ); final int maxTokens = 3; if ( tokenizer.countTokens() > maxTokens ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant." ); } Locale localeObject = null; if ( tokenizer.hasMoreTokens() ) { String language = tokenizer.nextToken().toLowerCase( Locale.ENGLISH ); if ( !Arrays.asList( Locale.getISOLanguages() ).contains( language ) ) { throw new MavenReportException( "Unsupported language '" + language + "' in option <locale/> '" + this.locale + "'" ); } localeObject = new Locale( language ); if ( tokenizer.hasMoreTokens() ) { String country = tokenizer.nextToken().toUpperCase( Locale.ENGLISH ); if ( !Arrays.asList( Locale.getISOCountries() ).contains( country ) ) { throw new MavenReportException( "Unsupported country '" + country + "' in option <locale/> '" + this.locale + "'" ); } localeObject = new Locale( language, country ); if ( tokenizer.hasMoreTokens() ) { String variant = tokenizer.nextToken(); localeObject = new Locale( language, country, variant ); } } } if ( localeObject == null ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "', should be language_country_variant." ); } this.locale = localeObject.toString(); final List availableLocalesList = Arrays.asList( Locale.getAvailableLocales() ); if ( StringUtils.isNotEmpty( localeObject.getVariant() ) && !availableLocalesList.contains( localeObject ) ) { StringBuffer sb = new StringBuffer(); sb.append( "Unsupported option <locale/> with variant '" ).append( this.locale ); sb.append( "'" ); localeObject = new Locale( localeObject.getLanguage(), localeObject.getCountry() ); this.locale = localeObject.toString(); sb.append( ", trying to use <locale/> without variant, i.e. '" ).append( this.locale ).append( "'" ); if ( getLog().isWarnEnabled() ) { getLog().warn( sb.toString() ); } } if ( !availableLocalesList.contains( localeObject ) ) { throw new MavenReportException( "Unsupported option <locale/> '" + this.locale + "'" ); } } } /** * Checks for the validity of the Standard Doclet options. * <br/> * For example, throw an exception if &lt;nohelp/&gt; and &lt;helpfile/&gt; options are used together. * * @throws MavenReportException if error or conflict found */ private void validateStandardDocletOptions() throws MavenReportException { // docencoding if ( StringUtils.isNotEmpty( getDocencoding() ) && !JavadocUtil.validateEncoding( getDocencoding() ) ) { throw new MavenReportException( "Unsupported option <docencoding/> '" + getDocencoding() + "'" ); } // charset if ( StringUtils.isNotEmpty( getCharset() ) && !JavadocUtil.validateEncoding( getCharset() ) ) { throw new MavenReportException( "Unsupported option <charset/> '" + getCharset() + "'" ); } // helpfile if ( StringUtils.isNotEmpty( helpfile ) && nohelp ) { throw new MavenReportException( "Option <nohelp/> conflicts with <helpfile/>" ); } // overview if ( ( getOverview() != null ) && nooverview ) { throw new MavenReportException( "Option <nooverview/> conflicts with <overview/>" ); } // index if ( splitindex && noindex ) { throw new MavenReportException( "Option <noindex/> conflicts with <splitindex/>" ); } // stylesheet if ( StringUtils.isNotEmpty( stylesheet ) && !( stylesheet.equalsIgnoreCase( "maven" ) || stylesheet.equalsIgnoreCase( "java" ) ) ) { throw new MavenReportException( "Option <stylesheet/> supports only \"maven\" or \"java\" value." ); } // default java api links if ( javaApiLinks == null || javaApiLinks.size() == 0 ) { javaApiLinks = DEFAULT_JAVA_API_LINKS; } } /** * This method is checking to see if the artifacts that can't be resolved are all * part of this reactor. This is done to prevent a chicken or egg scenario with * fresh projects. See MJAVADOC-116 for more info. * * @param dependencyArtifacts the sibling projects in the reactor * @param missing the artifacts that can't be found * @return true if ALL missing artifacts are found in the reactor. * @see DefaultPluginManager#checkRequiredMavenVersion( plugin, localRepository, remoteRepositories ) */ private boolean checkMissingArtifactsInReactor( Collection dependencyArtifacts, Collection missing ) { Set foundInReactor = new HashSet(); Iterator iter = missing.iterator(); while ( iter.hasNext() ) { Artifact mArtifact = (Artifact) iter.next(); Iterator pIter = reactorProjects.iterator(); while ( pIter.hasNext() ) { MavenProject p = (MavenProject) pIter.next(); if ( p.getArtifactId().equals( mArtifact.getArtifactId() ) && p.getGroupId().equals( mArtifact.getGroupId() ) && p.getVersion().equals( mArtifact.getVersion() ) ) { getLog().warn( "The dependency: [" + p.getId() + "] can't be resolved but has been found in the reactor (probably snapshots).\n" + "This dependency has been excluded from the Javadoc classpath. " + "You should rerun javadoc after executing mvn install." ); // found it, move on. foundInReactor.add( p ); break; } } } // if all of them have been found, we can continue. return foundInReactor.size() == missing.size(); } /** * Add Standard Javadoc Options. * <br/> * The <a href="package-summary.html#Standard_Javadoc_Options">package documentation</a> details the * Standard Javadoc Options wrapped by this Plugin. * * @param arguments not null * @param sourcePaths not null * @throws MavenReportException if any * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#javadocoptions">http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#javadocoptions</a> */ private void addJavadocOptions( List arguments, List sourcePaths ) throws MavenReportException { validateJavadocOptions(); // see com.sun.tools.javadoc.Start#parseAndExecute(String argv[]) addArgIfNotEmpty( arguments, "-locale", JavadocUtil.quotedArgument( this.locale ) ); // all options in alphabetical order if ( old && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Javadoc 1.4+ doesn't support the -1.1 switch anymore. Ignore this option." ); } } else { addArgIf( arguments, old, "-1.1" ); } addArgIfNotEmpty( arguments, "-bootclasspath", JavadocUtil.quotedPathArgument( getBootclassPath() ) ); if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_5 ); } addArgIfNotEmpty( arguments, "-classpath", JavadocUtil.quotedPathArgument( getClasspath() ) ); if ( StringUtils.isNotEmpty( doclet ) ) { addArgIfNotEmpty( arguments, "-doclet", JavadocUtil.quotedArgument( doclet ) ); addArgIfNotEmpty( arguments, "-docletpath", JavadocUtil.quotedPathArgument( getDocletPath() ) ); } if ( StringUtils.isEmpty( encoding ) ) { getLog().warn( "Source files encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!" ); } addArgIfNotEmpty( arguments, "-encoding", JavadocUtil.quotedArgument( getEncoding() ) ); addArgIfNotEmpty( arguments, "-exclude", getExcludedPackages( sourcePaths ), SINCE_JAVADOC_1_4 ); addArgIfNotEmpty( arguments, "-extdirs", JavadocUtil.quotedPathArgument( JavadocUtil.unifyPathSeparator( extdirs ) ) ); if ( ( getOverview() != null ) && ( getOverview().exists() ) ) { addArgIfNotEmpty( arguments, "-overview", JavadocUtil.quotedPathArgument( getOverview().getAbsolutePath() ) ); } arguments.add( getAccessLevel() ); if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_5 ); } addArgIfNotEmpty( arguments, "-source", JavadocUtil.quotedArgument( source ), SINCE_JAVADOC_1_4 ); if ( ( StringUtils.isEmpty( sourcepath ) ) && ( StringUtils.isNotEmpty( subpackages ) ) ) { sourcepath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); } addArgIfNotEmpty( arguments, "-sourcepath", JavadocUtil.quotedPathArgument( getSourcePath( sourcePaths ) ) ); if ( StringUtils.isNotEmpty( sourcepath ) && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_5 ); } addArgIf( arguments, verbose, "-verbose" ); addArgIfNotEmpty( arguments, null, additionalparam ); } /** * Add Standard Doclet Options. * <br/> * The <a href="package-summary.html#Standard_Doclet_Options">package documentation</a> details the * Standard Doclet Options wrapped by this Plugin. * * @param javadocOutputDirectory not null * @param arguments not null * @throws MavenReportException if any * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard"> * http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#standard</a> */ private void addStandardDocletOptions( File javadocOutputDirectory, List arguments ) throws MavenReportException { validateStandardDocletOptions(); // all options in alphabetical order addArgIf( arguments, author, "-author" ); addArgIfNotEmpty( arguments, "-bottom", JavadocUtil.quotedArgument( getBottomText() ), false, false ); if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-charset", JavadocUtil.quotedArgument( getCharset() ) ); addArgIfNotEmpty( arguments, "-d", JavadocUtil.quotedPathArgument( javadocOutputDirectory.toString() ) ); addArgIfNotEmpty( arguments, "-docencoding", JavadocUtil.quotedArgument( getDocencoding() ) ); addArgIf( arguments, docfilessubdirs, "-docfilessubdirs", SINCE_JAVADOC_1_4 ); addArgIfNotEmpty( arguments, "-doctitle", JavadocUtil.quotedArgument( getDoctitle() ), false, false ); if ( docfilessubdirs ) { addArgIfNotEmpty( arguments, "-excludedocfilessubdir", JavadocUtil.quotedPathArgument( excludedocfilessubdir ), SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-footer", JavadocUtil.quotedArgument( footer ), false, false ); addGroups( arguments ); addArgIfNotEmpty( arguments, "-header", JavadocUtil.quotedArgument( header ), false, false ); addArgIfNotEmpty( arguments, "-helpfile", JavadocUtil.quotedPathArgument( getHelpFile( javadocOutputDirectory ) ) ); addArgIf( arguments, keywords, "-keywords", SINCE_JAVADOC_1_4_2 ); if ( !isOffline ) { addLinkArguments( arguments ); } addLinkofflineArguments( arguments ); addArgIf( arguments, linksource, "-linksource", SINCE_JAVADOC_1_4 ); if ( sourcetab > 0 ) { if ( fJavadocVersion == SINCE_JAVADOC_1_4_2 ) { addArgIfNotEmpty( arguments, "-linksourcetab", String.valueOf( sourcetab ) ); } addArgIfNotEmpty( arguments, "-sourcetab", String.valueOf( sourcetab ), SINCE_JAVADOC_1_5 ); } addArgIf( arguments, nocomment, "-nocomment", SINCE_JAVADOC_1_4 ); addArgIf( arguments, nodeprecated, "-nodeprecated" ); addArgIf( arguments, nodeprecatedlist, "-nodeprecatedlist" ); addArgIf( arguments, nohelp, "-nohelp" ); addArgIf( arguments, noindex, "-noindex" ); addArgIf( arguments, nonavbar, "-nonavbar" ); addArgIf( arguments, nooverview, "-nooverview" ); addArgIfNotEmpty( arguments, "-noqualifier", JavadocUtil.quotedArgument( noqualifier ), SINCE_JAVADOC_1_4 ); addArgIf( arguments, nosince, "-nosince" ); addArgIf( arguments, notimestamp, "-notimestamp", SINCE_JAVADOC_1_5 ); addArgIf( arguments, notree, "-notree" ); addArgIfNotEmpty( arguments, "-packagesheader", JavadocUtil.quotedArgument( packagesheader ), SINCE_JAVADOC_1_4_2 ); if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) // Sun bug: 4714350 { addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_4 ); } addArgIf( arguments, serialwarn, "-serialwarn" ); addArgIf( arguments, splitindex, "-splitindex" ); addArgIfNotEmpty( arguments, "-stylesheetfile", JavadocUtil.quotedPathArgument( getStylesheetFile( javadocOutputDirectory ) ) ); if ( StringUtils.isNotEmpty( sourcepath ) && !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) { addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_4 ); } addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglet ), SINCE_JAVADOC_1_4 ); addTaglets( arguments ); addTagletsFromTagletArtifacts( arguments ); addArgIfNotEmpty( arguments, "-tagletpath", JavadocUtil.quotedPathArgument( getTagletPath() ), SINCE_JAVADOC_1_4 ); addTags( arguments ); addArgIfNotEmpty( arguments, "-top", JavadocUtil.quotedArgument( top ), false, false, SINCE_JAVADOC_1_6 ); addArgIf( arguments, use, "-use" ); addArgIf( arguments, version, "-version" ); addArgIfNotEmpty( arguments, "-windowtitle", JavadocUtil.quotedArgument( getWindowtitle() ), false, false ); } /** * Add <code>groups</code> parameter to arguments. * * @param arguments not null */ private void addGroups( List arguments ) { if ( groups == null ) { return; } for ( int i = 0; i < groups.length; i++ ) { if ( groups[i] == null || StringUtils.isEmpty( groups[i].getTitle() ) || StringUtils.isEmpty( groups[i].getPackages() ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A group option is empty. Ignore this option." ); } } else { String groupTitle = StringUtils.replace( groups[i].getTitle(), ",", "&#44;" ); addArgIfNotEmpty( arguments, "-group", JavadocUtil.quotedArgument( groupTitle ) + " " + JavadocUtil.quotedArgument( groups[i].getPackages() ), true ); } } } /** * Add <code>tags</code> parameter to arguments. * * @param arguments not null */ private void addTags( List arguments ) { if ( tags == null ) { return; } for ( int i = 0; i < tags.length; i++ ) { if ( StringUtils.isEmpty( tags[i].getName() ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A tag name is empty. Ignore this option." ); } } else { String value = "\"" + tags[i].getName(); if ( StringUtils.isNotEmpty( tags[i].getPlacement() ) ) { value += ":" + tags[i].getPlacement(); if ( StringUtils.isNotEmpty( tags[i].getHead() ) ) { value += ":" + tags[i].getHead(); } } value += "\""; addArgIfNotEmpty( arguments, "-tag", value, SINCE_JAVADOC_1_4 ); } } } /** * Add <code>taglets</code> parameter to arguments. * * @param arguments not null */ private void addTaglets( List arguments ) { if ( taglets == null ) { return; } for ( int i = 0; i < taglets.length; i++ ) { if ( ( taglets[i] == null ) || ( StringUtils.isEmpty( taglets[i].getTagletClass() ) ) ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "A taglet option is empty. Ignore this option." ); } } else { addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglets[i].getTagletClass() ), SINCE_JAVADOC_1_4 ); } } } /** * Auto-detect taglets class name from <code>tagletArtifacts</code> and add them to arguments. * * @param arguments not null * @throws MavenReportException if any * @see JavadocUtil#getTagletClassNames(File) */ private void addTagletsFromTagletArtifacts( List arguments ) throws MavenReportException { if ( tagletArtifacts == null ) { return; } List tagletsPath = new ArrayList(); for ( int i = 0; i < tagletArtifacts.length; i++ ) { TagletArtifact aTagletArtifact = tagletArtifacts[i]; if ( ( StringUtils.isNotEmpty( aTagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getVersion() ) ) ) { Artifact artifact; try { artifact = createAndResolveArtifact( aTagletArtifact ); } catch ( ArtifactResolutionException e ) { throw new MavenReportException( "Unable to resolve artifact:" + aTagletArtifact, e ); } catch ( ArtifactNotFoundException e ) { throw new MavenReportException( "Unable to find artifact:" + aTagletArtifact, e ); } catch ( ProjectBuildingException e ) { throw new MavenReportException( "Unable to build the Maven project for the artifact:" + aTagletArtifact, e ); } tagletsPath.add( artifact.getFile().getAbsolutePath() ); } } tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); for ( Iterator it = tagletsPath.iterator(); it.hasNext(); ) { String tagletJar = (String) it.next(); if ( !tagletJar.toLowerCase( Locale.ENGLISH ).endsWith( ".jar" ) ) { continue; } List tagletClasses; try { tagletClasses = JavadocUtil.getTagletClassNames( new File( tagletJar ) ); } catch ( IOException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "IOException: " + e.getMessage(), e ); } continue; } catch ( ClassNotFoundException e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "ClassNotFoundException: " + e.getMessage(), e ); } continue; } catch ( NoClassDefFoundError e ) { if ( getLog().isWarnEnabled() ) { getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar + "'. Try to specify them with <taglets/>." ); } if ( getLog().isDebugEnabled() ) { getLog().debug( "NoClassDefFoundError: " + e.getMessage(), e ); } continue; } if ( tagletClasses != null && !tagletClasses.isEmpty() ) { for ( Iterator it2 = tagletClasses.iterator(); it2.hasNext(); ) { String tagletClass = (String) it2.next(); addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( tagletClass ), SINCE_JAVADOC_1_4 ); } } } } /** * Execute the Javadoc command line * * @param cmd not null * @param javadocOutputDirectory not null * @throws MavenReportException if any errors occur */ private void executeJavadocCommandLine( Commandline cmd, File javadocOutputDirectory ) throws MavenReportException { if ( getLog().isDebugEnabled() ) { // no quoted arguments getLog().debug( CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ) ); } String cmdLine = null; if ( debug ) { cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); cmdLine = JavadocUtil.hideProxyPassword( cmdLine, settings ); writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); } CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer(); CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer(); try { int exitCode = CommandLineUtils.executeCommandLine( cmd, out, err ); String output = ( StringUtils.isEmpty( out.getOutput() ) ? null : '\n' + out.getOutput().trim() ); if ( exitCode != 0 ) { if ( cmdLine == null ) { cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); cmdLine = JavadocUtil.hideProxyPassword( cmdLine, settings ); } writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); if ( StringUtils.isNotEmpty( output ) && StringUtils.isEmpty( err.getOutput() ) && isJavadocVMInitError( output ) ) { StringBuffer msg = new StringBuffer(); msg.append( output ); msg.append( '\n' ).append( '\n' ); msg.append( JavadocUtil.ERROR_INIT_VM ).append( '\n' ); msg.append( "Or, try to reduce the Java heap size for the Javadoc goal using " ); msg.append( "-Dminmemory=<size> and -Dmaxmemory=<size>." ).append( '\n' ).append( '\n' ); msg.append( "Command line was: " ).append( cmdLine ).append( '\n' ).append( '\n' ); msg.append( "Refer to the generated Javadoc files in '" ).append( javadocOutputDirectory ) .append( "' dir.\n" ); throw new MavenReportException( msg.toString() ); } if ( StringUtils.isNotEmpty( output ) ) { getLog().info( output ); } StringBuffer msg = new StringBuffer( "\nExit code: " ); msg.append( exitCode ); if ( StringUtils.isNotEmpty( err.getOutput() ) ) { msg.append( " - " ).append( err.getOutput() ); } msg.append( '\n' ); msg.append( "Command line was: " ).append( cmdLine ).append( '\n' ).append( '\n' ); msg.append( "Refer to the generated Javadoc files in '" ).append( javadocOutputDirectory ) .append( "' dir.\n" ); throw new MavenReportException( msg.toString() ); } if ( StringUtils.isNotEmpty( output ) ) { getLog().info( output ); } } catch ( CommandLineException e ) { throw new MavenReportException( "Unable to execute javadoc command: " + e.getMessage(), e ); } // ---------------------------------------------------------------------- // Handle Javadoc warnings // ---------------------------------------------------------------------- if ( StringUtils.isNotEmpty( err.getOutput() ) && getLog().isWarnEnabled() ) { getLog().warn( "Javadoc Warnings" ); StringTokenizer token = new StringTokenizer( err.getOutput(), "\n" ); while ( token.hasMoreTokens() ) { String current = token.nextToken().trim(); getLog().warn( current ); } } } /** * @param outputFile not nul * @param inputResourceName a not null resource in <code>src/main/java</code>, <code>src/main/resources</code> or <code>src/main/javadoc</code> * or in the Javadoc plugin dependencies. * @return the resource file absolute path as String * @since 2.6 */ private String getResource( File outputFile, String inputResourceName ) { if ( inputResourceName.startsWith( "/" ) ) { inputResourceName = inputResourceName.replaceFirst( "//*", "" ); } List classPath = new ArrayList(); classPath.add( project.getBuild().getSourceDirectory() ); URL resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main src directory of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } classPath.clear(); for ( Iterator it = project.getBuild().getResources().iterator(); it.hasNext(); ) { Resource resource = (Resource) it.next(); classPath.add( resource.getDirectory() ); } resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main resources directories of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } if ( javadocDirectory.exists() ) { classPath.clear(); classPath.add( javadocDirectory.getAbsolutePath() ); resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in the main javadoc directory of the project." ); return FileUtils.toFile( resourceURL ).getAbsolutePath(); } } classPath.clear(); final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; Plugin javadocPlugin = getPlugin( project, pluginId ); if ( javadocPlugin != null && javadocPlugin.getDependencies() != null ) { for ( Iterator it = javadocPlugin.getDependencies().iterator(); it.hasNext(); ) { Dependency dependency = (Dependency) it.next(); JavadocPathArtifact javadocPathArtifact = new JavadocPathArtifact(); javadocPathArtifact.setGroupId( dependency.getGroupId() ); javadocPathArtifact.setArtifactId( dependency.getArtifactId() ); javadocPathArtifact.setVersion( dependency.getVersion() ); Artifact artifact = null; try { artifact = createAndResolveArtifact( javadocPathArtifact ); } catch ( Exception e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "Unable to retrieve the dependency: " + dependency + ". Ignored.", e ); } else { getLog().error( "Unable to retrieve the dependency: " + dependency + ". Ignored." ); } } if ( artifact != null && artifact.getFile().exists() ) { classPath.add( artifact.getFile().getAbsolutePath() ); } } resourceURL = getResource( classPath, inputResourceName ); if ( resourceURL != null ) { getLog().debug( inputResourceName + " found in javadoc plugin dependencies." ); try { JavadocUtil.copyResource( resourceURL, outputFile ); return outputFile.getAbsolutePath(); } catch ( IOException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "IOException: " + e.getMessage(), e ); } else { getLog().error( "IOException: " + e.getMessage() ); } } } } getLog() .warn( "Unable to find the resource '" + inputResourceName + "'. Using default Javadoc resources." ); return null; } /** * @param classPath a not null String list of files where resource will be look up. * @param resource a not null ressource to find in the class path. * @return the resource from the given classpath or null if not found * @see ClassLoader#getResource(String) * @since 2.6 */ private URL getResource( final List classPath, final String resource ) { List urls = new ArrayList( classPath.size() ); Iterator iter = classPath.iterator(); while ( iter.hasNext() ) { try { urls.add( new File( ( (String) iter.next() ) ).toURL() ); } catch ( MalformedURLException e ) { getLog().error( "MalformedURLException: " + e.getMessage() ); } } ClassLoader javadocClassLoader = new URLClassLoader( (URL[]) urls.toArray( new URL[urls.size()] ), null ); return javadocClassLoader.getResource( resource ); } /** * Load the plugin pom.properties to get the current plugin version. * * @return <code>org.apache.maven.plugins:maven-javadoc-plugin:CURRENT_VERSION:javadoc</code> */ private String getFullJavadocGoal() { String javadocPluginVersion = null; InputStream resourceAsStream = null; try { String resource = "META-INF/maven/org.apache.maven.plugins/maven-javadoc-plugin/pom.properties"; resourceAsStream = AbstractJavadocMojo.class.getClassLoader().getResourceAsStream( resource ); if ( resourceAsStream != null ) { Properties properties = new Properties(); properties.load( resourceAsStream ); if ( StringUtils.isNotEmpty( properties.getProperty( "version" ) ) ) { javadocPluginVersion = properties.getProperty( "version" ); } } } catch ( IOException e ) { // nop } finally { IOUtil.close( resourceAsStream ); } StringBuffer sb = new StringBuffer(); sb.append( "org.apache.maven.plugins" ).append( ":" ); sb.append( "maven-javadoc-plugin" ).append( ":" ); if ( StringUtils.isNotEmpty( javadocPluginVersion ) ) { sb.append( javadocPluginVersion ).append( ":" ); } if ( TestJavadocReport.class.isAssignableFrom( getClass() ) ) { sb.append( "test-javadoc" ); } else { sb.append( "javadoc" ); } return sb.toString(); } /** * Using Maven, a Javadoc link is given by <code>${project.url}/apidocs</code>. * * @return the detected Javadoc links using the Maven conventions for all modules defined in the current project * or an empty list. * @throws MavenReportException if any * @see #detectOfflineLinks * @see #reactorProjects * @since 2.6 */ private List getModulesLinks() throws MavenReportException { if ( !( detectOfflineLinks && !isAggregator() && reactorProjects != null ) ) { return Collections.EMPTY_LIST; } getLog().debug( "Try to add links for modules..." ); List modulesLinks = new ArrayList(); String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getOutputDirectory() ); for ( Iterator it = reactorProjects.iterator(); it.hasNext(); ) { MavenProject p = (MavenProject) it.next(); if ( p.getPackaging().equals( "pom" ) ) { continue; } if ( p.getId().equals( project.getId() ) ) { continue; } File location = new File( p.getBasedir(), javadocDirRelative ); if ( p.getUrl() != null ) { if ( !location.exists() ) { String javadocGoal = getFullJavadocGoal(); getLog().info( "The goal '" + javadocGoal + "' has not be previously called for the project: '" + p.getId() + "'. Trying to invoke it..." ); File invokerDir = new File( project.getBuild().getDirectory(), "invoker" ); invokerDir.mkdirs(); File invokerLogFile = FileUtils.createTempFile( "maven-javadoc-plugin", ".txt", invokerDir ); try { JavadocUtil.invokeMaven( getLog(), new File( localRepository.getBasedir() ), p.getFile(), Collections.singletonList( javadocGoal ), null, invokerLogFile ); } catch ( MavenInvocationException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "MavenInvocationException: " + e.getMessage(), e ); } else { getLog().error( "MavenInvocationException: " + e.getMessage() ); } String invokerLogContent = JavadocUtil.readFile( invokerLogFile, "UTF-8" ); if ( invokerLogContent != null && invokerLogContent.indexOf( JavadocUtil.ERROR_INIT_VM ) == -1 ) { throw new MavenReportException( e.getMessage(), e ); } } finally { // just create the directory to prevent repeated invokations.. if ( !location.exists() ) { location.mkdirs(); } } } if ( location.exists() ) { String url = getJavadocLink( p ); OfflineLink ol = new OfflineLink(); ol.setUrl( url ); ol.setLocation( location.getAbsolutePath() ); if ( getLog().isDebugEnabled() ) { getLog().debug( "Added Javadoc link: " + url + " for the project: " + p.getId() ); } modulesLinks.add( ol ); } } } return modulesLinks; } /** * Using Maven, a Javadoc link is given by <code>${project.url}/apidocs</code>. * * @return the detected Javadoc links using the Maven conventions for all dependencies defined in the current * project or an empty list. * @see #detectLinks * @since 2.6 */ private List getDependenciesLinks() { if ( !detectLinks ) { return Collections.EMPTY_LIST; } getLog().debug( "Try to add links for dependencies..." ); List dependenciesLinks = new ArrayList(); for ( Iterator it = project.getDependencyArtifacts().iterator(); it.hasNext(); ) { Artifact artifact = (Artifact) it.next(); if ( artifact != null && artifact.getFile().exists() ) { try { MavenProject artifactProject = mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository ); if ( StringUtils.isNotEmpty( artifactProject.getUrl() ) ) { String url = getJavadocLink( artifactProject ); if ( getLog().isDebugEnabled() ) { getLog().debug( "Added Javadoc link: " + url + " for the project: " + artifactProject.getId() ); } dependenciesLinks.add( url ); } } catch ( ProjectBuildingException e ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "Error when building the artifact: " + artifact.toString() + ". Ignored to add Javadoc link." ); getLog().error( "ProjectBuildingException: " + e.getMessage(), e ); } else { getLog().error( "ProjectBuildingException: " + e.getMessage() ); } } } } return dependenciesLinks; } /** * @return if {@link #detectJavaApiLink}, the Java API link based on the {@link #javaApiLinks} properties and the * value of the <code>source</code> parameter in the <code>org.apache.maven.plugins:maven-compiler-plugin</code> * defined in <code>${project.build.plugins}</code> or in <code>${project.build.pluginManagement}</code>, * or the {@link #fJavadocVersion}, or <code>null</code> if not defined. * @since 2.6 * @see #detectJavaApiLink * @see #javaApiLinks * @see #DEFAULT_JAVA_API_LINKS * @see <a href="http://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#source">source parameter</a> */ private String getDefaultJavadocApiLink() { if ( !detectJavaApiLink ) { return null; } final String pluginId = "org.apache.maven.plugins:maven-compiler-plugin"; float sourceVersion = fJavadocVersion; String sourceConfigured = getPluginParameter( project, pluginId, "source" ); if ( sourceConfigured != null ) { try { sourceVersion = Float.parseFloat( sourceConfigured ); } catch ( NumberFormatException e ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "NumberFormatException for the source parameter in the maven-compiler-plugin. " + "Ignored it", e ); } } } else { if ( getLog().isDebugEnabled() ) { getLog().debug( "No maven-compiler-plugin defined in ${build.plugins} or in " + "${project.build.pluginManagement} for the " + project.getId() + ". Added Javadoc API link according the javadoc executable version i.e.: " + fJavadocVersion ); } } String javaApiLink = null; if ( sourceVersion >= 1.3f && sourceVersion < 1.4f && javaApiLinks.getProperty( "api_1.3" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.3" ).toString(); } else if ( sourceVersion >= 1.4f && sourceVersion < 1.5f && javaApiLinks.getProperty( "api_1.4" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.4" ).toString(); } else if ( sourceVersion >= 1.5f && sourceVersion < 1.6f && javaApiLinks.getProperty( "api_1.5" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.5" ).toString(); } else if ( sourceVersion >= 1.6f && javaApiLinks.getProperty( "api_1.6" ) != null ) { javaApiLink = javaApiLinks.getProperty( "api_1.6" ).toString(); } if ( StringUtils.isNotEmpty( javaApiLink ) ) { if ( getLog().isDebugEnabled() ) { getLog().debug( "Found Java API link: " + javaApiLink ); } } else { if ( getLog().isDebugEnabled() ) { getLog().debug( "No Java API link found." ); } } return javaApiLink; } /** * @param link not null * @return <code>true</code> if the link has a <code>/package-list</code>, <code>false</code> otherwise. * @since 2.6 * @see <a href="http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/javadoc.html#package-list"> * package-list spec</a> */ private boolean isValidJavadocLink( String link ) { try { URI linkUri; if ( link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "http" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "https" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "ftp" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "file" ) ) { linkUri = new URI( link + "/package-list" ); } else { // links can be relative paths or files File dir = new File( link ); if ( !dir.isAbsolute() ) { dir = new File( getOutputDirectory(), link ); } if ( !dir.isDirectory() ) { getLog().error( "The given File link: " + dir + " is not a dir." ); } linkUri = new File( dir, "package-list" ).toURI(); } JavadocUtil.fetchURL( settings, linkUri.toURL() ); return true; } catch ( URISyntaxException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Malformed link: " + link + "/package-list. Ignored it." ); } return false; } catch ( IOException e ) { if ( getLog().isErrorEnabled() ) { getLog().error( "Error fetching link: " + link + "/package-list. Ignored it." ); } return false; } } /** * Write a debug javadoc script in case of command line error or in debug mode. * * @param cmdLine the current command line as string, not null. * @param javadocOutputDirectory the output dir, not null. * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6 */ private void writeDebugJavadocScript( String cmdLine, File javadocOutputDirectory ) { File commandLineFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); commandLineFile.getParentFile().mkdirs(); try { FileUtils.fileWrite( commandLineFile.getAbsolutePath(), "UTF-8", cmdLine ); if ( !SystemUtils.IS_OS_WINDOWS ) { Runtime.getRuntime().exec( new String[] { "chmod", "a+x", commandLineFile.getAbsolutePath() } ); } } catch ( IOException e ) { if ( getLog().isDebugEnabled() ) { getLog().error( "Unable to write '" + commandLineFile.getName() + "' debug script file", e ); } else { getLog().error( "Unable to write '" + commandLineFile.getName() + "' debug script file" ); } } } /** * Check if the Javadoc JVM is correctly started or not. * * @param output the command line output, not null. * @return <code>true</code> if Javadoc output command line contains Javadoc word, <code>false</code> otherwise. * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6.1 */ private boolean isJavadocVMInitError( String output ) { /* * see main.usage and main.Building_tree keys from * com.sun.tools.javadoc.resources.javadoc bundle in tools.jar */ if ( output.indexOf( "Javadoc" ) != -1 || output.indexOf( "javadoc" ) != -1 ) { return false; } return true; } // ---------------------------------------------------------------------- // Static methods // ---------------------------------------------------------------------- /** * @param p not null * @return the javadoc link based on the project url i.e. <code>${project.url}/${destDir}</code> where * <code>destDir</code> is configued in the Javadoc plugin configuration (<code>apidocs</code> by default). * @since 2.6 */ private static String getJavadocLink( MavenProject p ) { if ( p.getUrl() == null ) { return null; } String url = cleanUrl( p.getUrl() ); String destDir = "apidocs"; // see JavadocReport#destDir final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; String destDirConfigured = getPluginParameter( p, pluginId, "destDir" ); if ( destDirConfigured != null ) { destDir = destDirConfigured; } return url + "/" + destDir; } /** * @param url could be null. * @return the url cleaned or empty if url was null. * @since 2.6 */ private static String cleanUrl( String url ) { if ( url == null ) { return ""; } url = url.trim(); while ( url.endsWith( "/" ) ) { url = url.substring( 0, url.lastIndexOf( "/" ) ); } return url; } /** * @param p not null * @param pluginId not null key of the plugin defined in {@link org.apache.maven.model.Build#getPluginsAsMap()} * or in {@link org.apache.maven.model.PluginManagement#getPluginsAsMap()} * @return the Maven plugin defined in <code>${project.build.plugins}</code> or in * <code>${project.build.pluginManagement}</code>, or <code>null</code> if not defined. * @since 2.6 */ private static Plugin getPlugin( MavenProject p, String pluginId ) { Plugin plugin = null; if ( p.getBuild() != null && p.getBuild().getPluginsAsMap() != null ) { plugin = (Plugin) p.getBuild().getPluginsAsMap().get( pluginId ); if ( plugin == null ) { if ( p.getBuild().getPluginManagement() != null && p.getBuild().getPluginManagement().getPluginsAsMap() != null ) { plugin = (Plugin) p.getBuild().getPluginManagement().getPluginsAsMap().get( pluginId ); } } } return plugin; } /** * @param p not null * @param pluginId not null * @param param not null * @return the simple parameter as String defined in the plugin configuration by <code>param</code> key * or <code>null</code> if not found. * @since 2.6 */ private static String getPluginParameter( MavenProject p, String pluginId, String param ) { // p.getGoalConfiguration( pluginGroupId, pluginArtifactId, executionId, goalId ); Plugin plugin = getPlugin( p, pluginId ); if ( plugin != null ) { Xpp3Dom xpp3Dom = (Xpp3Dom) plugin.getConfiguration(); if ( xpp3Dom != null && xpp3Dom.getChild( param ) != null && StringUtils.isNotEmpty( xpp3Dom.getChild( param ).getValue() ) ) { return xpp3Dom.getChild( param ).getValue(); } } return null; } }
prevent potential NPE. git-svn-id: 6038db50b076e48c7926ed71fd94f8e91be2fbc9@911264 13f79535-47bb-0310-9956-ffa450edef68
maven-javadoc-plugin/src/main/java/org/apache/maven/plugin/javadoc/AbstractJavadocMojo.java
prevent potential NPE.
Java
apache-2.0
a380e0e16910d54fc6b098373be55e75ff3b3062
0
kubum/elasticsearch,luiseduardohdbackup/elasticsearch,Kakakakakku/elasticsearch,luiseduardohdbackup/elasticsearch,tkssharma/elasticsearch,lchennup/elasticsearch,yuy168/elasticsearch,scottsom/elasticsearch,JSCooke/elasticsearch,xingguang2013/elasticsearch,kalburgimanjunath/elasticsearch,schonfeld/elasticsearch,F0lha/elasticsearch,amaliujia/elasticsearch,wayeast/elasticsearch,nrkkalyan/elasticsearch,yanjunh/elasticsearch,ThalaivaStars/OrgRepo1,nellicus/elasticsearch,anti-social/elasticsearch,dantuffery/elasticsearch,slavau/elasticsearch,andrejserafim/elasticsearch,sdauletau/elasticsearch,cnfire/elasticsearch-1,areek/elasticsearch,kimimj/elasticsearch,rajanm/elasticsearch,golubev/elasticsearch,lydonchandra/elasticsearch,djschny/elasticsearch,jaynblue/elasticsearch,himanshuag/elasticsearch,naveenhooda2000/elasticsearch,kenshin233/elasticsearch,Stacey-Gammon/elasticsearch,khiraiwa/elasticsearch,dongaihua/highlight-elasticsearch,phani546/elasticsearch,thecocce/elasticsearch,hanswang/elasticsearch,uschindler/elasticsearch,likaiwalkman/elasticsearch,gfyoung/elasticsearch,tsohil/elasticsearch,areek/elasticsearch,karthikjaps/elasticsearch,kingaj/elasticsearch,kimimj/elasticsearch,jbertouch/elasticsearch,Chhunlong/elasticsearch,bawse/elasticsearch,MaineC/elasticsearch,scorpionvicky/elasticsearch,glefloch/elasticsearch,wbowling/elasticsearch,gmarz/elasticsearch,rento19962/elasticsearch,jango2015/elasticsearch,wbowling/elasticsearch,sreeramjayan/elasticsearch,nezirus/elasticsearch,iamjakob/elasticsearch,dylan8902/elasticsearch,fekaputra/elasticsearch,himanshuag/elasticsearch,MisterAndersen/elasticsearch,overcome/elasticsearch,iamjakob/elasticsearch,huanzhong/elasticsearch,18098924759/elasticsearch,tebriel/elasticsearch,chirilo/elasticsearch,henakamaMSFT/elasticsearch,zeroctu/elasticsearch,mjhennig/elasticsearch,sc0ttkclark/elasticsearch,snikch/elasticsearch,glefloch/elasticsearch,onegambler/elasticsearch,mnylen/elasticsearch,mnylen/elasticsearch,golubev/elasticsearch,pritishppai/elasticsearch,xuzha/elasticsearch,franklanganke/elasticsearch,sreeramjayan/elasticsearch,weipinghe/elasticsearch,AshishThakur/elasticsearch,mute/elasticsearch,Shekharrajak/elasticsearch,jeteve/elasticsearch,ulkas/elasticsearch,raishiv/elasticsearch,strapdata/elassandra,djschny/elasticsearch,onegambler/elasticsearch,ydsakyclguozi/elasticsearch,queirozfcom/elasticsearch,aparo/elasticsearch,Stacey-Gammon/elasticsearch,fekaputra/elasticsearch,zhiqinghuang/elasticsearch,mikemccand/elasticsearch,andrewvc/elasticsearch,strapdata/elassandra,sarwarbhuiyan/elasticsearch,VukDukic/elasticsearch,heng4fun/elasticsearch,mgalushka/elasticsearch,brwe/elasticsearch,onegambler/elasticsearch,hydro2k/elasticsearch,mortonsykes/elasticsearch,xpandan/elasticsearch,hanswang/elasticsearch,obourgain/elasticsearch,palecur/elasticsearch,hechunwen/elasticsearch,iacdingping/elasticsearch,hanst/elasticsearch,ricardocerq/elasticsearch,kaneshin/elasticsearch,sjohnr/elasticsearch,khiraiwa/elasticsearch,yanjunh/elasticsearch,rlugojr/elasticsearch,kalimatas/elasticsearch,yynil/elasticsearch,ESamir/elasticsearch,zhaocloud/elasticsearch,zhiqinghuang/elasticsearch,girirajsharma/elasticsearch,huypx1292/elasticsearch,rento19962/elasticsearch,opendatasoft/elasticsearch,infusionsoft/elasticsearch,EasonYi/elasticsearch,golubev/elasticsearch,bawse/elasticsearch,schonfeld/elasticsearch,gingerwizard/elasticsearch,vvcephei/elasticsearch,koxa29/elasticsearch,JervyShi/elasticsearch,obourgain/elasticsearch,Rygbee/elasticsearch,brandonkearby/elasticsearch,fekaputra/elasticsearch,Brijeshrpatel9/elasticsearch,tkssharma/elasticsearch,wimvds/elasticsearch,abibell/elasticsearch,rmuir/elasticsearch,tcucchietti/elasticsearch,mjason3/elasticsearch,pozhidaevak/elasticsearch,anti-social/elasticsearch,marcuswr/elasticsearch-dateline,loconsolutions/elasticsearch,jbertouch/elasticsearch,yuy168/elasticsearch,robin13/elasticsearch,milodky/elasticsearch,Chhunlong/elasticsearch,cwurm/elasticsearch,amit-shar/elasticsearch,amaliujia/elasticsearch,rento19962/elasticsearch,nrkkalyan/elasticsearch,martinstuga/elasticsearch,ydsakyclguozi/elasticsearch,beiske/elasticsearch,alexkuk/elasticsearch,tahaemin/elasticsearch,palecur/elasticsearch,fooljohnny/elasticsearch,Brijeshrpatel9/elasticsearch,masterweb121/elasticsearch,ajhalani/elasticsearch,cnfire/elasticsearch-1,SergVro/elasticsearch,vvcephei/elasticsearch,jw0201/elastic,cwurm/elasticsearch,winstonewert/elasticsearch,linglaiyao1314/elasticsearch,caengcjd/elasticsearch,iantruslove/elasticsearch,Flipkart/elasticsearch,Shekharrajak/elasticsearch,pozhidaevak/elasticsearch,nazarewk/elasticsearch,weipinghe/elasticsearch,yongminxia/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,elasticdog/elasticsearch,vrkansagara/elasticsearch,Fsero/elasticsearch,LeoYao/elasticsearch,mrorii/elasticsearch,lydonchandra/elasticsearch,Uiho/elasticsearch,Siddartha07/elasticsearch,khiraiwa/elasticsearch,jeteve/elasticsearch,PhaedrusTheGreek/elasticsearch,vinsonlou/elasticsearch,maddin2016/elasticsearch,wuranbo/elasticsearch,rajanm/elasticsearch,strapdata/elassandra5-rc,PhaedrusTheGreek/elasticsearch,PhaedrusTheGreek/elasticsearch,martinstuga/elasticsearch,rhoml/elasticsearch,mohit/elasticsearch,likaiwalkman/elasticsearch,wangyuxue/elasticsearch,libosu/elasticsearch,achow/elasticsearch,amit-shar/elasticsearch,szroland/elasticsearch,lmtwga/elasticsearch,thecocce/elasticsearch,brwe/elasticsearch,jsgao0/elasticsearch,F0lha/elasticsearch,JackyMai/elasticsearch,MetSystem/elasticsearch,Siddartha07/elasticsearch,jw0201/elastic,KimTaehee/elasticsearch,mm0/elasticsearch,sauravmondallive/elasticsearch,rmuir/elasticsearch,golubev/elasticsearch,kcompher/elasticsearch,iacdingping/elasticsearch,gfyoung/elasticsearch,dylan8902/elasticsearch,kaneshin/elasticsearch,JervyShi/elasticsearch,nazarewk/elasticsearch,iamjakob/elasticsearch,rhoml/elasticsearch,nknize/elasticsearch,polyfractal/elasticsearch,markwalkom/elasticsearch,luiseduardohdbackup/elasticsearch,humandb/elasticsearch,ajhalani/elasticsearch,coding0011/elasticsearch,Fsero/elasticsearch,kkirsche/elasticsearch,andrestc/elasticsearch,lightslife/elasticsearch,Widen/elasticsearch,IanvsPoplicola/elasticsearch,mute/elasticsearch,kevinkluge/elasticsearch,scorpionvicky/elasticsearch,koxa29/elasticsearch,wittyameta/elasticsearch,Liziyao/elasticsearch,beiske/elasticsearch,humandb/elasticsearch,hafkensite/elasticsearch,smflorentino/elasticsearch,cnfire/elasticsearch-1,Brijeshrpatel9/elasticsearch,kalimatas/elasticsearch,artnowo/elasticsearch,ZTE-PaaS/elasticsearch,himanshuag/elasticsearch,18098924759/elasticsearch,yanjunh/elasticsearch,mmaracic/elasticsearch,fekaputra/elasticsearch,jsgao0/elasticsearch,Kakakakakku/elasticsearch,AleksKochev/elasticsearch,markllama/elasticsearch,MisterAndersen/elasticsearch,mute/elasticsearch,pablocastro/elasticsearch,nellicus/elasticsearch,iantruslove/elasticsearch,strapdata/elassandra-test,jchampion/elasticsearch,apepper/elasticsearch,dpursehouse/elasticsearch,uschindler/elasticsearch,liweinan0423/elasticsearch,socialrank/elasticsearch,djschny/elasticsearch,hanst/elasticsearch,mnylen/elasticsearch,kevinkluge/elasticsearch,thecocce/elasticsearch,JSCooke/elasticsearch,pritishppai/elasticsearch,hechunwen/elasticsearch,sdauletau/elasticsearch,libosu/elasticsearch,Clairebi/ElasticsearchClone,KimTaehee/elasticsearch,aparo/elasticsearch,kcompher/elasticsearch,kalimatas/elasticsearch,yynil/elasticsearch,pritishppai/elasticsearch,ImpressTV/elasticsearch,Stacey-Gammon/elasticsearch,glefloch/elasticsearch,strapdata/elassandra,dataduke/elasticsearch,ckclark/elasticsearch,loconsolutions/elasticsearch,lzo/elasticsearch-1,wittyameta/elasticsearch,amaliujia/elasticsearch,rhoml/elasticsearch,pozhidaevak/elasticsearch,koxa29/elasticsearch,njlawton/elasticsearch,wuranbo/elasticsearch,F0lha/elasticsearch,apepper/elasticsearch,nrkkalyan/elasticsearch,nomoa/elasticsearch,micpalmia/elasticsearch,gfyoung/elasticsearch,LewayneNaidoo/elasticsearch,Stacey-Gammon/elasticsearch,sreeramjayan/elasticsearch,yongminxia/elasticsearch,alexbrasetvik/elasticsearch,episerver/elasticsearch,brwe/elasticsearch,mapr/elasticsearch,camilojd/elasticsearch,infusionsoft/elasticsearch,rhoml/elasticsearch,alexkuk/elasticsearch,kingaj/elasticsearch,mrorii/elasticsearch,nezirus/elasticsearch,ZTE-PaaS/elasticsearch,Kakakakakku/elasticsearch,yynil/elasticsearch,caengcjd/elasticsearch,coding0011/elasticsearch,vroyer/elasticassandra,mikemccand/elasticsearch,gingerwizard/elasticsearch,hirdesh2008/elasticsearch,sneivandt/elasticsearch,mortonsykes/elasticsearch,sposam/elasticsearch,bawse/elasticsearch,mapr/elasticsearch,jimhooker2002/elasticsearch,fernandozhu/elasticsearch,xingguang2013/elasticsearch,hafkensite/elasticsearch,jimczi/elasticsearch,jaynblue/elasticsearch,Helen-Zhao/elasticsearch,LewayneNaidoo/elasticsearch,coding0011/elasticsearch,lydonchandra/elasticsearch,sscarduzio/elasticsearch,achow/elasticsearch,LewayneNaidoo/elasticsearch,markllama/elasticsearch,strapdata/elassandra,pritishppai/elasticsearch,lzo/elasticsearch-1,amaliujia/elasticsearch,robin13/elasticsearch,rlugojr/elasticsearch,mgalushka/elasticsearch,hydro2k/elasticsearch,petabytedata/elasticsearch,hanst/elasticsearch,pablocastro/elasticsearch,fekaputra/elasticsearch,xpandan/elasticsearch,Shekharrajak/elasticsearch,sreeramjayan/elasticsearch,weipinghe/elasticsearch,scottsom/elasticsearch,NBSW/elasticsearch,hanst/elasticsearch,fred84/elasticsearch,qwerty4030/elasticsearch,JervyShi/elasticsearch,aglne/elasticsearch,jimczi/elasticsearch,rhoml/elasticsearch,areek/elasticsearch,masaruh/elasticsearch,tsohil/elasticsearch,StefanGor/elasticsearch,kalburgimanjunath/elasticsearch,Chhunlong/elasticsearch,jango2015/elasticsearch,jw0201/elastic,dylan8902/elasticsearch,sauravmondallive/elasticsearch,golubev/elasticsearch,franklanganke/elasticsearch,markwalkom/elasticsearch,petmit/elasticsearch,petabytedata/elasticsearch,hanswang/elasticsearch,djschny/elasticsearch,C-Bish/elasticsearch,kevinkluge/elasticsearch,beiske/elasticsearch,maddin2016/elasticsearch,JervyShi/elasticsearch,sjohnr/elasticsearch,nilabhsagar/elasticsearch,hirdesh2008/elasticsearch,fubuki/elasticsearch,ivansun1010/elasticsearch,hydro2k/elasticsearch,pablocastro/elasticsearch,ulkas/elasticsearch,jchampion/elasticsearch,kalburgimanjunath/elasticsearch,StefanGor/elasticsearch,lmenezes/elasticsearch,ouyangkongtong/elasticsearch,janmejay/elasticsearch,onegambler/elasticsearch,xingguang2013/elasticsearch,palecur/elasticsearch,cnfire/elasticsearch-1,shreejay/elasticsearch,scottsom/elasticsearch,sdauletau/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,i-am-Nathan/elasticsearch,VukDukic/elasticsearch,springning/elasticsearch,naveenhooda2000/elasticsearch,ckclark/elasticsearch,yuy168/elasticsearch,scorpionvicky/elasticsearch,kaneshin/elasticsearch,rmuir/elasticsearch,ThiagoGarciaAlves/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,nilabhsagar/elasticsearch,masterweb121/elasticsearch,sarwarbhuiyan/elasticsearch,chrismwendt/elasticsearch,bestwpw/elasticsearch,YosuaMichael/elasticsearch,nilabhsagar/elasticsearch,Collaborne/elasticsearch,jimhooker2002/elasticsearch,mbrukman/elasticsearch,robin13/elasticsearch,kunallimaye/elasticsearch,mjhennig/elasticsearch,lydonchandra/elasticsearch,fred84/elasticsearch,petabytedata/elasticsearch,IanvsPoplicola/elasticsearch,xpandan/elasticsearch,martinstuga/elasticsearch,Rygbee/elasticsearch,henakamaMSFT/elasticsearch,vvcephei/elasticsearch,a2lin/elasticsearch,queirozfcom/elasticsearch,abibell/elasticsearch,strapdata/elassandra5-rc,VukDukic/elasticsearch,knight1128/elasticsearch,brwe/elasticsearch,jango2015/elasticsearch,artnowo/elasticsearch,dongjoon-hyun/elasticsearch,zkidkid/elasticsearch,Microsoft/elasticsearch,lmtwga/elasticsearch,elasticdog/elasticsearch,alexshadow007/elasticsearch,nellicus/elasticsearch,markharwood/elasticsearch,sarwarbhuiyan/elasticsearch,linglaiyao1314/elasticsearch,winstonewert/elasticsearch,loconsolutions/elasticsearch,wimvds/elasticsearch,Charlesdong/elasticsearch,cwurm/elasticsearch,Fsero/elasticsearch,kunallimaye/elasticsearch,s1monw/elasticsearch,Flipkart/elasticsearch,micpalmia/elasticsearch,yynil/elasticsearch,JervyShi/elasticsearch,winstonewert/elasticsearch,ImpressTV/elasticsearch,chrismwendt/elasticsearch,weipinghe/elasticsearch,sc0ttkclark/elasticsearch,Flipkart/elasticsearch,likaiwalkman/elasticsearch,ThalaivaStars/OrgRepo1,sreeramjayan/elasticsearch,MaineC/elasticsearch,onegambler/elasticsearch,dylan8902/elasticsearch,jsgao0/elasticsearch,boliza/elasticsearch,marcuswr/elasticsearch-dateline,wimvds/elasticsearch,kingaj/elasticsearch,fforbeck/elasticsearch,vrkansagara/elasticsearch,F0lha/elasticsearch,Siddartha07/elasticsearch,Charlesdong/elasticsearch,achow/elasticsearch,marcuswr/elasticsearch-dateline,henakamaMSFT/elasticsearch,abhijitiitr/es,adrianbk/elasticsearch,Microsoft/elasticsearch,queirozfcom/elasticsearch,Rygbee/elasticsearch,kingaj/elasticsearch,masaruh/elasticsearch,MichaelLiZhou/elasticsearch,yongminxia/elasticsearch,avikurapati/elasticsearch,aparo/elasticsearch,raishiv/elasticsearch,djschny/elasticsearch,wangyuxue/elasticsearch,ThalaivaStars/OrgRepo1,hechunwen/elasticsearch,jaynblue/elasticsearch,diendt/elasticsearch,Collaborne/elasticsearch,karthikjaps/elasticsearch,pranavraman/elasticsearch,slavau/elasticsearch,marcuswr/elasticsearch-dateline,maddin2016/elasticsearch,ckclark/elasticsearch,JSCooke/elasticsearch,hydro2k/elasticsearch,Chhunlong/elasticsearch,Kakakakakku/elasticsearch,zhiqinghuang/elasticsearch,iacdingping/elasticsearch,smflorentino/elasticsearch,nazarewk/elasticsearch,combinatorist/elasticsearch,fred84/elasticsearch,Asimov4/elasticsearch,gmarz/elasticsearch,avikurapati/elasticsearch,sneivandt/elasticsearch,apepper/elasticsearch,aglne/elasticsearch,sposam/elasticsearch,elasticdog/elasticsearch,kubum/elasticsearch,alexshadow007/elasticsearch,areek/elasticsearch,slavau/elasticsearch,mkis-/elasticsearch,ricardocerq/elasticsearch,salyh/elasticsearch,jpountz/elasticsearch,vorce/es-metrics,Charlesdong/elasticsearch,sjohnr/elasticsearch,xingguang2013/elasticsearch,ricardocerq/elasticsearch,petmit/elasticsearch,jsgao0/elasticsearch,andrestc/elasticsearch,Helen-Zhao/elasticsearch,PhaedrusTheGreek/elasticsearch,slavau/elasticsearch,dongjoon-hyun/elasticsearch,yanjunh/elasticsearch,huypx1292/elasticsearch,tebriel/elasticsearch,ImpressTV/elasticsearch,sarwarbhuiyan/elasticsearch,djschny/elasticsearch,mgalushka/elasticsearch,mute/elasticsearch,kimchy/elasticsearch,brandonkearby/elasticsearch,dongjoon-hyun/elasticsearch,skearns64/elasticsearch,geidies/elasticsearch,bestwpw/elasticsearch,truemped/elasticsearch,opendatasoft/elasticsearch,maddin2016/elasticsearch,vroyer/elassandra,infusionsoft/elasticsearch,Shepard1212/elasticsearch,javachengwc/elasticsearch,mgalushka/elasticsearch,iamjakob/elasticsearch,feiqitian/elasticsearch,kenshin233/elasticsearch,jsgao0/elasticsearch,Helen-Zhao/elasticsearch,overcome/elasticsearch,hirdesh2008/elasticsearch,Brijeshrpatel9/elasticsearch,hirdesh2008/elasticsearch,karthikjaps/elasticsearch,hafkensite/elasticsearch,MetSystem/elasticsearch,elancom/elasticsearch,ivansun1010/elasticsearch,jimhooker2002/elasticsearch,iacdingping/elasticsearch,shreejay/elasticsearch,alexkuk/elasticsearch,davidvgalbraith/elasticsearch,camilojd/elasticsearch,tahaemin/elasticsearch,franklanganke/elasticsearch,mrorii/elasticsearch,ckclark/elasticsearch,AshishThakur/elasticsearch,trangvh/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,tsohil/elasticsearch,btiernay/elasticsearch,iacdingping/elasticsearch,Charlesdong/elasticsearch,Uiho/elasticsearch,Widen/elasticsearch,Fsero/elasticsearch,henakamaMSFT/elasticsearch,alexkuk/elasticsearch,skearns64/elasticsearch,Helen-Zhao/elasticsearch,raishiv/elasticsearch,MjAbuz/elasticsearch,strapdata/elassandra-test,s1monw/elasticsearch,Charlesdong/elasticsearch,jw0201/elastic,kevinkluge/elasticsearch,kimchy/elasticsearch,ivansun1010/elasticsearch,schonfeld/elasticsearch,petmit/elasticsearch,fernandozhu/elasticsearch,HarishAtGitHub/elasticsearch,beiske/elasticsearch,mnylen/elasticsearch,lchennup/elasticsearch,MetSystem/elasticsearch,elancom/elasticsearch,nknize/elasticsearch,kalimatas/elasticsearch,lmtwga/elasticsearch,episerver/elasticsearch,lks21c/elasticsearch,pablocastro/elasticsearch,ThiagoGarciaAlves/elasticsearch,szroland/elasticsearch,micpalmia/elasticsearch,mgalushka/elasticsearch,mbrukman/elasticsearch,codebunt/elasticsearch,myelin/elasticsearch,PhaedrusTheGreek/elasticsearch,humandb/elasticsearch,combinatorist/elasticsearch,Shekharrajak/elasticsearch,petabytedata/elasticsearch,andrewvc/elasticsearch,sjohnr/elasticsearch,hirdesh2008/elasticsearch,Stacey-Gammon/elasticsearch,YosuaMichael/elasticsearch,tahaemin/elasticsearch,acchen97/elasticsearch,jimhooker2002/elasticsearch,tsohil/elasticsearch,jimczi/elasticsearch,alexshadow007/elasticsearch,wenpos/elasticsearch,Flipkart/elasticsearch,mute/elasticsearch,djschny/elasticsearch,jango2015/elasticsearch,bawse/elasticsearch,dongaihua/highlight-elasticsearch,umeshdangat/elasticsearch,diendt/elasticsearch,likaiwalkman/elasticsearch,knight1128/elasticsearch,franklanganke/elasticsearch,chrismwendt/elasticsearch,NBSW/elasticsearch,LewayneNaidoo/elasticsearch,ThalaivaStars/OrgRepo1,anti-social/elasticsearch,fooljohnny/elasticsearch,aparo/elasticsearch,humandb/elasticsearch,btiernay/elasticsearch,jchampion/elasticsearch,ThalaivaStars/OrgRepo1,amit-shar/elasticsearch,jbertouch/elasticsearch,jbertouch/elasticsearch,xpandan/elasticsearch,acchen97/elasticsearch,vroyer/elassandra,ThiagoGarciaAlves/elasticsearch,TonyChai24/ESSource,ulkas/elasticsearch,kubum/elasticsearch,xpandan/elasticsearch,knight1128/elasticsearch,javachengwc/elasticsearch,markharwood/elasticsearch,njlawton/elasticsearch,davidvgalbraith/elasticsearch,dpursehouse/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,drewr/elasticsearch,vingupta3/elasticsearch,nilabhsagar/elasticsearch,girirajsharma/elasticsearch,mapr/elasticsearch,opendatasoft/elasticsearch,ouyangkongtong/elasticsearch,amit-shar/elasticsearch,bestwpw/elasticsearch,NBSW/elasticsearch,ricardocerq/elasticsearch,mjhennig/elasticsearch,javachengwc/elasticsearch,jaynblue/elasticsearch,tkssharma/elasticsearch,sposam/elasticsearch,tebriel/elasticsearch,TonyChai24/ESSource,dataduke/elasticsearch,lightslife/elasticsearch,rmuir/elasticsearch,socialrank/elasticsearch,alexbrasetvik/elasticsearch,episerver/elasticsearch,18098924759/elasticsearch,nomoa/elasticsearch,TonyChai24/ESSource,slavau/elasticsearch,zhiqinghuang/elasticsearch,Siddartha07/elasticsearch,golubev/elasticsearch,jchampion/elasticsearch,ZTE-PaaS/elasticsearch,HarishAtGitHub/elasticsearch,MichaelLiZhou/elasticsearch,SergVro/elasticsearch,jprante/elasticsearch,liweinan0423/elasticsearch,jimhooker2002/elasticsearch,LewayneNaidoo/elasticsearch,mjason3/elasticsearch,lchennup/elasticsearch,linglaiyao1314/elasticsearch,jeteve/elasticsearch,nomoa/elasticsearch,jeteve/elasticsearch,javachengwc/elasticsearch,18098924759/elasticsearch,boliza/elasticsearch,ulkas/elasticsearch,zkidkid/elasticsearch,avikurapati/elasticsearch,elasticdog/elasticsearch,AshishThakur/elasticsearch,easonC/elasticsearch,Widen/elasticsearch,Uiho/elasticsearch,nknize/elasticsearch,kingaj/elasticsearch,truemped/elasticsearch,girirajsharma/elasticsearch,AndreKR/elasticsearch,mm0/elasticsearch,huypx1292/elasticsearch,mjhennig/elasticsearch,jpountz/elasticsearch,EasonYi/elasticsearch,JackyMai/elasticsearch,kunallimaye/elasticsearch,njlawton/elasticsearch,queirozfcom/elasticsearch,hydro2k/elasticsearch,F0lha/elasticsearch,zhaocloud/elasticsearch,diendt/elasticsearch,lchennup/elasticsearch,amaliujia/elasticsearch,chirilo/elasticsearch,pranavraman/elasticsearch,jbertouch/elasticsearch,YosuaMichael/elasticsearch,phani546/elasticsearch,Rygbee/elasticsearch,mnylen/elasticsearch,geidies/elasticsearch,wayeast/elasticsearch,iamjakob/elasticsearch,brandonkearby/elasticsearch,lzo/elasticsearch-1,himanshuag/elasticsearch,kevinkluge/elasticsearch,geidies/elasticsearch,kkirsche/elasticsearch,dataduke/elasticsearch,spiegela/elasticsearch,episerver/elasticsearch,drewr/elasticsearch,mute/elasticsearch,IanvsPoplicola/elasticsearch,18098924759/elasticsearch,trangvh/elasticsearch,xuzha/elasticsearch,bestwpw/elasticsearch,Clairebi/ElasticsearchClone,mjason3/elasticsearch,hanswang/elasticsearch,lchennup/elasticsearch,wuranbo/elasticsearch,henakamaMSFT/elasticsearch,MichaelLiZhou/elasticsearch,mrorii/elasticsearch,jaynblue/elasticsearch,mbrukman/elasticsearch,nezirus/elasticsearch,avikurapati/elasticsearch,salyh/elasticsearch,lks21c/elasticsearch,vrkansagara/elasticsearch,heng4fun/elasticsearch,ImpressTV/elasticsearch,mohit/elasticsearch,bestwpw/elasticsearch,mgalushka/elasticsearch,heng4fun/elasticsearch,tkssharma/elasticsearch,strapdata/elassandra-test,rajanm/elasticsearch,peschlowp/elasticsearch,lightslife/elasticsearch,Microsoft/elasticsearch,myelin/elasticsearch,zkidkid/elasticsearch,fernandozhu/elasticsearch,pablocastro/elasticsearch,vietlq/elasticsearch,nrkkalyan/elasticsearch,aparo/elasticsearch,LeoYao/elasticsearch,dylan8902/elasticsearch,clintongormley/elasticsearch,xuzha/elasticsearch,mikemccand/elasticsearch,GlenRSmith/elasticsearch,brandonkearby/elasticsearch,wayeast/elasticsearch,sjohnr/elasticsearch,vingupta3/elasticsearch,fubuki/elasticsearch,girirajsharma/elasticsearch,kkirsche/elasticsearch,karthikjaps/elasticsearch,truemped/elasticsearch,Chhunlong/elasticsearch,nknize/elasticsearch,feiqitian/elasticsearch,Siddartha07/elasticsearch,gingerwizard/elasticsearch,tcucchietti/elasticsearch,snikch/elasticsearch,karthikjaps/elasticsearch,mm0/elasticsearch,andrestc/elasticsearch,abhijitiitr/es,hechunwen/elasticsearch,uboness/elasticsearch,Chhunlong/elasticsearch,alexbrasetvik/elasticsearch,mjhennig/elasticsearch,onegambler/elasticsearch,wuranbo/elasticsearch,wimvds/elasticsearch,clintongormley/elasticsearch,wittyameta/elasticsearch,nomoa/elasticsearch,polyfractal/elasticsearch,petabytedata/elasticsearch,JackyMai/elasticsearch,fforbeck/elasticsearch,xingguang2013/elasticsearch,jango2015/elasticsearch,beiske/elasticsearch,a2lin/elasticsearch,drewr/elasticsearch,jpountz/elasticsearch,iantruslove/elasticsearch,snikch/elasticsearch,slavau/elasticsearch,caengcjd/elasticsearch,diendt/elasticsearch,Microsoft/elasticsearch,peschlowp/elasticsearch,tebriel/elasticsearch,kkirsche/elasticsearch,salyh/elasticsearch,petabytedata/elasticsearch,luiseduardohdbackup/elasticsearch,wbowling/elasticsearch,Collaborne/elasticsearch,knight1128/elasticsearch,MetSystem/elasticsearch,markllama/elasticsearch,abibell/elasticsearch,polyfractal/elasticsearch,mcku/elasticsearch,Ansh90/elasticsearch,MjAbuz/elasticsearch,kenshin233/elasticsearch,Liziyao/elasticsearch,ajhalani/elasticsearch,YosuaMichael/elasticsearch,zhaocloud/elasticsearch,hafkensite/elasticsearch,franklanganke/elasticsearch,fubuki/elasticsearch,franklanganke/elasticsearch,wimvds/elasticsearch,vietlq/elasticsearch,vorce/es-metrics,njlawton/elasticsearch,alexshadow007/elasticsearch,hechunwen/elasticsearch,sneivandt/elasticsearch,shreejay/elasticsearch,springning/elasticsearch,karthikjaps/elasticsearch,ouyangkongtong/elasticsearch,truemped/elasticsearch,Asimov4/elasticsearch,Chhunlong/elasticsearch,mcku/elasticsearch,gmarz/elasticsearch,18098924759/elasticsearch,SergVro/elasticsearch,liweinan0423/elasticsearch,lightslife/elasticsearch,mcku/elasticsearch,JSCooke/elasticsearch,fforbeck/elasticsearch,AndreKR/elasticsearch,hanswang/elasticsearch,abibell/elasticsearch,pranavraman/elasticsearch,anti-social/elasticsearch,andrejserafim/elasticsearch,ckclark/elasticsearch,iantruslove/elasticsearch,kaneshin/elasticsearch,tsohil/elasticsearch,chirilo/elasticsearch,phani546/elasticsearch,davidvgalbraith/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,overcome/elasticsearch,Shekharrajak/elasticsearch,LeoYao/elasticsearch,robin13/elasticsearch,sc0ttkclark/elasticsearch,zhiqinghuang/elasticsearch,AshishThakur/elasticsearch,gingerwizard/elasticsearch,Charlesdong/elasticsearch,fforbeck/elasticsearch,xuzha/elasticsearch,Rygbee/elasticsearch,hirdesh2008/elasticsearch,springning/elasticsearch,IanvsPoplicola/elasticsearch,onegambler/elasticsearch,chrismwendt/elasticsearch,fred84/elasticsearch,Shepard1212/elasticsearch,drewr/elasticsearch,strapdata/elassandra-test,ydsakyclguozi/elasticsearch,anti-social/elasticsearch,weipinghe/elasticsearch,adrianbk/elasticsearch,KimTaehee/elasticsearch,alexkuk/elasticsearch,cwurm/elasticsearch,petabytedata/elasticsearch,Clairebi/ElasticsearchClone,sdauletau/elasticsearch,yanjunh/elasticsearch,fekaputra/elasticsearch,shreejay/elasticsearch,mapr/elasticsearch,jpountz/elasticsearch,boliza/elasticsearch,wayeast/elasticsearch,iantruslove/elasticsearch,ivansun1010/elasticsearch,mortonsykes/elasticsearch,dataduke/elasticsearch,i-am-Nathan/elasticsearch,mbrukman/elasticsearch,amit-shar/elasticsearch,MaineC/elasticsearch,VukDukic/elasticsearch,schonfeld/elasticsearch,sarwarbhuiyan/elasticsearch,kenshin233/elasticsearch,skearns64/elasticsearch,springning/elasticsearch,TonyChai24/ESSource,mnylen/elasticsearch,dataduke/elasticsearch,aglne/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,mcku/elasticsearch,KimTaehee/elasticsearch,MjAbuz/elasticsearch,thecocce/elasticsearch,zkidkid/elasticsearch,amit-shar/elasticsearch,Ansh90/elasticsearch,mm0/elasticsearch,Clairebi/ElasticsearchClone,amit-shar/elasticsearch,mohit/elasticsearch,andrejserafim/elasticsearch,mkis-/elasticsearch,dpursehouse/elasticsearch,Shepard1212/elasticsearch,socialrank/elasticsearch,opendatasoft/elasticsearch,lchennup/elasticsearch,HonzaKral/elasticsearch,sjohnr/elasticsearch,clintongormley/elasticsearch,zeroctu/elasticsearch,huypx1292/elasticsearch,snikch/elasticsearch,areek/elasticsearch,vingupta3/elasticsearch,yuy168/elasticsearch,vvcephei/elasticsearch,caengcjd/elasticsearch,MichaelLiZhou/elasticsearch,uboness/elasticsearch,scorpionvicky/elasticsearch,girirajsharma/elasticsearch,MisterAndersen/elasticsearch,mmaracic/elasticsearch,markwalkom/elasticsearch,masterweb121/elasticsearch,rajanm/elasticsearch,drewr/elasticsearch,mrorii/elasticsearch,SergVro/elasticsearch,schonfeld/elasticsearch,xingguang2013/elasticsearch,socialrank/elasticsearch,nrkkalyan/elasticsearch,camilojd/elasticsearch,mortonsykes/elasticsearch,awislowski/elasticsearch,rajanm/elasticsearch,ouyangkongtong/elasticsearch,petmit/elasticsearch,umeshdangat/elasticsearch,alexksikes/elasticsearch,vingupta3/elasticsearch,wittyameta/elasticsearch,mohsinh/elasticsearch,a2lin/elasticsearch,kenshin233/elasticsearch,queirozfcom/elasticsearch,awislowski/elasticsearch,JSCooke/elasticsearch,a2lin/elasticsearch,lightslife/elasticsearch,ouyangkongtong/elasticsearch,janmejay/elasticsearch,SergVro/elasticsearch,codebunt/elasticsearch,Liziyao/elasticsearch,huypx1292/elasticsearch,mmaracic/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,knight1128/elasticsearch,Widen/elasticsearch,vietlq/elasticsearch,umeshdangat/elasticsearch,loconsolutions/elasticsearch,MjAbuz/elasticsearch,mohsinh/elasticsearch,feiqitian/elasticsearch,acchen97/elasticsearch,masterweb121/elasticsearch,drewr/elasticsearch,kalimatas/elasticsearch,nezirus/elasticsearch,synhershko/elasticsearch,libosu/elasticsearch,fooljohnny/elasticsearch,sposam/elasticsearch,tcucchietti/elasticsearch,Ansh90/elasticsearch,zeroctu/elasticsearch,khiraiwa/elasticsearch,markwalkom/elasticsearch,raishiv/elasticsearch,sauravmondallive/elasticsearch,Microsoft/elasticsearch,vietlq/elasticsearch,achow/elasticsearch,wittyameta/elasticsearch,fubuki/elasticsearch,GlenRSmith/elasticsearch,wbowling/elasticsearch,lydonchandra/elasticsearch,artnowo/elasticsearch,likaiwalkman/elasticsearch,glefloch/elasticsearch,codebunt/elasticsearch,janmejay/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,luiseduardohdbackup/elasticsearch,tcucchietti/elasticsearch,koxa29/elasticsearch,kubum/elasticsearch,Brijeshrpatel9/elasticsearch,feiqitian/elasticsearch,sarwarbhuiyan/elasticsearch,vrkansagara/elasticsearch,uschindler/elasticsearch,hirdesh2008/elasticsearch,easonC/elasticsearch,mapr/elasticsearch,ivansun1010/elasticsearch,kunallimaye/elasticsearch,kalburgimanjunath/elasticsearch,davidvgalbraith/elasticsearch,IanvsPoplicola/elasticsearch,mbrukman/elasticsearch,martinstuga/elasticsearch,elancom/elasticsearch,HarishAtGitHub/elasticsearch,mrorii/elasticsearch,hanswang/elasticsearch,martinstuga/elasticsearch,JervyShi/elasticsearch,gingerwizard/elasticsearch,mcku/elasticsearch,sdauletau/elasticsearch,masaruh/elasticsearch,Uiho/elasticsearch,mkis-/elasticsearch,LeoYao/elasticsearch,wenpos/elasticsearch,yynil/elasticsearch,geidies/elasticsearch,salyh/elasticsearch,huypx1292/elasticsearch,infusionsoft/elasticsearch,humandb/elasticsearch,s1monw/elasticsearch,davidvgalbraith/elasticsearch,StefanGor/elasticsearch,rento19962/elasticsearch,dataduke/elasticsearch,MjAbuz/elasticsearch,Collaborne/elasticsearch,kcompher/elasticsearch,naveenhooda2000/elasticsearch,btiernay/elasticsearch,fooljohnny/elasticsearch,i-am-Nathan/elasticsearch,adrianbk/elasticsearch,mapr/elasticsearch,xpandan/elasticsearch,wenpos/elasticsearch,infusionsoft/elasticsearch,vorce/es-metrics,MisterAndersen/elasticsearch,aglne/elasticsearch,andrewvc/elasticsearch,trangvh/elasticsearch,wbowling/elasticsearch,mohsinh/elasticsearch,geidies/elasticsearch,andrestc/elasticsearch,knight1128/elasticsearch,zhaocloud/elasticsearch,robin13/elasticsearch,hanswang/elasticsearch,ouyangkongtong/elasticsearch,wangtuo/elasticsearch,overcome/elasticsearch,sposam/elasticsearch,vrkansagara/elasticsearch,alexbrasetvik/elasticsearch,rlugojr/elasticsearch,likaiwalkman/elasticsearch,HarishAtGitHub/elasticsearch,marcuswr/elasticsearch-dateline,MichaelLiZhou/elasticsearch,lks21c/elasticsearch,KimTaehee/elasticsearch,lzo/elasticsearch-1,areek/elasticsearch,geidies/elasticsearch,clintongormley/elasticsearch,mm0/elasticsearch,zhiqinghuang/elasticsearch,NBSW/elasticsearch,elancom/elasticsearch,kalburgimanjunath/elasticsearch,koxa29/elasticsearch,lightslife/elasticsearch,sneivandt/elasticsearch,strapdata/elassandra5-rc,elasticdog/elasticsearch,strapdata/elassandra5-rc,zeroctu/elasticsearch,fubuki/elasticsearch,Charlesdong/elasticsearch,infusionsoft/elasticsearch,weipinghe/elasticsearch,nomoa/elasticsearch,EasonYi/elasticsearch,PhaedrusTheGreek/elasticsearch,wimvds/elasticsearch,C-Bish/elasticsearch,elancom/elasticsearch,masaruh/elasticsearch,JackyMai/elasticsearch,mjason3/elasticsearch,yuy168/elasticsearch,ThiagoGarciaAlves/elasticsearch,abibell/elasticsearch,ThalaivaStars/OrgRepo1,milodky/elasticsearch,SaiprasadKrishnamurthy/elasticsearch,truemped/elasticsearch,kubum/elasticsearch,C-Bish/elasticsearch,feiqitian/elasticsearch,micpalmia/elasticsearch,AndreKR/elasticsearch,uboness/elasticsearch,hafkensite/elasticsearch,myelin/elasticsearch,apepper/elasticsearch,tahaemin/elasticsearch,yongminxia/elasticsearch,drewr/elasticsearch,kunallimaye/elasticsearch,Fsero/elasticsearch,springning/elasticsearch,spiegela/elasticsearch,boliza/elasticsearch,mm0/elasticsearch,pozhidaevak/elasticsearch,AndreKR/elasticsearch,Fsero/elasticsearch,EasonYi/elasticsearch,markwalkom/elasticsearch,skearns64/elasticsearch,koxa29/elasticsearch,sscarduzio/elasticsearch,jimczi/elasticsearch,artnowo/elasticsearch,jw0201/elastic,iamjakob/elasticsearch,phani546/elasticsearch,YosuaMichael/elasticsearch,kevinkluge/elasticsearch,MjAbuz/elasticsearch,mmaracic/elasticsearch,Siddartha07/elasticsearch,adrianbk/elasticsearch,jbertouch/elasticsearch,ESamir/elasticsearch,vietlq/elasticsearch,NBSW/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,wangtuo/elasticsearch,diendt/elasticsearch,cnfire/elasticsearch-1,infusionsoft/elasticsearch,rlugojr/elasticsearch,C-Bish/elasticsearch,nellicus/elasticsearch,thecocce/elasticsearch,scorpionvicky/elasticsearch,jpountz/elasticsearch,chirilo/elasticsearch,HarishAtGitHub/elasticsearch,jimhooker2002/elasticsearch,liweinan0423/elasticsearch,szroland/elasticsearch,kingaj/elasticsearch,fernandozhu/elasticsearch,kubum/elasticsearch,jw0201/elastic,Asimov4/elasticsearch,rmuir/elasticsearch,thecocce/elasticsearch,sauravmondallive/elasticsearch,MjAbuz/elasticsearch,alexkuk/elasticsearch,adrianbk/elasticsearch,ESamir/elasticsearch,umeshdangat/elasticsearch,himanshuag/elasticsearch,diendt/elasticsearch,loconsolutions/elasticsearch,sscarduzio/elasticsearch,mjhennig/elasticsearch,mkis-/elasticsearch,huanzhong/elasticsearch,overcome/elasticsearch,naveenhooda2000/elasticsearch,Collaborne/elasticsearch,karthikjaps/elasticsearch,rento19962/elasticsearch,adrianbk/elasticsearch,kimchy/elasticsearch,tahaemin/elasticsearch,kimimj/elasticsearch,sc0ttkclark/elasticsearch,easonC/elasticsearch,kcompher/elasticsearch,HonzaKral/elasticsearch,fred84/elasticsearch,rmuir/elasticsearch,smflorentino/elasticsearch,mikemccand/elasticsearch,lmenezes/elasticsearch,markwalkom/elasticsearch,yynil/elasticsearch,wittyameta/elasticsearch,iantruslove/elasticsearch,dongjoon-hyun/elasticsearch,qwerty4030/elasticsearch,dpursehouse/elasticsearch,polyfractal/elasticsearch,btiernay/elasticsearch,qwerty4030/elasticsearch,wayeast/elasticsearch,abhijitiitr/es,Uiho/elasticsearch,s1monw/elasticsearch,lmtwga/elasticsearch,uschindler/elasticsearch,ajhalani/elasticsearch,trangvh/elasticsearch,wangtuo/elasticsearch,pritishppai/elasticsearch,awislowski/elasticsearch,SergVro/elasticsearch,mohsinh/elasticsearch,obourgain/elasticsearch,Helen-Zhao/elasticsearch,sscarduzio/elasticsearch,alexbrasetvik/elasticsearch,phani546/elasticsearch,markllama/elasticsearch,wayeast/elasticsearch,iacdingping/elasticsearch,zhaocloud/elasticsearch,polyfractal/elasticsearch,ivansun1010/elasticsearch,Rygbee/elasticsearch,jeteve/elasticsearch,socialrank/elasticsearch,lks21c/elasticsearch,StefanGor/elasticsearch,sauravmondallive/elasticsearch,lydonchandra/elasticsearch,ydsakyclguozi/elasticsearch,sc0ttkclark/elasticsearch,codebunt/elasticsearch,easonC/elasticsearch,vingupta3/elasticsearch,Brijeshrpatel9/elasticsearch,Kakakakakku/elasticsearch,overcome/elasticsearch,rajanm/elasticsearch,hechunwen/elasticsearch,vingupta3/elasticsearch,huanzhong/elasticsearch,heng4fun/elasticsearch,girirajsharma/elasticsearch,kkirsche/elasticsearch,mcku/elasticsearch,sc0ttkclark/elasticsearch,HonzaKral/elasticsearch,ThiagoGarciaAlves/elasticsearch,amaliujia/elasticsearch,wimvds/elasticsearch,khiraiwa/elasticsearch,ZTE-PaaS/elasticsearch,vietlq/elasticsearch,davidvgalbraith/elasticsearch,milodky/elasticsearch,dataduke/elasticsearch,mgalushka/elasticsearch,ouyangkongtong/elasticsearch,Shekharrajak/elasticsearch,codebunt/elasticsearch,obourgain/elasticsearch,Flipkart/elasticsearch,szroland/elasticsearch,salyh/elasticsearch,tebriel/elasticsearch,synhershko/elasticsearch,AndreKR/elasticsearch,Shepard1212/elasticsearch,KimTaehee/elasticsearch,winstonewert/elasticsearch,easonC/elasticsearch,rento19962/elasticsearch,dpursehouse/elasticsearch,achow/elasticsearch,humandb/elasticsearch,Fsero/elasticsearch,camilojd/elasticsearch,mbrukman/elasticsearch,alexksikes/elasticsearch,markharwood/elasticsearch,mohit/elasticsearch,kimimj/elasticsearch,AleksKochev/elasticsearch,ckclark/elasticsearch,Ansh90/elasticsearch,linglaiyao1314/elasticsearch,schonfeld/elasticsearch,wuranbo/elasticsearch,spiegela/elasticsearch,LeoYao/elasticsearch,nellicus/elasticsearch,milodky/elasticsearch,libosu/elasticsearch,pranavraman/elasticsearch,opendatasoft/elasticsearch,Ansh90/elasticsearch,s1monw/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,zkidkid/elasticsearch,Shekharrajak/elasticsearch,rhoml/elasticsearch,milodky/elasticsearch,TonyChai24/ESSource,easonC/elasticsearch,jchampion/elasticsearch,weipinghe/elasticsearch,chrismwendt/elasticsearch,myelin/elasticsearch,MetSystem/elasticsearch,YosuaMichael/elasticsearch,kunallimaye/elasticsearch,nezirus/elasticsearch,spiegela/elasticsearch,mkis-/elasticsearch,adrianbk/elasticsearch,tsohil/elasticsearch,snikch/elasticsearch,lmtwga/elasticsearch,markllama/elasticsearch,kingaj/elasticsearch,schonfeld/elasticsearch,anti-social/elasticsearch,masterweb121/elasticsearch,andrejserafim/elasticsearch,abhijitiitr/es,springning/elasticsearch,kenshin233/elasticsearch,ImpressTV/elasticsearch,njlawton/elasticsearch,smflorentino/elasticsearch,nilabhsagar/elasticsearch,Brijeshrpatel9/elasticsearch,knight1128/elasticsearch,Ansh90/elasticsearch,Asimov4/elasticsearch,awislowski/elasticsearch,sauravmondallive/elasticsearch,pranavraman/elasticsearch,ckclark/elasticsearch,shreejay/elasticsearch,alexksikes/elasticsearch,scottsom/elasticsearch,luiseduardohdbackup/elasticsearch,acchen97/elasticsearch,nellicus/elasticsearch,Liziyao/elasticsearch,caengcjd/elasticsearch,nknize/elasticsearch,Siddartha07/elasticsearch,clintongormley/elasticsearch,Uiho/elasticsearch,zeroctu/elasticsearch,vvcephei/elasticsearch,lmtwga/elasticsearch,lzo/elasticsearch-1,kimimj/elasticsearch,qwerty4030/elasticsearch,peschlowp/elasticsearch,jprante/elasticsearch,vroyer/elasticassandra,vrkansagara/elasticsearch,lzo/elasticsearch-1,ZTE-PaaS/elasticsearch,clintongormley/elasticsearch,Widen/elasticsearch,TonyChai24/ESSource,andrejserafim/elasticsearch,tkssharma/elasticsearch,socialrank/elasticsearch,zhiqinghuang/elasticsearch,ESamir/elasticsearch,bestwpw/elasticsearch,vvcephei/elasticsearch,micpalmia/elasticsearch,yongminxia/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,vroyer/elassandra,abibell/elasticsearch,tsohil/elasticsearch,pritishppai/elasticsearch,jeteve/elasticsearch,Widen/elasticsearch,NBSW/elasticsearch,wenpos/elasticsearch,Shepard1212/elasticsearch,areek/elasticsearch,huanzhong/elasticsearch,jaynblue/elasticsearch,beiske/elasticsearch,Ansh90/elasticsearch,libosu/elasticsearch,masterweb121/elasticsearch,trangvh/elasticsearch,nrkkalyan/elasticsearch,combinatorist/elasticsearch,andrestc/elasticsearch,masterweb121/elasticsearch,LeoYao/elasticsearch,sposam/elasticsearch,beiske/elasticsearch,kevinkluge/elasticsearch,strapdata/elassandra-test,ydsakyclguozi/elasticsearch,btiernay/elasticsearch,iamjakob/elasticsearch,achow/elasticsearch,fernandozhu/elasticsearch,sposam/elasticsearch,lks21c/elasticsearch,pritishppai/elasticsearch,MaineC/elasticsearch,libosu/elasticsearch,ajhalani/elasticsearch,mkis-/elasticsearch,VukDukic/elasticsearch,xuzha/elasticsearch,artnowo/elasticsearch,fooljohnny/elasticsearch,polyfractal/elasticsearch,Widen/elasticsearch,acchen97/elasticsearch,sdauletau/elasticsearch,kimimj/elasticsearch,fforbeck/elasticsearch,glefloch/elasticsearch,MaineC/elasticsearch,alexksikes/elasticsearch,apepper/elasticsearch,rlugojr/elasticsearch,truemped/elasticsearch,pranavraman/elasticsearch,lightslife/elasticsearch,zeroctu/elasticsearch,lydonchandra/elasticsearch,jeteve/elasticsearch,smflorentino/elasticsearch,wangtuo/elasticsearch,iantruslove/elasticsearch,dylan8902/elasticsearch,acchen97/elasticsearch,linglaiyao1314/elasticsearch,lzo/elasticsearch-1,mbrukman/elasticsearch,cwurm/elasticsearch,ThiagoGarciaAlves/elasticsearch,huanzhong/elasticsearch,AleksKochev/elasticsearch,liweinan0423/elasticsearch,wayeast/elasticsearch,petmit/elasticsearch,janmejay/elasticsearch,wittyameta/elasticsearch,nazarewk/elasticsearch,ESamir/elasticsearch,heng4fun/elasticsearch,jprante/elasticsearch,maddin2016/elasticsearch,yongminxia/elasticsearch,naveenhooda2000/elasticsearch,awislowski/elasticsearch,alexbrasetvik/elasticsearch,xuzha/elasticsearch,jimczi/elasticsearch,MichaelLiZhou/elasticsearch,MichaelLiZhou/elasticsearch,btiernay/elasticsearch,luiseduardohdbackup/elasticsearch,markllama/elasticsearch,milodky/elasticsearch,palecur/elasticsearch,vroyer/elasticassandra,MisterAndersen/elasticsearch,aglne/elasticsearch,MetSystem/elasticsearch,nellicus/elasticsearch,Liziyao/elasticsearch,dantuffery/elasticsearch,chirilo/elasticsearch,xingguang2013/elasticsearch,wbowling/elasticsearch,pozhidaevak/elasticsearch,mohsinh/elasticsearch,chirilo/elasticsearch,myelin/elasticsearch,baishuo/elasticsearch_v2.1.0-baishuo,vietlq/elasticsearch,markharwood/elasticsearch,dantuffery/elasticsearch,tkssharma/elasticsearch,fekaputra/elasticsearch,jango2015/elasticsearch,opendatasoft/elasticsearch,abibell/elasticsearch,khiraiwa/elasticsearch,kaneshin/elasticsearch,StefanGor/elasticsearch,ydsakyclguozi/elasticsearch,episerver/elasticsearch,wbowling/elasticsearch,gmarz/elasticsearch,gingerwizard/elasticsearch,andrestc/elasticsearch,gmarz/elasticsearch,likaiwalkman/elasticsearch,brandonkearby/elasticsearch,kunallimaye/elasticsearch,sdauletau/elasticsearch,markharwood/elasticsearch,kcompher/elasticsearch,franklanganke/elasticsearch,kimimj/elasticsearch,C-Bish/elasticsearch,strapdata/elassandra-test,himanshuag/elasticsearch,EasonYi/elasticsearch,elancom/elasticsearch,bestwpw/elasticsearch,LeoYao/elasticsearch,sc0ttkclark/elasticsearch,martinstuga/elasticsearch,PhaedrusTheGreek/elasticsearch,smflorentino/elasticsearch,jango2015/elasticsearch,combinatorist/elasticsearch,uschindler/elasticsearch,gfyoung/elasticsearch,caengcjd/elasticsearch,kkirsche/elasticsearch,qwerty4030/elasticsearch,pablocastro/elasticsearch,phani546/elasticsearch,tkssharma/elasticsearch,huanzhong/elasticsearch,AshishThakur/elasticsearch,snikch/elasticsearch,Collaborne/elasticsearch,i-am-Nathan/elasticsearch,AshishThakur/elasticsearch,janmejay/elasticsearch,scottsom/elasticsearch,EasonYi/elasticsearch,andrestc/elasticsearch,raishiv/elasticsearch,ulkas/elasticsearch,codebunt/elasticsearch,elancom/elasticsearch,gfyoung/elasticsearch,pranavraman/elasticsearch,yuy168/elasticsearch,F0lha/elasticsearch,wangtuo/elasticsearch,camilojd/elasticsearch,NBSW/elasticsearch,abhijitiitr/es,avikurapati/elasticsearch,kubum/elasticsearch,caengcjd/elasticsearch,linglaiyao1314/elasticsearch,linglaiyao1314/elasticsearch,hydro2k/elasticsearch,zeroctu/elasticsearch,kcompher/elasticsearch,cnfire/elasticsearch-1,fooljohnny/elasticsearch,AleksKochev/elasticsearch,huanzhong/elasticsearch,AndreKR/elasticsearch,jimhooker2002/elasticsearch,ESamir/elasticsearch,tcucchietti/elasticsearch,Liziyao/elasticsearch,Collaborne/elasticsearch,dongjoon-hyun/elasticsearch,combinatorist/elasticsearch,Clairebi/ElasticsearchClone,gingerwizard/elasticsearch,palecur/elasticsearch,JackyMai/elasticsearch,AleksKochev/elasticsearch,Asimov4/elasticsearch,btiernay/elasticsearch,sscarduzio/elasticsearch,dylan8902/elasticsearch,a2lin/elasticsearch,queirozfcom/elasticsearch,tahaemin/elasticsearch,pablocastro/elasticsearch,HarishAtGitHub/elasticsearch,ricardocerq/elasticsearch,sarwarbhuiyan/elasticsearch,mm0/elasticsearch,feiqitian/elasticsearch,obourgain/elasticsearch,apepper/elasticsearch,kalburgimanjunath/elasticsearch,KimTaehee/elasticsearch,spiegela/elasticsearch,winstonewert/elasticsearch,hydro2k/elasticsearch,vingupta3/elasticsearch,mmaracic/elasticsearch,Liziyao/elasticsearch,tahaemin/elasticsearch,TonyChai24/ESSource,jsgao0/elasticsearch,mikemccand/elasticsearch,hanst/elasticsearch,strapdata/elassandra5-rc,mjhennig/elasticsearch,vinsonlou/elasticsearch,aglne/elasticsearch,jpountz/elasticsearch,socialrank/elasticsearch,ImpressTV/elasticsearch,EasonYi/elasticsearch,wangyuxue/elasticsearch,acchen97/elasticsearch,kaneshin/elasticsearch,coding0011/elasticsearch,i-am-Nathan/elasticsearch,ImpressTV/elasticsearch,Flipkart/elasticsearch,masaruh/elasticsearch,kcompher/elasticsearch,markharwood/elasticsearch,apepper/elasticsearch,brwe/elasticsearch,achow/elasticsearch,markllama/elasticsearch,vorce/es-metrics,dantuffery/elasticsearch,janmejay/elasticsearch,umeshdangat/elasticsearch,hanst/elasticsearch,vorce/es-metrics,aparo/elasticsearch,ulkas/elasticsearch,truemped/elasticsearch,fubuki/elasticsearch,nazarewk/elasticsearch,mortonsykes/elasticsearch,HarishAtGitHub/elasticsearch,hafkensite/elasticsearch,mute/elasticsearch,skearns64/elasticsearch,nrkkalyan/elasticsearch,rento19962/elasticsearch,mohit/elasticsearch,lchennup/elasticsearch,dantuffery/elasticsearch,szroland/elasticsearch,skearns64/elasticsearch,sneivandt/elasticsearch,uboness/elasticsearch,jprante/elasticsearch,mjason3/elasticsearch,Clairebi/ElasticsearchClone,camilojd/elasticsearch,peschlowp/elasticsearch,jchampion/elasticsearch,sreeramjayan/elasticsearch,strapdata/elassandra,slavau/elasticsearch,andrejserafim/elasticsearch,humandb/elasticsearch,mnylen/elasticsearch,YosuaMichael/elasticsearch,boliza/elasticsearch,javachengwc/elasticsearch,wenpos/elasticsearch,lmtwga/elasticsearch,yongminxia/elasticsearch,loconsolutions/elasticsearch,bawse/elasticsearch,himanshuag/elasticsearch,springning/elasticsearch,MetSystem/elasticsearch,zhaocloud/elasticsearch,alexshadow007/elasticsearch,Uiho/elasticsearch,tebriel/elasticsearch,ulkas/elasticsearch,kalburgimanjunath/elasticsearch,alexksikes/elasticsearch,18098924759/elasticsearch,Kakakakakku/elasticsearch,mcku/elasticsearch,yuy168/elasticsearch,GlenRSmith/elasticsearch,Rygbee/elasticsearch,Asimov4/elasticsearch,kenshin233/elasticsearch,peschlowp/elasticsearch,GlenRSmith/elasticsearch,queirozfcom/elasticsearch,hafkensite/elasticsearch,strapdata/elassandra-test,jprante/elasticsearch,mmaracic/elasticsearch,iacdingping/elasticsearch,szroland/elasticsearch,javachengwc/elasticsearch,cnfire/elasticsearch-1,HonzaKral/elasticsearch
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.search.query; import com.google.common.collect.ImmutableMap; import org.apache.lucene.search.*; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.search.Queries; import org.elasticsearch.common.lucene.search.function.BoostScoreFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchPhase; import org.elasticsearch.search.facet.FacetPhase; import org.elasticsearch.search.internal.ContextIndexSearcher; import org.elasticsearch.search.internal.ScopePhase; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.sort.SortParseElement; import org.elasticsearch.search.sort.TrackScoresParseElement; import java.util.Map; /** * */ public class QueryPhase implements SearchPhase { private final FacetPhase facetPhase; @Inject public QueryPhase(FacetPhase facetPhase) { this.facetPhase = facetPhase; } @Override public Map<String, ? extends SearchParseElement> parseElements() { ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); parseElements.put("from", new FromParseElement()).put("size", new SizeParseElement()) .put("indices_boost", new IndicesBoostParseElement()) .put("indicesBoost", new IndicesBoostParseElement()) .put("query", new QueryParseElement()) .put("queryBinary", new QueryBinaryParseElement()) .put("query_binary", new QueryBinaryParseElement()) .put("filter", new FilterParseElement()) .put("filterBinary", new FilterBinaryParseElement()) .put("filter_binary", new FilterBinaryParseElement()) .put("sort", new SortParseElement()) .put("trackScores", new TrackScoresParseElement()) .put("track_scores", new TrackScoresParseElement()) .put("min_score", new MinScoreParseElement()) .put("minScore", new MinScoreParseElement()) .putAll(facetPhase.parseElements()); return parseElements.build(); } @Override public void preProcess(SearchContext context) { if (context.query() == null) { context.parsedQuery(ParsedQuery.MATCH_ALL_PARSED_QUERY); } if (context.queryBoost() != 1.0f) { context.parsedQuery(new ParsedQuery(new FunctionScoreQuery(context.query(), new BoostScoreFunction(context.queryBoost())), context.parsedQuery())); } Filter searchFilter = context.mapperService().searchFilter(context.types()); if (searchFilter != null) { if (Queries.isMatchAllQuery(context.query())) { Query q = new DeletionAwareConstantScoreQuery(context.filterCache().cache(searchFilter)); q.setBoost(context.query().getBoost()); context.parsedQuery(new ParsedQuery(q, context.parsedQuery())); } else { context.parsedQuery(new ParsedQuery(new FilteredQuery(context.query(), context.filterCache().cache(searchFilter)), context.parsedQuery())); } } facetPhase.preProcess(context); } public void execute(SearchContext searchContext) throws QueryPhaseExecutionException { // set the filter on the searcher if (searchContext.scopePhases() != null) { // we have scoped queries, refresh the id cache try { searchContext.idCache().refresh(searchContext.searcher().subReaders()); } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to refresh id cache for child queries", e); } // process scoped queries (from the last to the first, working with the parsing option here) for (int i = searchContext.scopePhases().size() - 1; i >= 0; i--) { ScopePhase scopePhase = searchContext.scopePhases().get(i); if (scopePhase instanceof ScopePhase.TopDocsPhase) { ScopePhase.TopDocsPhase topDocsPhase = (ScopePhase.TopDocsPhase) scopePhase; topDocsPhase.clear(); int numDocs = (searchContext.from() + searchContext.size()); if (numDocs == 0) { numDocs = 1; } try { numDocs *= topDocsPhase.factor(); while (true) { if (topDocsPhase.scope() != null) { searchContext.searcher().processingScope(topDocsPhase.scope()); } TopDocs topDocs = searchContext.searcher().search(topDocsPhase.query(), numDocs); if (topDocsPhase.scope() != null) { // we mark the scope as processed, so we don't process it again, even if we need to rerun the query... searchContext.searcher().processedScope(); } topDocsPhase.processResults(topDocs, searchContext); // check if we found enough docs, if so, break if (topDocsPhase.numHits() >= (searchContext.from() + searchContext.size())) { break; } // if we did not find enough docs, check if it make sense to search further if (topDocs.totalHits <= numDocs) { break; } // if not, update numDocs, and search again numDocs *= topDocsPhase.incrementalFactor(); if (numDocs > topDocs.totalHits) { numDocs = topDocs.totalHits; } } } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute child query [" + scopePhase.query() + "]", e); } } else if (scopePhase instanceof ScopePhase.CollectorPhase) { try { ScopePhase.CollectorPhase collectorPhase = (ScopePhase.CollectorPhase) scopePhase; // collector phase might not require extra processing, for example, when scrolling if (!collectorPhase.requiresProcessing()) { continue; } if (scopePhase.scope() != null) { searchContext.searcher().processingScope(scopePhase.scope()); } Collector collector = collectorPhase.collector(); searchContext.searcher().search(collectorPhase.query(), collector); collectorPhase.processCollector(collector); if (collectorPhase.scope() != null) { // we mark the scope as processed, so we don't process it again, even if we need to rerun the query... searchContext.searcher().processedScope(); } } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute child query [" + scopePhase.query() + "]", e); } } } } searchContext.searcher().processingScope(ContextIndexSearcher.Scopes.MAIN); try { searchContext.queryResult().from(searchContext.from()); searchContext.queryResult().size(searchContext.size()); Query query = searchContext.query(); TopDocs topDocs; int numDocs = searchContext.from() + searchContext.size(); if (numDocs == 0) { // if 0 was asked, change it to 1 since 0 is not allowed numDocs = 1; } if (searchContext.searchType() == SearchType.COUNT) { TotalHitCountCollector collector = new TotalHitCountCollector(); searchContext.searcher().search(query, collector); topDocs = new TopDocs(collector.getTotalHits(), Lucene.EMPTY_SCORE_DOCS, 0); } else if (searchContext.searchType() == SearchType.SCAN) { topDocs = searchContext.scanContext().execute(searchContext); } else if (searchContext.sort() != null) { topDocs = searchContext.searcher().search(query, null, numDocs, searchContext.sort()); } else { topDocs = searchContext.searcher().search(query, numDocs); } searchContext.queryResult().topDocs(topDocs); } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute main query", e); } finally { searchContext.searcher().processedScope(); } facetPhase.execute(searchContext); } }
src/main/java/org/elasticsearch/search/query/QueryPhase.java
/* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch 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.elasticsearch.search.query; import com.google.common.collect.ImmutableMap; import org.apache.lucene.search.*; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.lucene.search.function.BoostScoreFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.search.SearchParseElement; import org.elasticsearch.search.SearchPhase; import org.elasticsearch.search.facet.FacetPhase; import org.elasticsearch.search.internal.ContextIndexSearcher; import org.elasticsearch.search.internal.ScopePhase; import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.sort.SortParseElement; import org.elasticsearch.search.sort.TrackScoresParseElement; import java.util.Map; /** * */ public class QueryPhase implements SearchPhase { private final FacetPhase facetPhase; @Inject public QueryPhase(FacetPhase facetPhase) { this.facetPhase = facetPhase; } @Override public Map<String, ? extends SearchParseElement> parseElements() { ImmutableMap.Builder<String, SearchParseElement> parseElements = ImmutableMap.builder(); parseElements.put("from", new FromParseElement()).put("size", new SizeParseElement()) .put("indices_boost", new IndicesBoostParseElement()) .put("indicesBoost", new IndicesBoostParseElement()) .put("query", new QueryParseElement()) .put("queryBinary", new QueryBinaryParseElement()) .put("query_binary", new QueryBinaryParseElement()) .put("filter", new FilterParseElement()) .put("filterBinary", new FilterBinaryParseElement()) .put("filter_binary", new FilterBinaryParseElement()) .put("sort", new SortParseElement()) .put("trackScores", new TrackScoresParseElement()) .put("track_scores", new TrackScoresParseElement()) .put("min_score", new MinScoreParseElement()) .put("minScore", new MinScoreParseElement()) .putAll(facetPhase.parseElements()); return parseElements.build(); } @Override public void preProcess(SearchContext context) { if (context.query() == null) { context.parsedQuery(ParsedQuery.MATCH_ALL_PARSED_QUERY); } if (context.queryBoost() != 1.0f) { context.parsedQuery(new ParsedQuery(new FunctionScoreQuery(context.query(), new BoostScoreFunction(context.queryBoost())), context.parsedQuery())); } Filter searchFilter = context.mapperService().searchFilter(context.types()); if (searchFilter != null) { context.parsedQuery(new ParsedQuery(new FilteredQuery(context.query(), context.filterCache().cache(searchFilter)), context.parsedQuery())); } facetPhase.preProcess(context); } public void execute(SearchContext searchContext) throws QueryPhaseExecutionException { // set the filter on the searcher if (searchContext.scopePhases() != null) { // we have scoped queries, refresh the id cache try { searchContext.idCache().refresh(searchContext.searcher().subReaders()); } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to refresh id cache for child queries", e); } // process scoped queries (from the last to the first, working with the parsing option here) for (int i = searchContext.scopePhases().size() - 1; i >= 0; i--) { ScopePhase scopePhase = searchContext.scopePhases().get(i); if (scopePhase instanceof ScopePhase.TopDocsPhase) { ScopePhase.TopDocsPhase topDocsPhase = (ScopePhase.TopDocsPhase) scopePhase; topDocsPhase.clear(); int numDocs = (searchContext.from() + searchContext.size()); if (numDocs == 0) { numDocs = 1; } try { numDocs *= topDocsPhase.factor(); while (true) { if (topDocsPhase.scope() != null) { searchContext.searcher().processingScope(topDocsPhase.scope()); } TopDocs topDocs = searchContext.searcher().search(topDocsPhase.query(), numDocs); if (topDocsPhase.scope() != null) { // we mark the scope as processed, so we don't process it again, even if we need to rerun the query... searchContext.searcher().processedScope(); } topDocsPhase.processResults(topDocs, searchContext); // check if we found enough docs, if so, break if (topDocsPhase.numHits() >= (searchContext.from() + searchContext.size())) { break; } // if we did not find enough docs, check if it make sense to search further if (topDocs.totalHits <= numDocs) { break; } // if not, update numDocs, and search again numDocs *= topDocsPhase.incrementalFactor(); if (numDocs > topDocs.totalHits) { numDocs = topDocs.totalHits; } } } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute child query [" + scopePhase.query() + "]", e); } } else if (scopePhase instanceof ScopePhase.CollectorPhase) { try { ScopePhase.CollectorPhase collectorPhase = (ScopePhase.CollectorPhase) scopePhase; // collector phase might not require extra processing, for example, when scrolling if (!collectorPhase.requiresProcessing()) { continue; } if (scopePhase.scope() != null) { searchContext.searcher().processingScope(scopePhase.scope()); } Collector collector = collectorPhase.collector(); searchContext.searcher().search(collectorPhase.query(), collector); collectorPhase.processCollector(collector); if (collectorPhase.scope() != null) { // we mark the scope as processed, so we don't process it again, even if we need to rerun the query... searchContext.searcher().processedScope(); } } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute child query [" + scopePhase.query() + "]", e); } } } } searchContext.searcher().processingScope(ContextIndexSearcher.Scopes.MAIN); try { searchContext.queryResult().from(searchContext.from()); searchContext.queryResult().size(searchContext.size()); Query query = searchContext.query(); TopDocs topDocs; int numDocs = searchContext.from() + searchContext.size(); if (numDocs == 0) { // if 0 was asked, change it to 1 since 0 is not allowed numDocs = 1; } if (searchContext.searchType() == SearchType.COUNT) { TotalHitCountCollector collector = new TotalHitCountCollector(); searchContext.searcher().search(query, collector); topDocs = new TopDocs(collector.getTotalHits(), Lucene.EMPTY_SCORE_DOCS, 0); } else if (searchContext.searchType() == SearchType.SCAN) { topDocs = searchContext.scanContext().execute(searchContext); } else if (searchContext.sort() != null) { topDocs = searchContext.searcher().search(query, null, numDocs, searchContext.sort()); } else { topDocs = searchContext.searcher().search(query, numDocs); } searchContext.queryResult().topDocs(topDocs); } catch (Exception e) { throw new QueryPhaseExecutionException(searchContext, "Failed to execute main query", e); } finally { searchContext.searcher().processedScope(); } facetPhase.execute(searchContext); } }
optimize match all query against a type to be wrapped with a constant score query and not filtered
src/main/java/org/elasticsearch/search/query/QueryPhase.java
optimize match all query against a type to be wrapped with a constant score query and not filtered
Java
bsd-3-clause
c138fa6e74820bae388798b8a1f8f462e6e62ab8
0
uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo,uw-dims/tupelo
/** * Copyright ยฉ 2015, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the University of Washington nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * 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 UNIVERSITY OF * WASHINGTON 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. */ package edu.uw.apl.tupelo.store.filesys; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sqlite.JDBC; import edu.uw.apl.commons.tsk4j.digests.BodyFile.Record; import edu.uw.apl.tupelo.model.ManagedDiskDescriptor; /** * A store for keeping a disk's file {@link Record} information. <br> * The implementation uses a SQLite database */ public class FileRecordStore implements Closeable { private static final Log log = LogFactory.getLog(FileRecordStore.class); // The name of the database file private static final String DB_FILE = "fileRecord.sqlite"; // SQL Table/column names private static final String TABLE_NAME = "records"; // String private static final String PATH_COL = "path"; // byte[] private static final String MD5_COL = "md5"; // long private static final String INODE_COL = "inode"; // short private static final String ATTR_TYPE_COL = "attr_type"; private static final String ATTR_ID_COL = "attr_id"; // byte private static final String NAME_TYPE_COL = "name_type"; private static final String META_TYPE_COL = "meta_type"; // int private static final String PERM_COL = "perms"; private static final String UID_COL = "uid"; private static final String GID_COL = "gid"; // long private static final String SIZE_COL = "size"; // int private static final String ATIME_COL = "atime"; private static final String MTIME_COL = "mtime"; private static final String CTIME_COL = "ctime"; private static final String CRTIME_COL = "crtime"; // Table creation SQL statement private static final String CREATE_STATEMENT = "CREATE TABLE "+TABLE_NAME+" ("+ PATH_COL+" STRING, "+ MD5_COL+" BLOB, "+ INODE_COL+" INTEGER, "+ ATTR_TYPE_COL+" INTEGER, "+ ATTR_ID_COL+" INTEGER, "+ NAME_TYPE_COL+" INTEGER, "+ META_TYPE_COL+" INTEGER, "+ PERM_COL+" INTEGER, "+ UID_COL+" INTEGER, "+ GID_COL+" INTEGER, "+ SIZE_COL+" INTEGER, "+ ATIME_COL+" INTEGER, "+ MTIME_COL+" INTEGER, "+ CTIME_COL+" INTEGER, "+ CRTIME_COL+" INTEGER"+ ")"; // Insert SQL statment private static final String INSERT_STATEMENT = "INSERT INTO "+TABLE_NAME+" ("+ PATH_COL+", "+MD5_COL+", "+INODE_COL+", "+ ATTR_TYPE_COL+", "+ ATTR_ID_COL+", "+NAME_TYPE_COL+", "+META_TYPE_COL+", "+PERM_COL+", "+ UID_COL+", "+GID_COL+", "+SIZE_COL+", "+ATIME_COL+", "+MTIME_COL+", " +CTIME_COL+", "+CRTIME_COL+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // Count the number of hash statement private static final String COUNT_HASH_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME+" WHERE "+MD5_COL+" = ?"; // This needs a ? added for each value and then needs to have a closing ) private static final String COUNT_HASH_IN_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME+" WHERE "+MD5_COL+" IN ("; // Count all rows statement private static final String COUNT_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME; // Select statement private static final String SELECT_RECORD_BY_HASH = "SELECT * FROM "+TABLE_NAME+" WHERE "+MD5_COL+" = ?"; // Select from multiple hashes // This needs a ? added for each potential hash, and a closing ) private static final String SELECT_RECORD_BY_HASHES = "SELECT * FROM "+TABLE_NAME+" WHERE "+MD5_COL+" IN ("; // The constructor for Record objects private static Constructor<Record> recordConstructor; private File sqlFile; private ManagedDiskDescriptor mdd; private Connection connection; /** * Create a new FileHashStore that saves the data in the dataDir folder * for the ManagedDiskDescriptor * @param dataDir * @param mdd * @throws Exception */ public FileRecordStore(File dataDir, ManagedDiskDescriptor mdd) throws IOException{ try{ this.mdd = mdd; log.info("FileHashStore for "+mdd); // Get the file name sqlFile = new File(dataDir, DB_FILE); // If the file doesn't already exist, set up the tables boolean setup = !sqlFile.exists(); // Open a connection connection = DriverManager.getConnection(JDBC.PREFIX + sqlFile.getAbsolutePath()); if(setup){ init(); } } catch(SQLException e){ throw new IOException(e); } } /** * Check if there is any stored data at all * @return * @throws Exception */ public boolean hasData() throws IOException { try{ PreparedStatement count = connection.prepareStatement(COUNT_STATEMENT); ResultSet result = count.executeQuery(); return result.getInt(1) > 0; } catch(SQLException e){ throw new IOException(e); } } /** * Add all the hashes in the (Filename, hash) map to the database * @param hashes */ public void addRecords(List<Record> records) throws IOException { log.debug("Adding file records for disk "+mdd); // Add everything for(Record cur : records){ addRecord(cur); } } /** * Checks if the provided hash is contained in the store * @param hash * @return */ public boolean containsFileHash(byte[] hash) throws IOException { try{ PreparedStatement query = connection.prepareStatement(COUNT_HASH_STATEMENT); query.setBytes(1, hash); ResultSet result = query.executeQuery(); // If the count is != 0, the hash is in there return result.getInt(1) != 0; } catch(SQLException e){ throw new IOException(e); } } /** * Check if any of the provided hashes are contained in the store * @param hashes * @return * @throws IOException */ public boolean containsFileHash(List<byte[]> hashes) throws IOException { if (hashes == null || hashes.isEmpty()) { throw new IllegalArgumentException("Array must not be empty"); } // For a single hash, use the search for one hash method because it // could be faster if (hashes.size() == 1) { return containsFileHash(hashes.get(0)); } try { // The query string needs to be built StringBuilder queryBuilder = new StringBuilder(COUNT_HASH_IN_STATEMENT); for (int i = 0; i < (hashes.size() - 1); i++) { queryBuilder.append("?, "); } // Now, add the last ? and close the parentheses queryBuilder.append("?)"); // Now, build the statement PreparedStatement query = connection.prepareStatement(queryBuilder.toString()); // The prepared statement setXXXX() methods start with 1 for (int i = 1; i <= hashes.size(); i++) { query.setBytes(i, hashes.get(i - 1)); } // Run the query ResultSet result = query.executeQuery(); return result.getInt(1) != 0; } catch (SQLException e) { throw new IOException(e); } } /** * Insert a {@link Record} to the database * @param record * @throws SQLException */ public void addRecord(Record record) throws IOException { /* PATH_COL+" STRING, "+ MD5_COL+" BLOB, "+ INODE_COL+" INTEGER, "+ ATTR_TYPE_COL+" INTEGER, "+ ATTR_ID_COL+" INTEGER, "+ NAME_TYPE_COL+" INTEGER, "+ META_TYPE_COL+" INTEGER, "+ PERM_COL+" INTEGER, "+ UID_COL+" INTEGER, "+ GID_COL+" INTEGER, "+ SIZE_COL+" INTEGER, "+ ATIME_COL+" INTEGER, "+ MTIME_COL+" INTEGER, "+ CTIME_COL+" INTEGER, "+ CRTIME_COL+" INTEGER"+ */ try{ PreparedStatement insert = connection.prepareStatement(INSERT_STATEMENT); insert.setString(1, record.path); insert.setBytes(2, record.md5); insert.setLong(3, record.inode); insert.setShort(4, record.attrType); insert.setShort(5, record.attrId); insert.setByte(6, record.nameType); insert.setByte(7, record.metaType); insert.setInt(8, record.perms); insert.setInt(9, record.uid); insert.setInt(10, record.gid); insert.setLong(11, record.size); insert.setInt(12, record.atime); insert.setInt(13, record.mtime); insert.setInt(14, record.ctime); insert.setInt(15, record.crtime); insert.execute(); } catch(SQLException e){ throw new IOException(e); } } /** * Get the list of {@link Record} objects with a matching MD5 hash * @param hash the MD5 hash * @return the list of records * @throws IOException */ public List<Record> getRecordsFromHash(byte[] hash) throws IOException { try { // Prep the query PreparedStatement query = connection.prepareStatement(SELECT_RECORD_BY_HASH); query.setBytes(1, hash); // Run the query ResultSet result = query.executeQuery(); // Get the results out List<Record> records = new LinkedList<Record>(); while (result.next()) { records.add(getRecordFromResult(result)); } return records; } catch (SQLException e) { throw new IOException(e); } } /** * Get the list of {@link Record} objects with a matching MD5 hash * @param hash the MD5 hash * @return the list of records * @throws IOException */ public List<Record> getRecordsFromHashes(List<byte[]> hashes) throws IOException { try { // Use the single lookup method for a single hash if (hashes.size() == 1) { return getRecordsFromHash(hashes.get(0)); } // Build the query string StringBuilder queryBuilder = new StringBuilder(SELECT_RECORD_BY_HASHES); for (int i = 0; i < (hashes.size() - 1); i++) { queryBuilder.append("?, "); } // Close off the query // The last ? gets added here queryBuilder.append("?)"); // Prep the query PreparedStatement query = connection.prepareStatement(queryBuilder.toString()); for (int i = 1; i <= hashes.size(); i++) { query.setBytes(i, hashes.get(i - 1)); } // Run the query ResultSet result = query.executeQuery(); // Get the results out List<Record> records = new LinkedList<Record>(); while (result.next()) { records.add(getRecordFromResult(result)); } return records; } catch (SQLException e) { throw new IOException(e); } } /** * Creates a Record object from the current row of a ResultSet * @param result * @return */ @SuppressWarnings("unchecked") private Record getRecordFromResult(ResultSet result) throws SQLException { String path = result.getString(PATH_COL); byte[] hash = result.getBytes(MD5_COL); long inode = result.getLong(INODE_COL); int attrType = result.getInt(ATTR_TYPE_COL); int attrId = result.getInt(ATTR_ID_COL); int nameType = result.getInt(NAME_TYPE_COL); int metaType = result.getInt(META_TYPE_COL); int perms = result.getInt(PERM_COL); int uid = result.getInt(UID_COL); int gid = result.getInt(GID_COL); long size = result.getLong(SIZE_COL); int atime = result.getInt(ATIME_COL); int mtime = result.getInt(MTIME_COL); int ctime = result.getInt(CTIME_COL); int crtime = result.getInt(CRTIME_COL); // Check the constructor if (recordConstructor == null) { recordConstructor = (Constructor<Record>) Record.class.getDeclaredConstructors()[0]; recordConstructor.setAccessible(true); } try { // Try and create the record object return recordConstructor.newInstance(hash, path, inode, attrType, attrId, nameType, metaType, perms, uid, gid, size, atime, mtime, ctime, crtime); } catch (Exception e) { log.error("Exception re-creating record from result", e); return null; } } /** * Run initial setup * @throws SQLException */ private void init() throws SQLException { log.debug("Initializing database for managed disk "+mdd); Statement statement = connection.createStatement(); statement.executeUpdate(CREATE_STATEMENT); } @Override public void close() throws IOException { try { connection.close(); } catch (SQLException e) { throw new IOException(e); } } }
store/filesys/src/main/java/edu/uw/apl/tupelo/store/filesys/FileRecordStore.java
/** * Copyright ยฉ 2015, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of the University of Washington nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * 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 UNIVERSITY OF * WASHINGTON 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. */ package edu.uw.apl.tupelo.store.filesys; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.lang.reflect.Constructor; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sqlite.JDBC; import edu.uw.apl.commons.tsk4j.digests.BodyFile.Record; import edu.uw.apl.tupelo.model.ManagedDiskDescriptor; /** * A store for keeping a disk's file {@link Record} information. <br> * The implementation uses a SQLite database */ public class FileRecordStore implements Closeable { private static final Log log = LogFactory.getLog(FileRecordStore.class); // The name of the database file private static final String DB_FILE = "fileHash.sqlite"; // SQL Table/column names private static final String TABLE_NAME = "records"; // String private static final String PATH_COL = "path"; // byte[] private static final String MD5_COL = "md5"; // long private static final String INODE_COL = "inode"; // short private static final String ATTR_TYPE_COL = "attr_type"; private static final String ATTR_ID_COL = "attr_id"; // byte private static final String NAME_TYPE_COL = "name_type"; private static final String META_TYPE_COL = "meta_type"; // int private static final String PERM_COL = "perms"; private static final String UID_COL = "uid"; private static final String GID_COL = "gid"; // long private static final String SIZE_COL = "size"; // int private static final String ATIME_COL = "atime"; private static final String MTIME_COL = "mtime"; private static final String CTIME_COL = "ctime"; private static final String CRTIME_COL = "crtime"; // Table creation SQL statement private static final String CREATE_STATEMENT = "CREATE TABLE "+TABLE_NAME+" ("+ PATH_COL+" STRING, "+ MD5_COL+" BLOB, "+ INODE_COL+" INTEGER, "+ ATTR_TYPE_COL+" INTEGER, "+ ATTR_ID_COL+" INTEGER, "+ NAME_TYPE_COL+" INTEGER, "+ META_TYPE_COL+" INTEGER, "+ PERM_COL+" INTEGER, "+ UID_COL+" INTEGER, "+ GID_COL+" INTEGER, "+ SIZE_COL+" INTEGER, "+ ATIME_COL+" INTEGER, "+ MTIME_COL+" INTEGER, "+ CTIME_COL+" INTEGER, "+ CRTIME_COL+" INTEGER"+ ")"; // Insert SQL statment private static final String INSERT_STATEMENT = "INSERT INTO "+TABLE_NAME+" ("+ PATH_COL+", "+MD5_COL+", "+INODE_COL+", "+ ATTR_TYPE_COL+", "+ ATTR_ID_COL+", "+NAME_TYPE_COL+", "+META_TYPE_COL+", "+PERM_COL+", "+ UID_COL+", "+GID_COL+", "+SIZE_COL+", "+ATIME_COL+", "+MTIME_COL+", " +CTIME_COL+", "+CRTIME_COL+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; // Count the number of hash statement private static final String COUNT_HASH_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME+" WHERE "+MD5_COL+" = ?"; // This needs a ? added for each value and then needs to have a closing ) private static final String COUNT_HASH_IN_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME+" WHERE "+MD5_COL+" IN ("; // Count all rows statement private static final String COUNT_STATEMENT = "SELECT COUNT(*) FROM "+TABLE_NAME; // Select statement private static final String SELECT_RECORD_BY_HASH = "SELECT * FROM "+TABLE_NAME+" WHERE "+MD5_COL+" = ?"; // Select from multiple hashes // This needs a ? added for each potential hash, and a closing ) private static final String SELECT_RECORD_BY_HASHES = "SELECT * FROM "+TABLE_NAME+" WHERE "+MD5_COL+" IN ("; // The constructor for Record objects private static Constructor<Record> recordConstructor; private File sqlFile; private ManagedDiskDescriptor mdd; private Connection connection; /** * Create a new FileHashStore that saves the data in the dataDir folder * for the ManagedDiskDescriptor * @param dataDir * @param mdd * @throws Exception */ public FileRecordStore(File dataDir, ManagedDiskDescriptor mdd) throws IOException{ try{ this.mdd = mdd; log.info("FileHashStore for "+mdd); // Get the file name sqlFile = new File(dataDir, DB_FILE); // If the file doesn't already exist, set up the tables boolean setup = !sqlFile.exists(); // Open a connection connection = DriverManager.getConnection(JDBC.PREFIX + sqlFile.getAbsolutePath()); if(setup){ init(); } } catch(SQLException e){ throw new IOException(e); } } /** * Check if there is any stored data at all * @return * @throws Exception */ public boolean hasData() throws IOException { try{ PreparedStatement count = connection.prepareStatement(COUNT_STATEMENT); ResultSet result = count.executeQuery(); return result.getInt(1) > 0; } catch(SQLException e){ throw new IOException(e); } } /** * Add all the hashes in the (Filename, hash) map to the database * @param hashes */ public void addRecords(List<Record> records) throws IOException { log.debug("Adding file records for disk "+mdd); // Add everything for(Record cur : records){ addRecord(cur); } } /** * Checks if the provided hash is contained in the store * @param hash * @return */ public boolean containsFileHash(byte[] hash) throws IOException { try{ PreparedStatement query = connection.prepareStatement(COUNT_HASH_STATEMENT); query.setBytes(1, hash); ResultSet result = query.executeQuery(); // If the count is != 0, the hash is in there return result.getInt(1) != 0; } catch(SQLException e){ throw new IOException(e); } } /** * Check if any of the provided hashes are contained in the store * @param hashes * @return * @throws IOException */ public boolean containsFileHash(List<byte[]> hashes) throws IOException { if (hashes == null || hashes.isEmpty()) { throw new IllegalArgumentException("Array must not be empty"); } // For a single hash, use the search for one hash method because it // could be faster if (hashes.size() == 1) { return containsFileHash(hashes.get(0)); } try { // The query string needs to be built StringBuilder queryBuilder = new StringBuilder(COUNT_HASH_IN_STATEMENT); for (int i = 0; i < (hashes.size() - 1); i++) { queryBuilder.append("?, "); } // Now, add the last ? and close the parentheses queryBuilder.append("?)"); // Now, build the statement PreparedStatement query = connection.prepareStatement(queryBuilder.toString()); // The prepared statement setXXXX() methods start with 1 for (int i = 1; i <= hashes.size(); i++) { query.setBytes(i, hashes.get(i - 1)); } // Run the query ResultSet result = query.executeQuery(); return result.getInt(1) != 0; } catch (SQLException e) { throw new IOException(e); } } /** * Insert a {@link Record} to the database * @param record * @throws SQLException */ public void addRecord(Record record) throws IOException { /* PATH_COL+" STRING, "+ MD5_COL+" BLOB, "+ INODE_COL+" INTEGER, "+ ATTR_TYPE_COL+" INTEGER, "+ ATTR_ID_COL+" INTEGER, "+ NAME_TYPE_COL+" INTEGER, "+ META_TYPE_COL+" INTEGER, "+ PERM_COL+" INTEGER, "+ UID_COL+" INTEGER, "+ GID_COL+" INTEGER, "+ SIZE_COL+" INTEGER, "+ ATIME_COL+" INTEGER, "+ MTIME_COL+" INTEGER, "+ CTIME_COL+" INTEGER, "+ CRTIME_COL+" INTEGER"+ */ try{ PreparedStatement insert = connection.prepareStatement(INSERT_STATEMENT); insert.setString(1, record.path); insert.setBytes(2, record.md5); insert.setLong(3, record.inode); insert.setShort(4, record.attrType); insert.setShort(5, record.attrId); insert.setByte(6, record.nameType); insert.setByte(7, record.metaType); insert.setInt(8, record.perms); insert.setInt(9, record.uid); insert.setInt(10, record.gid); insert.setLong(11, record.size); insert.setInt(12, record.atime); insert.setInt(13, record.mtime); insert.setInt(14, record.ctime); insert.setInt(15, record.crtime); insert.execute(); } catch(SQLException e){ throw new IOException(e); } } /** * Get the list of {@link Record} objects with a matching MD5 hash * @param hash the MD5 hash * @return the list of records * @throws IOException */ public List<Record> getRecordsFromHash(byte[] hash) throws IOException { try { // Prep the query PreparedStatement query = connection.prepareStatement(SELECT_RECORD_BY_HASH); query.setBytes(1, hash); // Run the query ResultSet result = query.executeQuery(); // Get the results out List<Record> records = new LinkedList<Record>(); while (result.next()) { records.add(getRecordFromResult(result)); } return records; } catch (SQLException e) { throw new IOException(e); } } /** * Get the list of {@link Record} objects with a matching MD5 hash * @param hash the MD5 hash * @return the list of records * @throws IOException */ public List<Record> getRecordsFromHashes(List<byte[]> hashes) throws IOException { try { // Use the single lookup method for a single hash if (hashes.size() == 1) { return getRecordsFromHash(hashes.get(0)); } // Build the query string StringBuilder queryBuilder = new StringBuilder(SELECT_RECORD_BY_HASHES); for (int i = 0; i < (hashes.size() - 1); i++) { queryBuilder.append("?, "); } // Close off the query // The last ? gets added here queryBuilder.append("?)"); // Prep the query PreparedStatement query = connection.prepareStatement(queryBuilder.toString()); for (int i = 1; i <= hashes.size(); i++) { query.setBytes(i, hashes.get(i - 1)); } // Run the query ResultSet result = query.executeQuery(); // Get the results out List<Record> records = new LinkedList<Record>(); while (result.next()) { records.add(getRecordFromResult(result)); } return records; } catch (SQLException e) { throw new IOException(e); } } /** * Creates a Record object from the current row of a ResultSet * @param result * @return */ @SuppressWarnings("unchecked") private Record getRecordFromResult(ResultSet result) throws SQLException { String path = result.getString(PATH_COL); byte[] hash = result.getBytes(MD5_COL); long inode = result.getLong(INODE_COL); int attrType = result.getInt(ATTR_TYPE_COL); int attrId = result.getInt(ATTR_ID_COL); int nameType = result.getInt(NAME_TYPE_COL); int metaType = result.getInt(META_TYPE_COL); int perms = result.getInt(PERM_COL); int uid = result.getInt(UID_COL); int gid = result.getInt(GID_COL); long size = result.getLong(SIZE_COL); int atime = result.getInt(ATIME_COL); int mtime = result.getInt(MTIME_COL); int ctime = result.getInt(CTIME_COL); int crtime = result.getInt(CRTIME_COL); // Check the constructor if (recordConstructor == null) { recordConstructor = (Constructor<Record>) Record.class.getDeclaredConstructors()[0]; recordConstructor.setAccessible(true); } try { // Try and create the record object return recordConstructor.newInstance(hash, path, inode, attrType, attrId, nameType, metaType, perms, uid, gid, size, atime, mtime, ctime, crtime); } catch (Exception e) { log.error("Exception re-creating record from result", e); return null; } } /** * Run initial setup * @throws SQLException */ private void init() throws SQLException { log.debug("Initializing database for managed disk "+mdd); Statement statement = connection.createStatement(); statement.executeUpdate(CREATE_STATEMENT); } @Override public void close() throws IOException { try { connection.close(); } catch (SQLException e) { throw new IOException(e); } } }
Rename fileHash.sqlite to fileRecord.sqlite
store/filesys/src/main/java/edu/uw/apl/tupelo/store/filesys/FileRecordStore.java
Rename fileHash.sqlite to fileRecord.sqlite
Java
bsd-3-clause
1581dd5ffd9a45019fd457293bf13f22dc67ba7a
0
TitanRobotics2022TEMP/2022-FRC-2013,TitanRobotics/2022-FRC-2013
package org.usfirst.frc2022.subsystems; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.camera.AxisCameraException; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.image.*; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; import edu.wpi.first.wpilibj.image.NIVision.Rect; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc2022.commands.CommandBase; /** * Image processor using NIVision to find the most rectangular of objects in a * scene. Analysis is performed using a CriteriaCollection, among other * techniques. The distance from the target (and which target is being aimed at) * is computed. * * @author FRC, FRC Team #2022 * @param ip String of the camera's IP address * @return * */ public class Robocam extends Subsystem{ private AxisCamera camera; //camera instance private CriteriaCollection collection; //criteria for analyzing image private final int X_IMAGE_RES = 640; //X Image resolution in pixels, should be 160, 320 or 640 private double angle = CommandBase.camServos.getRotateAngle(); final int XMAXSIZE = 24; final int XMINSIZE = 24; final int YMAXSIZE = 24; final int YMINSIZE = 48; final double xMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double xMin[] = {.4, .6, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, 0.6, 0}; final double yMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double yMin[] = {.4, .6, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .6, 0}; final int RECTANGULARITY_LIMIT = 60; final int ASPECT_RATIO_LIMIT = 75; final int X_EDGE_LIMIT = 40; final int Y_EDGE_LIMIT = 60; /** * Creates a new Robocam instance * * @param ip String of the camera's IP address * @return */ public Robocam(String ip) { camera = AxisCamera.getInstance(ip); collection = new CriteriaCollection(); collection.addCriteria(MeasurementType.IMAQ_MT_AREA, 500, 65535, false); } protected void initDefaultCommand() { } /** * Struct-style class containing variables required for various computations */ public class Scores { double rectangularity; double aspectRatioInner; double aspectRatioOuter; double xEdge; double yEdge; } /** * Computes a score (0-100) estimating how rectangular the particle is by comparing the area of the particle * to the area of the bounding box surrounding it. A perfect rectangle would cover the entire bounding box. * * @param report The Particle Analysis Report for the particle to score * @return The rectangularity score (0-100) */ double scoreRectangularity(ParticleAnalysisReport report){ if(report.boundingRectWidth*report.boundingRectHeight !=0){ return 100*report.particleArea/(report.boundingRectWidth*report.boundingRectHeight); } else { return 0; } } /** * Computes the distance away from the target * * @param image The image containing the particle to score * @param report The Particle Analysis Report for the particle * @param particleNumber Particle number in the analysis * @param outer Indicates whether the particle aspect ratio should be compared to the ratio for the inner target or the outer * @return Approximate distance from the target * @throws NIVisionException */ double computeDistance (BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean outer) throws NIVisionException { double rectShort, height; int targetHeight; rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); //using the smaller of the estimated rectangle short side and the bounding rectangle height results in better performance //on skewed rectangles height = Math.min(report.boundingRectHeight, rectShort); targetHeight = outer ? 29 : 21; return X_IMAGE_RES * targetHeight / (height * 12 * 2 * Math.tan(angle*Math.PI/(180*2))); } /** * Computes a score (0-100) comparing the aspect ratio to the ideal aspect ratio for the target. This method uses * the equivalent rectangle sides to determine aspect ratio as it performs better as the target gets skewed by moving * to the left or right. The equivalent rectangle is the rectangle with sides x and y where particle area= x*y * and particle perimeter= 2x+2y * * @param image The image containing the particle to score, needed to perform additional measurements * @param report The Particle Analysis Report for the particle, used for the width, height, and particle number * @param outer Indicates whether the particle aspect ratio should be compared to the ratio for the inner target or the outer * @return The aspect ratio score (0-100) */ public double scoreAspectRatio(BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean outer) throws NIVisionException { double rectLong, rectShort, aspectRatio, idealAspectRatio; rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE); rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); idealAspectRatio = outer ? (62/29) : (62/20); //Dimensions of goal opening + 4 inches on all 4 sides for reflective tape //Divide width by height to measure aspect ratio if(report.boundingRectWidth > report.boundingRectHeight){ //particle is wider than it is tall, divide long by short aspectRatio = 100*(1-Math.abs((1-((rectLong/rectShort)/idealAspectRatio)))); } else { //particle is taller than it is wide, divide short by long aspectRatio = 100*(1-Math.abs((1-((rectShort/rectLong)/idealAspectRatio)))); } return (Math.max(0, Math.min(aspectRatio, 100.0))); //force to be in range 0-100 } /** * Compares scores to defined limits and returns true if the particle appears to be a target * * @param scores The structure containing the scores to compare * @param outer True if the particle should be treated as an outer target, false to treat it as a center target * * @return True if the particle meets all limits, false otherwise */ boolean scoreCompare(Scores scores, boolean outer){ boolean isTarget = true; isTarget &= scores.rectangularity > RECTANGULARITY_LIMIT; if(outer){ isTarget &= scores.aspectRatioOuter > ASPECT_RATIO_LIMIT; } else { isTarget &= scores.aspectRatioInner > ASPECT_RATIO_LIMIT; } isTarget &= scores.xEdge > X_EDGE_LIMIT; isTarget &= scores.yEdge > Y_EDGE_LIMIT; return isTarget; } /** * Computes a score based on the match between a template profile and the particle profile in the X direction. This method uses the * the column averages and the profile defined at the top of the sample to look for the solid vertical edges with * a hollow center. * * @param image The image to use, should be the image before the convex hull is performed * @param report The Particle Analysis Report for the particle * * @return The X Edge Score (0-100) */ public double scoreXEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; Rect rect = new Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_COLUMN_AVERAGES, rect); float columnAverages[] = averages.getColumnAverages(); for(int i=0; i < (columnAverages.length); i++){ if(xMin[(i*(XMINSIZE-1)/columnAverages.length)] < columnAverages[i] && columnAverages[i] < xMax[i*(XMAXSIZE-1)/columnAverages.length]){ total++; } } total = 100*total/(columnAverages.length); return total; } /** * Computes a score based on the match between a template profile and the particle profile in the Y direction. This method uses the * the row averages and the profile defined at the top of the sample to look for the solid horizontal edges with * a hollow center * * @param image The image to use, should be the image before the convex hull is performed * @param report The Particle Analysis Report for the particle * * @return The Y Edge score (0-100) * */ public double scoreYEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; Rect rect = new Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_ROW_AVERAGES, rect); float rowAverages[] = averages.getRowAverages(); for(int i=0; i < (rowAverages.length); i++){ if(yMin[(i*(YMINSIZE-1)/rowAverages.length)] < rowAverages[i] && rowAverages[i] < yMax[i*(YMAXSIZE-1)/rowAverages.length]){ total++; } } total = 100*total/(rowAverages.length); return total; } /** * Analyzes an image taken by the Axis Camera, performing various functions * to determine where the goal is and at what goal the robot is facing * * @param * @return Array of doubles where the first value is the type of goal * (2.0 high, 1.0 middle, 0.0 no goal), the x-centered-normalized value, * the y-centered-normalized value and the distance. If the distance is negative, * no goal was found. * */ public double[] analyze() { double[] data = new double[3]; //[goal type, x-centered, y-centered, distance] try { ColorImage image = camera.getImage(); //Get image from camera BinaryImage thresholdImage; thresholdImage = image.thresholdHSV(120, 120, 44, 80, 98, 100); //"Look" for objects in this HSV range BinaryImage convexHullImage = thresholdImage.convexHull(false); // Fill in occluded rectangles BinaryImage filteredImage = convexHullImage.particleFilter(collection); // Find filled in rectangles Scores scores[] = new Scores[filteredImage.getNumberParticles()]; for (int i = 0; i < scores.length; i++) { ParticleAnalysisReport report = filteredImage.getParticleAnalysisReport(i); //Get the report for each particle found scores[i] = new Scores(); scores[i].rectangularity = scoreRectangularity(report); scores[i].aspectRatioOuter = scoreAspectRatio(filteredImage, report, i, true); scores[i].aspectRatioInner = scoreAspectRatio(filteredImage, report, i, false); scores[i].xEdge = scoreXEdge(thresholdImage, report); scores[i].yEdge = scoreYEdge(thresholdImage, report); if (scoreCompare(scores[i], false)){ double dist = computeDistance(thresholdImage, report, i, false); System.out.println("particle: " + i + " is a High Goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); System.out.println("Distance: " + dist); data[0] = 2.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = dist; } else if (scoreCompare(scores[i], true)){ double dist = computeDistance(thresholdImage, report, i, false); System.out.println("particle: " + i + " is a Middle Goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); System.out.println("Distance: " + dist); data[0] = 1.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = dist; } else { System.out.println("particle: " + i + " is not a goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); data[0] = 0.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = -1.0; } System.out.println("rect: " + scores[i].rectangularity + "ARinner: " + scores[i].aspectRatioInner); System.out.println("ARouter: " + scores[i].aspectRatioOuter + "xEdge: " + scores[i].xEdge + "yEdge: " + scores[i].yEdge); } /* MUST USE FREE FUNCTION: all images are currently allocated in C structures */ filteredImage.free(); convexHullImage.free(); thresholdImage.free(); image.free(); } //end analyze() catch (AxisCameraException e) { data[0] = 0.0; data[1] = 0.0; data[2] = 0.0; data[3] = -1.0; SmartDashboard.putString("ERROR: ", "Camera malfunction!"); } catch (NIVisionException ex) { data[0] = 0.0; data[1] = 0.0; data[2] = 0.0; data[3] = -1.0; SmartDashboard.putString("ERROR: ", "NIVision Exception!"); } return data; } }
src/org/usfirst/frc2022/subsystems/Robocam.java
package org.usfirst.frc2022.subsystems; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.camera.AxisCameraException; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.image.*; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; import edu.wpi.first.wpilibj.image.NIVision.Rect; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import org.usfirst.frc2022.commands.CommandBase; /** * Image processor using NIVision to find the most rectangular of objects in a * scene. Analysis is performed using a CriteriaCollection, among other * techniques. The distance from the target (and which target is being aimed at) * is computed. * * Modified from original post on * http://www.chiefdelphi.com/forums/showthread.php?t=109657 * * @author FRC, FRC Team #2022 * @param ip String of the camera's IP address * @return * */ public class Robocam extends Subsystem{ private AxisCamera camera; //camera instance private CriteriaCollection collection; //criteria for analyzing image private final int X_IMAGE_RES = 640; //X Image resolution in pixels, should be 160, 320 or 640 private double angle = CommandBase.camServos.getRotateAngle(); final int XMAXSIZE = 24; final int XMINSIZE = 24; final int YMAXSIZE = 24; final int YMINSIZE = 48; final double xMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double xMin[] = {.4, .6, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, .1, 0.6, 0}; final double yMax[] = {1, 1, 1, 1, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, .5, 1, 1, 1, 1}; final double yMin[] = {.4, .6, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .05, .6, 0}; final int RECTANGULARITY_LIMIT = 60; final int ASPECT_RATIO_LIMIT = 75; final int X_EDGE_LIMIT = 40; final int Y_EDGE_LIMIT = 60; /** * Creates a new Robocam instance * * @param ip String of the camera's IP address * @return */ public Robocam(String ip) { camera = AxisCamera.getInstance(ip); collection = new CriteriaCollection(); collection.addCriteria(MeasurementType.IMAQ_MT_AREA, 500, 65535, false); } protected void initDefaultCommand() { } /** * Struct-style class containing variables required for various computations */ public class Scores { double rectangularity; double aspectRatioInner; double aspectRatioOuter; double xEdge; double yEdge; } /** * Computes a score (0-100) estimating how rectangular the particle is by comparing the area of the particle * to the area of the bounding box surrounding it. A perfect rectangle would cover the entire bounding box. * * @param report The Particle Analysis Report for the particle to score * @return The rectangularity score (0-100) */ double scoreRectangularity(ParticleAnalysisReport report){ if(report.boundingRectWidth*report.boundingRectHeight !=0){ return 100*report.particleArea/(report.boundingRectWidth*report.boundingRectHeight); } else { return 0; } } /** * Computes the distance away from the target * * @param image The image containing the particle to score * @param report The Particle Analysis Report for the particle * @param particleNumber Particle number in the analysis * @param outer Indicates whether the particle aspect ratio should be compared to the ratio for the inner target or the outer * @return Approximate distance from the target * @throws NIVisionException */ double computeDistance (BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean outer) throws NIVisionException { double rectShort, height; int targetHeight; rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); //using the smaller of the estimated rectangle short side and the bounding rectangle height results in better performance //on skewed rectangles height = Math.min(report.boundingRectHeight, rectShort); targetHeight = outer ? 29 : 21; return X_IMAGE_RES * targetHeight / (height * 12 * 2 * Math.tan(angle*Math.PI/(180*2))); } /** * Computes a score (0-100) comparing the aspect ratio to the ideal aspect ratio for the target. This method uses * the equivalent rectangle sides to determine aspect ratio as it performs better as the target gets skewed by moving * to the left or right. The equivalent rectangle is the rectangle with sides x and y where particle area= x*y * and particle perimeter= 2x+2y * * @param image The image containing the particle to score, needed to perform additional measurements * @param report The Particle Analysis Report for the particle, used for the width, height, and particle number * @param outer Indicates whether the particle aspect ratio should be compared to the ratio for the inner target or the outer * @return The aspect ratio score (0-100) */ public double scoreAspectRatio(BinaryImage image, ParticleAnalysisReport report, int particleNumber, boolean outer) throws NIVisionException { double rectLong, rectShort, aspectRatio, idealAspectRatio; rectLong = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE); rectShort = NIVision.MeasureParticle(image.image, particleNumber, false, MeasurementType.IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE); idealAspectRatio = outer ? (62/29) : (62/20); //Dimensions of goal opening + 4 inches on all 4 sides for reflective tape //Divide width by height to measure aspect ratio if(report.boundingRectWidth > report.boundingRectHeight){ //particle is wider than it is tall, divide long by short aspectRatio = 100*(1-Math.abs((1-((rectLong/rectShort)/idealAspectRatio)))); } else { //particle is taller than it is wide, divide short by long aspectRatio = 100*(1-Math.abs((1-((rectShort/rectLong)/idealAspectRatio)))); } return (Math.max(0, Math.min(aspectRatio, 100.0))); //force to be in range 0-100 } /** * Compares scores to defined limits and returns true if the particle appears to be a target * * @param scores The structure containing the scores to compare * @param outer True if the particle should be treated as an outer target, false to treat it as a center target * * @return True if the particle meets all limits, false otherwise */ boolean scoreCompare(Scores scores, boolean outer){ boolean isTarget = true; isTarget &= scores.rectangularity > RECTANGULARITY_LIMIT; if(outer){ isTarget &= scores.aspectRatioOuter > ASPECT_RATIO_LIMIT; } else { isTarget &= scores.aspectRatioInner > ASPECT_RATIO_LIMIT; } isTarget &= scores.xEdge > X_EDGE_LIMIT; isTarget &= scores.yEdge > Y_EDGE_LIMIT; return isTarget; } /** * Computes a score based on the match between a template profile and the particle profile in the X direction. This method uses the * the column averages and the profile defined at the top of the sample to look for the solid vertical edges with * a hollow center. * * @param image The image to use, should be the image before the convex hull is performed * @param report The Particle Analysis Report for the particle * * @return The X Edge Score (0-100) */ public double scoreXEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; Rect rect = new Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_COLUMN_AVERAGES, rect); float columnAverages[] = averages.getColumnAverages(); for(int i=0; i < (columnAverages.length); i++){ if(xMin[(i*(XMINSIZE-1)/columnAverages.length)] < columnAverages[i] && columnAverages[i] < xMax[i*(XMAXSIZE-1)/columnAverages.length]){ total++; } } total = 100*total/(columnAverages.length); return total; } /** * Computes a score based on the match between a template profile and the particle profile in the Y direction. This method uses the * the row averages and the profile defined at the top of the sample to look for the solid horizontal edges with * a hollow center * * @param image The image to use, should be the image before the convex hull is performed * @param report The Particle Analysis Report for the particle * * @return The Y Edge score (0-100) * */ public double scoreYEdge(BinaryImage image, ParticleAnalysisReport report) throws NIVisionException { double total = 0; LinearAverages averages; Rect rect = new Rect(report.boundingRectTop, report.boundingRectLeft, report.boundingRectHeight, report.boundingRectWidth); averages = NIVision.getLinearAverages(image.image, LinearAverages.LinearAveragesMode.IMAQ_ROW_AVERAGES, rect); float rowAverages[] = averages.getRowAverages(); for(int i=0; i < (rowAverages.length); i++){ if(yMin[(i*(YMINSIZE-1)/rowAverages.length)] < rowAverages[i] && rowAverages[i] < yMax[i*(YMAXSIZE-1)/rowAverages.length]){ total++; } } total = 100*total/(rowAverages.length); return total; } /** * Analyzes an image taken by the Axis Camera, performing various functions * to determine where the goal is and at what goal the robot is facing * * @param * @return Array of doubles where the first value is the type of goal * (2.0 high, 1.0 middle, 0.0 no goal), the x-centered-normalized value, * the y-centered-normalized value and the distance. If the distance is negative, * no goal was found. * */ public double[] analyze() { double[] data = new double[3]; //[goal type, x-centered, y-centered, distance] try { ColorImage image = camera.getImage(); //Get image from camera BinaryImage thresholdImage; thresholdImage = image.thresholdHSV(120, 120, 44, 80, 98, 100); //"Look" for objects in this HSV range BinaryImage convexHullImage = thresholdImage.convexHull(false); // Fill in occluded rectangles BinaryImage filteredImage = convexHullImage.particleFilter(collection); // Find filled in rectangles Scores scores[] = new Scores[filteredImage.getNumberParticles()]; for (int i = 0; i < scores.length; i++) { ParticleAnalysisReport report = filteredImage.getParticleAnalysisReport(i); //Get the report for each particle found scores[i] = new Scores(); scores[i].rectangularity = scoreRectangularity(report); scores[i].aspectRatioOuter = scoreAspectRatio(filteredImage, report, i, true); scores[i].aspectRatioInner = scoreAspectRatio(filteredImage, report, i, false); scores[i].xEdge = scoreXEdge(thresholdImage, report); scores[i].yEdge = scoreYEdge(thresholdImage, report); if (scoreCompare(scores[i], false)){ double dist = computeDistance(thresholdImage, report, i, false); System.out.println("particle: " + i + "is a High Goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); System.out.println("Distance: " + dist); data[0] = 2.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = dist; } else if (scoreCompare(scores[i], true)){ double dist = computeDistance(thresholdImage, report, i, false); System.out.println("particle: " + i + "is a Middle Goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); System.out.println("Distance: " + dist); data[0] = 1.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = dist; } else { System.out.println("particle: " + i + "is not a goal centerX: " + report.center_mass_x_normalized + "centerY: " + report.center_mass_y_normalized); data[0] = 0.0; data[1] = report.center_mass_x_normalized; data[2] = report.center_mass_y_normalized; data[3] = -1.0; } System.out.println("rect: " + scores[i].rectangularity + "ARinner: " + scores[i].aspectRatioInner); System.out.println("ARouter: " + scores[i].aspectRatioOuter + "xEdge: " + scores[i].xEdge + "yEdge: " + scores[i].yEdge); } /* MUST USE FREE FUNCTION: all images are currently allocated in C structures */ filteredImage.free(); convexHullImage.free(); thresholdImage.free(); image.free(); } //end analyze() catch (AxisCameraException e) { data[0] = 0.0; data[1] = 0.0; data[2] = 0.0; data[3] = -1.0; SmartDashboard.putString("ERROR: ", "Camera malfunction!"); } catch (NIVisionException ex) { data[0] = 0.0; data[1] = 0.0; data[2] = 0.0; data[3] = -1.0; SmartDashboard.putString("ERROR: ", "NIVision Exception!"); } return data; } }
Quick comment change
src/org/usfirst/frc2022/subsystems/Robocam.java
Quick comment change
Java
mit
e8ad73f2f02a33e985524182f0c3da94b42991b6
0
talah/BBTH
package bbth.game; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import bbth.engine.achievements.Achievements; import bbth.engine.fastgraph.Wall; import bbth.engine.net.bluetooth.Bluetooth; import bbth.engine.net.bluetooth.State; import bbth.engine.net.simulation.LockStepProtocol; import bbth.engine.particles.ParticleSystem; import bbth.engine.sound.Beat.BeatType; import bbth.engine.sound.MusicPlayer; import bbth.engine.sound.MusicPlayer.OnCompletionListener; import bbth.engine.ui.Anchor; import bbth.engine.ui.UINavigationController; import bbth.engine.ui.UIView; import bbth.engine.util.Timer; import bbth.game.BBTHSimulation.GameState; import bbth.game.ai.PlayerAI; public class InGameScreen extends UIView implements OnCompletionListener { private BBTHSimulation sim; private Bluetooth bluetooth; private Team team; private BeatTrack beatTrack; private Wall currentWall; private ParticleSystem particles; private Paint paint; private static final boolean USE_UNIT_SELECTOR = false; private static final long TAP_HINT_DISPLAY_LENGTH = 3000; private static final long PLACEMENT_HINT_DISPLAY_LENGTH = 3000; private static final long DRAG_HINT_DISPLAY_LENGTH = 3000; private static final boolean USE_PAGINATED_TUTORIAL = false; // Timers for profiling while debugging private Timer entireUpdateTimer = new Timer(); private Timer simUpdateTimer = new Timer(); private Timer entireDrawTimer = new Timer(); private Timer drawParticleTimer = new Timer(); private Timer drawSimTimer = new Timer(); private Timer drawUITimer = new Timer(); private Path arrowPath; public ComboCircle combo_circle; private boolean userScrolling; private Tutorial tutorial; private long tap_location_hint_time; private long drag_tip_start_time; private PlayerAI player_ai; private float secondsUntilNextScreen = 4; private boolean setSong; private boolean gameIsStarted; private boolean countdownStarted; float aiDifficulty; boolean singlePlayer; private UINavigationController controller; public InGameScreen(UINavigationController controller, Team playerTeam, Bluetooth bluetooth, Song song, LockStepProtocol protocol, boolean singlePlayer) { setSize(BBTHGame.WIDTH, BBTHGame.HEIGHT); this.controller = controller; this.singlePlayer = singlePlayer; this.team = playerTeam; aiDifficulty = BBTHGame.AI_DIFFICULTY; if (USE_PAGINATED_TUTORIAL) { tutorial = new PaginatedTutorial(); } else { tutorial = new InteractiveTutorial(playerTeam); } tutorial.setSize(BBTHGame.WIDTH * 0.75f, BBTHGame.HEIGHT / 2.f); tutorial.setAnchor(Anchor.CENTER_CENTER); tutorial.setPosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2.f); paint = new Paint(Paint.ANTI_ALIAS_FLAG); tap_location_hint_time = 0; this.bluetooth = bluetooth; sim = new BBTHSimulation(playerTeam, protocol, team == Team.SERVER, this); BBTHSimulation.PARTICLES.reset(); if (team == Team.SERVER) { if (singlePlayer) { sim.simulateCustomEvent(0, 0, song.id, true); } else { sim.recordCustomEvent(0.f, 0.f, song.id); } // Set up sound stuff beatTrack = new BeatTrack(song, this); setSong = true; } else { beatTrack = new BeatTrack(Song.DERP, this); setSong = false; } paint = new Paint(); paint.setAntiAlias(true); paint.setStrokeWidth(2.0f); paint.setStrokeJoin(Join.ROUND); paint.setTextSize(20); paint.setAntiAlias(true); paint.setTextAlign(Align.CENTER); paint.setStrokeWidth(2.f); particles = new ParticleSystem(200, 0.5f); if (singlePlayer) { player_ai = new PlayerAI(sim, sim.remotePlayer, sim.localPlayer, beatTrack, aiDifficulty); } arrowPath = new Path(); arrowPath.moveTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 55); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 40, BBTHGame.HEIGHT * .75f + 65); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 75); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 70); arrowPath.lineTo(BBTHGame.WIDTH / 2, BBTHGame.HEIGHT * .75f + 70); arrowPath.lineTo(BBTHGame.WIDTH / 2, BBTHGame.HEIGHT * .75f + 60); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 60); arrowPath.close(); } @Override public void onStop() { beatTrack.stopMusic(); // Disconnect when we lose focus bluetooth.disconnect(); if (singlePlayer) { sim.simulateCustomEvent(0, 0, BBTHSimulation.MUSIC_STOPPED_EVENT, true); } Achievements.INSTANCE.commit(); } @Override public void onDraw(Canvas canvas) { if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished() && tutorial.supressDrawing()) { tutorial.onDraw(canvas); return; } entireDrawTimer.start(); // Draw the game drawSimTimer.start(); canvas.save(); canvas.translate(BBTHSimulation.GAME_X, BBTHSimulation.GAME_Y); if (team == Team.SERVER) { canvas.translate(0, BBTHSimulation.GAME_HEIGHT / 2); canvas.scale(1.f, -1.f); canvas.translate(0, -BBTHSimulation.GAME_HEIGHT / 2); } sim.draw(canvas); paint.setColor(team.getTempWallColor()); paint.setStrokeCap(Cap.ROUND); if (currentWall != null) { canvas.drawLine(currentWall.a.x, currentWall.a.y, currentWall.b.x, currentWall.b.y, paint); } paint.setStrokeCap(Cap.BUTT); drawParticleTimer.start(); particles.draw(canvas, paint); drawParticleTimer.stop(); canvas.restore(); drawSimTimer.stop(); drawUITimer.start(); // Overlay the beat track beatTrack.draw(canvas); // Overlay the unit selector if (USE_UNIT_SELECTOR) { sim.getMyUnitSelector().draw(canvas); } drawUITimer.stop(); if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onDraw(canvas); } else if (!sim.isReady()) { paint.setColor(Color.WHITE); paint.setTextSize(20); canvas.drawText("Waiting for other player...", BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2, paint); } else { float countdown = sim.getStartingCountdown(); int number = (int) Math.ceil(countdown); if (number > 0) { float alpha = countdown - (int) countdown; paint.setARGB((int) (alpha * 255), 255, 255, 255); paint.setTextSize(100); canvas.drawText(Integer.toString(number), BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2 + 30, paint); } } float percent = (System.currentTimeMillis() - tap_location_hint_time) / (float)TAP_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setStrokeCap(Cap.ROUND); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Tap further right ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .75f + 20, paint); canvas.drawText("to make units!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .75f + 45, paint); canvas.drawPath(arrowPath, paint); } // Draw unit placement hint if necessary. percent = (System.currentTimeMillis() - sim.placement_tip_start_time) / (float)PLACEMENT_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Tap inside your zone of ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .25f + 20, paint); canvas.drawText("influence to make units!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .25f + 45, paint); } // Draw wall drag hint if necessary. percent = (System.currentTimeMillis() - drag_tip_start_time) / (float)DRAG_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Drag finger further ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .5f + 20, paint); canvas.drawText("to draw a longer wall!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .5f + 45, paint); } if (BBTHGame.DEBUG) { // Draw timing information paint.setColor(Color.argb(63, 255, 255, 255)); paint.setTextSize(8); paint.setStyle(Style.FILL); int x = 80; int y = 30; int jump = 11; canvas.drawText("Entire update: " + entireUpdateTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- Sim update: " + simUpdateTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Sim tick: " + sim.entireTickTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - AI tick: " + sim.aiTickTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Controller: " + sim.aiControllerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Server player: " + sim.serverPlayerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Client player: " + sim.clientPlayerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("Entire draw: " + entireDrawTimer.getMilliseconds() + " ms", x, y += jump * 2, paint); canvas.drawText("- Sim: " + drawSimTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- Particles: " + drawParticleTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- UI: " + drawUITimer.getMilliseconds() + " ms", x, y += jump, paint); } if (!sim.isSynced()) { paint.setColor(Color.RED); paint.setTextSize(40); paint.setTextAlign(Align.CENTER); canvas.drawText("NOT SYNCED!", BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2 + 40, paint); } super.onDraw(canvas); entireDrawTimer.stop(); // draw achievement stuff Achievements.INSTANCE.draw(canvas, BBTHGame.WIDTH, BBTHGame.HEIGHT / 15.f); } @Override public void onUpdate(float seconds) { entireUpdateTimer.start(); if (!setSong && team == Team.CLIENT && sim.song != null) { // Set up sound stuff beatTrack.setSong(sim.song); setSong = true; } if (!singlePlayer) { // Stop the music if we disconnect if (bluetooth.getState() != State.CONNECTED) { beatTrack.stopMusic(); controller.pushUnder(new GameStatusMessageScreen.DisconnectScreen(controller)); controller.pop(); } } // Update the single-player AI if (singlePlayer && sim.getGameState() == GameState.IN_PROGRESS) { player_ai.update(seconds); } // Update the game simUpdateTimer.start(); if (singlePlayer) { sim.update(seconds); } else { sim.onUpdate(seconds); } simUpdateTimer.stop(); // Update the tutorial if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onUpdate(seconds); } else { endTutorial(); } // Start the countdown if (!countdownStarted && sim.getGameState() == GameState.WAITING_TO_START && sim.isReady()) { beatTrack.setStartDelay(3000); countdownStarted = true; } // Start the music if (setSong && sim.getGameState() == GameState.IN_PROGRESS && !beatTrack.isPlaying()) { beatTrack.startMusic(); } // Get new beats, yo beatTrack.refreshBeats(); // Shinies particles.tick(seconds); entireUpdateTimer.stop(); // End the game when the time comes GameState gameState = sim.getGameState(); if (gameState != GameState.WAITING_TO_START && gameState != GameState.IN_PROGRESS) { secondsUntilNextScreen -= seconds; if (secondsUntilNextScreen < 0) { moveToNextScreen(); } } // Update achievement stuff Achievements.INSTANCE.tick(seconds); } private void moveToNextScreen() { beatTrack.stopMusic(); // Move on to the next screen GameState gameState = sim.getGameState(); if (gameState == GameState.TIE) { controller.pushUnder(new GameStatusMessageScreen.TieScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } else if (sim.isServer == (gameState == GameState.SERVER_WON)) { controller.pushUnder(new GameStatusMessageScreen.WinScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } else { controller.pushUnder(new GameStatusMessageScreen.LoseScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } } @Override public void onTouchDown(float x, float y) { // We don't want to interact with the game if the tutorial is running! if ( BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchDown(x, y); return; } if (USE_UNIT_SELECTOR) { int unitType = sim.getMyUnitSelector().checkUnitChange(x, y); if (unitType >= 0) { if (singlePlayer) { sim.simulateCustomEvent(0, 0, unitType, true); } else { sim.recordCustomEvent(0, 0, unitType); } return; } } BeatType beatType = beatTrack.onTouchDown(x, y); boolean isHold = (beatType == BeatType.HOLD); boolean isOnBeat = (beatType != BeatType.REST); x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (x < 0) { // Display a message saying they should tap in-bounds tap_location_hint_time = System.currentTimeMillis(); } if (isOnBeat && isHold && x > 0 && y > 0) { currentWall = new Wall(x, y, x, y); } if (singlePlayer) { sim.simulateTapDown(x, y, true, isHold, isOnBeat); } else { sim.recordTapDown(x, y, isHold, isOnBeat); } } @Override public void onTouchMove(float x, float y) { // We don't want to interact with the game if the tutorial is running! if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchMove(x, y); return; } // We moved offscreen! x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (currentWall != null) { if (x < 0 || y < 0) { simulateWallGeneration(); } else { currentWall.b.set(x, y); } } if (singlePlayer) { sim.simulateTapMove(x, y, true); } else { sim.recordTapMove(x, y); } } @Override public void onTouchUp(float x, float y) { // We don't want to interact with the game if the tutorial is running! if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchUp(x, y); return; } beatTrack.onTouchUp(x, y); if (userScrolling) { userScrolling = false; return; } x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (currentWall != null) { simulateWallGeneration(); } if (singlePlayer) { sim.simulateTapUp(x, y, true); } else { sim.recordTapUp(x, y); } } public void simulateWallGeneration() { currentWall.updateLength(); if (currentWall.length <= BBTHSimulation.MIN_WALL_LENGTH) { // Display a tip about dragging! drag_tip_start_time = System.currentTimeMillis(); } if (currentWall.length >= BBTHSimulation.MIN_WALL_LENGTH) { BBTHSimulation.generateParticlesForWall(currentWall, this.team); } currentWall = null; } /** * Stupid method necessary because of android's weird context/activity mess. */ @Override public void onActivityResult(int requestCode, int resultCode) { bluetooth.onActivityResult(requestCode, resultCode); } @Override public void onCompletion(MusicPlayer mp) { mp.stop(); // End both games at the same time with a synced event if (singlePlayer) { sim.simulateCustomEvent(0, 0, BBTHSimulation.MUSIC_STOPPED_EVENT, true); } else { sim.recordCustomEvent(0, 0, BBTHSimulation.MUSIC_STOPPED_EVENT); } } @Override public void willHide(boolean animated) { super.willHide(animated); beatTrack.stopMusic(); } public void endTutorial() { if (!gameIsStarted) { gameIsStarted = true; removeSubview(tutorial); sim.recordCustomEvent(0, 0, BBTHSimulation.TUTORIAL_DONE_EVENT); if (singlePlayer) sim.setBothPlayersReady(); } } public BeatTrack getBeatTrack() { return beatTrack; } }
gameSrc/bbth/game/InGameScreen.java
package bbth.game; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Cap; import android.graphics.Paint.Join; import android.graphics.Paint.Style; import android.graphics.Path; import bbth.engine.achievements.Achievements; import bbth.engine.fastgraph.Wall; import bbth.engine.net.bluetooth.Bluetooth; import bbth.engine.net.bluetooth.State; import bbth.engine.net.simulation.LockStepProtocol; import bbth.engine.particles.ParticleSystem; import bbth.engine.sound.Beat.BeatType; import bbth.engine.sound.MusicPlayer; import bbth.engine.sound.MusicPlayer.OnCompletionListener; import bbth.engine.ui.Anchor; import bbth.engine.ui.UINavigationController; import bbth.engine.ui.UIView; import bbth.engine.util.Timer; import bbth.game.BBTHSimulation.GameState; import bbth.game.ai.PlayerAI; public class InGameScreen extends UIView implements OnCompletionListener { private BBTHSimulation sim; private Bluetooth bluetooth; private Team team; private BeatTrack beatTrack; private Wall currentWall; private ParticleSystem particles; private Paint paint; private static final boolean USE_UNIT_SELECTOR = false; private static final long TAP_HINT_DISPLAY_LENGTH = 3000; private static final long PLACEMENT_HINT_DISPLAY_LENGTH = 3000; private static final long DRAG_HINT_DISPLAY_LENGTH = 3000; private static final boolean USE_PAGINATED_TUTORIAL = false; // Timers for profiling while debugging private Timer entireUpdateTimer = new Timer(); private Timer simUpdateTimer = new Timer(); private Timer entireDrawTimer = new Timer(); private Timer drawParticleTimer = new Timer(); private Timer drawSimTimer = new Timer(); private Timer drawUITimer = new Timer(); private Path arrowPath; public ComboCircle combo_circle; private boolean userScrolling; private Tutorial tutorial; private long tap_location_hint_time; private long drag_tip_start_time; private PlayerAI player_ai; private float secondsUntilNextScreen = 4; private boolean setSong; private boolean gameIsStarted; private boolean countdownStarted; float aiDifficulty; boolean singlePlayer; private UINavigationController controller; public InGameScreen(UINavigationController controller, Team playerTeam, Bluetooth bluetooth, Song song, LockStepProtocol protocol, boolean singlePlayer) { setSize(BBTHGame.WIDTH, BBTHGame.HEIGHT); this.controller = controller; this.singlePlayer = singlePlayer; this.team = playerTeam; aiDifficulty = BBTHGame.AI_DIFFICULTY; if (USE_PAGINATED_TUTORIAL) { tutorial = new PaginatedTutorial(); } else { tutorial = new InteractiveTutorial(playerTeam); } tutorial.setSize(BBTHGame.WIDTH * 0.75f, BBTHGame.HEIGHT / 2.f); tutorial.setAnchor(Anchor.CENTER_CENTER); tutorial.setPosition(BBTHGame.WIDTH / 2.f, BBTHGame.HEIGHT / 2.f); paint = new Paint(Paint.ANTI_ALIAS_FLAG); tap_location_hint_time = 0; this.bluetooth = bluetooth; sim = new BBTHSimulation(playerTeam, protocol, team == Team.SERVER, this); BBTHSimulation.PARTICLES.reset(); if (team == Team.SERVER) { if (singlePlayer) { sim.simulateCustomEvent(0, 0, song.id, true); } else { sim.recordCustomEvent(0.f, 0.f, song.id); } // Set up sound stuff beatTrack = new BeatTrack(song, this); setSong = true; } else { beatTrack = new BeatTrack(Song.DERP, this); setSong = false; } paint = new Paint(); paint.setAntiAlias(true); paint.setStrokeWidth(2.0f); paint.setStrokeJoin(Join.ROUND); paint.setTextSize(20); paint.setAntiAlias(true); paint.setTextAlign(Align.CENTER); paint.setStrokeWidth(2.f); particles = new ParticleSystem(200, 0.5f); if (singlePlayer) { player_ai = new PlayerAI(sim, sim.remotePlayer, sim.localPlayer, beatTrack, aiDifficulty); } arrowPath = new Path(); arrowPath.moveTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 55); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 40, BBTHGame.HEIGHT * .75f + 65); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 75); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 70); arrowPath.lineTo(BBTHGame.WIDTH / 2, BBTHGame.HEIGHT * .75f + 70); arrowPath.lineTo(BBTHGame.WIDTH / 2, BBTHGame.HEIGHT * .75f + 60); arrowPath.lineTo(BBTHGame.WIDTH / 2 + 30, BBTHGame.HEIGHT * .75f + 60); arrowPath.close(); } @Override public void onStop() { beatTrack.stopMusic(); // Disconnect when we lose focus bluetooth.disconnect(); Achievements.INSTANCE.commit(); } @Override public void onDraw(Canvas canvas) { if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished() && tutorial.supressDrawing()) { tutorial.onDraw(canvas); return; } entireDrawTimer.start(); // Draw the game drawSimTimer.start(); canvas.save(); canvas.translate(BBTHSimulation.GAME_X, BBTHSimulation.GAME_Y); if (team == Team.SERVER) { canvas.translate(0, BBTHSimulation.GAME_HEIGHT / 2); canvas.scale(1.f, -1.f); canvas.translate(0, -BBTHSimulation.GAME_HEIGHT / 2); } sim.draw(canvas); paint.setColor(team.getTempWallColor()); paint.setStrokeCap(Cap.ROUND); if (currentWall != null) { canvas.drawLine(currentWall.a.x, currentWall.a.y, currentWall.b.x, currentWall.b.y, paint); } paint.setStrokeCap(Cap.BUTT); drawParticleTimer.start(); particles.draw(canvas, paint); drawParticleTimer.stop(); canvas.restore(); drawSimTimer.stop(); drawUITimer.start(); // Overlay the beat track beatTrack.draw(canvas); // Overlay the unit selector if (USE_UNIT_SELECTOR) { sim.getMyUnitSelector().draw(canvas); } drawUITimer.stop(); if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onDraw(canvas); } else if (!sim.isReady()) { paint.setColor(Color.WHITE); paint.setTextSize(20); canvas.drawText("Waiting for other player...", BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2, paint); } else { float countdown = sim.getStartingCountdown(); int number = (int) Math.ceil(countdown); if (number > 0) { float alpha = countdown - (int) countdown; paint.setARGB((int) (alpha * 255), 255, 255, 255); paint.setTextSize(100); canvas.drawText(Integer.toString(number), BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2 + 30, paint); } } float percent = (System.currentTimeMillis() - tap_location_hint_time) / (float)TAP_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setStrokeCap(Cap.ROUND); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Tap further right ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .75f + 20, paint); canvas.drawText("to make units!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .75f + 45, paint); canvas.drawPath(arrowPath, paint); } // Draw unit placement hint if necessary. percent = (System.currentTimeMillis() - sim.placement_tip_start_time) / (float)PLACEMENT_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Tap inside your zone of ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .25f + 20, paint); canvas.drawText("influence to make units!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .25f + 45, paint); } // Draw wall drag hint if necessary. percent = (System.currentTimeMillis() - drag_tip_start_time) / (float)DRAG_HINT_DISPLAY_LENGTH; if (percent < 1) { paint.setColor(Color.WHITE); paint.setStyle(Style.FILL); paint.setTextSize(18.0f); paint.setAlpha((int) (255 * 4 * (percent - percent * percent))); canvas.drawText("Drag finger further ", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .5f + 20, paint); canvas.drawText("to draw a longer wall!", BBTHGame.WIDTH / 2.0f, BBTHGame.HEIGHT * .5f + 45, paint); } if (BBTHGame.DEBUG) { // Draw timing information paint.setColor(Color.argb(63, 255, 255, 255)); paint.setTextSize(8); paint.setStyle(Style.FILL); int x = 80; int y = 30; int jump = 11; canvas.drawText("Entire update: " + entireUpdateTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- Sim update: " + simUpdateTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Sim tick: " + sim.entireTickTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - AI tick: " + sim.aiTickTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Controller: " + sim.aiControllerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Server player: " + sim.serverPlayerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText(" - Client player: " + sim.clientPlayerTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("Entire draw: " + entireDrawTimer.getMilliseconds() + " ms", x, y += jump * 2, paint); canvas.drawText("- Sim: " + drawSimTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- Particles: " + drawParticleTimer.getMilliseconds() + " ms", x, y += jump, paint); canvas.drawText("- UI: " + drawUITimer.getMilliseconds() + " ms", x, y += jump, paint); } if (!sim.isSynced()) { paint.setColor(Color.RED); paint.setTextSize(40); paint.setTextAlign(Align.CENTER); canvas.drawText("NOT SYNCED!", BBTHSimulation.GAME_X + BBTHSimulation.GAME_WIDTH / 2, BBTHSimulation.GAME_Y + BBTHSimulation.GAME_HEIGHT / 2 + 40, paint); } super.onDraw(canvas); entireDrawTimer.stop(); // draw achievement stuff Achievements.INSTANCE.draw(canvas, BBTHGame.WIDTH, BBTHGame.HEIGHT / 15.f); } @Override public void onUpdate(float seconds) { entireUpdateTimer.start(); if (!setSong && team == Team.CLIENT && sim.song != null) { // Set up sound stuff beatTrack.setSong(sim.song); setSong = true; } if (!singlePlayer) { // Stop the music if we disconnect if (bluetooth.getState() != State.CONNECTED) { beatTrack.stopMusic(); controller.pushUnder(new GameStatusMessageScreen.DisconnectScreen(controller)); controller.pop(); } } // Update the single-player AI if (singlePlayer && sim.getGameState() == GameState.IN_PROGRESS) { player_ai.update(seconds); } // Update the game simUpdateTimer.start(); if (singlePlayer) { sim.update(seconds); } else { sim.onUpdate(seconds); } simUpdateTimer.stop(); // Update the tutorial if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onUpdate(seconds); } else { endTutorial(); } // Start the countdown if (!countdownStarted && sim.getGameState() == GameState.WAITING_TO_START && sim.isReady()) { beatTrack.setStartDelay(3000); countdownStarted = true; } // Start the music if (setSong && sim.getGameState() == GameState.IN_PROGRESS && !beatTrack.isPlaying()) { beatTrack.startMusic(); } // Get new beats, yo beatTrack.refreshBeats(); // Shinies particles.tick(seconds); entireUpdateTimer.stop(); // End the game when the time comes GameState gameState = sim.getGameState(); if (gameState != GameState.WAITING_TO_START && gameState != GameState.IN_PROGRESS) { secondsUntilNextScreen -= seconds; if (secondsUntilNextScreen < 0) { moveToNextScreen(); } } // Update achievement stuff Achievements.INSTANCE.tick(seconds); } private void moveToNextScreen() { beatTrack.stopMusic(); // Move on to the next screen GameState gameState = sim.getGameState(); if (gameState == GameState.TIE) { controller.pushUnder(new GameStatusMessageScreen.TieScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } else if (sim.isServer == (gameState == GameState.SERVER_WON)) { controller.pushUnder(new GameStatusMessageScreen.WinScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } else { controller.pushUnder(new GameStatusMessageScreen.LoseScreen(controller)); controller.pop(BBTHGame.FROM_RIGHT_TRANSITION); } } @Override public void onTouchDown(float x, float y) { // We don't want to interact with the game if the tutorial is running! if ( BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchDown(x, y); return; } if (USE_UNIT_SELECTOR) { int unitType = sim.getMyUnitSelector().checkUnitChange(x, y); if (unitType >= 0) { if (singlePlayer) { sim.simulateCustomEvent(0, 0, unitType, true); } else { sim.recordCustomEvent(0, 0, unitType); } return; } } BeatType beatType = beatTrack.onTouchDown(x, y); boolean isHold = (beatType == BeatType.HOLD); boolean isOnBeat = (beatType != BeatType.REST); x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (x < 0) { // Display a message saying they should tap in-bounds tap_location_hint_time = System.currentTimeMillis(); } if (isOnBeat && isHold && x > 0 && y > 0) { currentWall = new Wall(x, y, x, y); } if (singlePlayer) { sim.simulateTapDown(x, y, true, isHold, isOnBeat); } else { sim.recordTapDown(x, y, isHold, isOnBeat); } } @Override public void onTouchMove(float x, float y) { // We don't want to interact with the game if the tutorial is running! if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchMove(x, y); return; } // We moved offscreen! x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (currentWall != null) { if (x < 0 || y < 0) { simulateWallGeneration(); } else { currentWall.b.set(x, y); } } if (singlePlayer) { sim.simulateTapMove(x, y, true); } else { sim.recordTapMove(x, y); } } @Override public void onTouchUp(float x, float y) { // We don't want to interact with the game if the tutorial is running! if (BBTHGame.SHOW_TUTORIAL && !tutorial.isFinished()) { tutorial.onTouchUp(x, y); return; } beatTrack.onTouchUp(x, y); if (userScrolling) { userScrolling = false; return; } x -= BBTHSimulation.GAME_X; y -= BBTHSimulation.GAME_Y; if (team == Team.SERVER) y = BBTHSimulation.GAME_HEIGHT - y; if (currentWall != null) { simulateWallGeneration(); } if (singlePlayer) { sim.simulateTapUp(x, y, true); } else { sim.recordTapUp(x, y); } } public void simulateWallGeneration() { currentWall.updateLength(); if (currentWall.length <= BBTHSimulation.MIN_WALL_LENGTH) { // Display a tip about dragging! drag_tip_start_time = System.currentTimeMillis(); } if (currentWall.length >= BBTHSimulation.MIN_WALL_LENGTH) { BBTHSimulation.generateParticlesForWall(currentWall, this.team); } currentWall = null; } /** * Stupid method necessary because of android's weird context/activity mess. */ @Override public void onActivityResult(int requestCode, int resultCode) { bluetooth.onActivityResult(requestCode, resultCode); } @Override public void onCompletion(MusicPlayer mp) { mp.stop(); // End both games at the same time with a synced event if (singlePlayer) { sim.simulateCustomEvent(0, 0, BBTHSimulation.MUSIC_STOPPED_EVENT, true); } else { sim.recordCustomEvent(0, 0, BBTHSimulation.MUSIC_STOPPED_EVENT); } } @Override public void willHide(boolean animated) { super.willHide(animated); beatTrack.stopMusic(); } public void endTutorial() { if (!gameIsStarted) { gameIsStarted = true; removeSubview(tutorial); sim.recordCustomEvent(0, 0, BBTHSimulation.TUTORIAL_DONE_EVENT); if (singlePlayer) sim.setBothPlayersReady(); } } public BeatTrack getBeatTrack() { return beatTrack; } }
InGameScreen ends game when it's stopped forcibly.
gameSrc/bbth/game/InGameScreen.java
InGameScreen ends game when it's stopped forcibly.
Java
mit
787b942b7fddf83de8daf4e478cdd740bf471fdf
0
mback2k/tsoexpert
package de.uxnr.tsoexpert.ui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextPane; import de.uxnr.tsoexpert.TSOExpert; import de.uxnr.tsoexpert.proxy.GameHandler; import de.uxnr.tsoexpert.ui.zone.ZoneMap; import de.uxnr.tsoexpert.ui.zone.ZoneMapFrame; import de.uxnr.tsoexpert.ui.zone.table.BuildingTableModel; import de.uxnr.tsoexpert.ui.zone.table.DepositTableModel; import de.uxnr.tsoexpert.ui.zone.table.ResourceTableModel; public class MainWindow implements PropertyChangeListener { private BuildingTableModel buildingTableModel = new BuildingTableModel(); private ResourceTableModel resourceTableModel = new ResourceTableModel(); private DepositTableModel depositTableModel = new DepositTableModel(); private ZoneMapFrame zoneMapFrame; private JFrame frame; private JTabbedPane tabbedPane; private JSplitPane splitPane; private JSplitPane zoneMapSplit; private JTable zoneBuildingTable; private JTable zoneResourceTable; private JTable zoneDepositTable; private JPanel zoneMapPanel; private JTextPane zoneText; private JLabel lblBackground; private JRadioButton btnBackgroundShow; private JRadioButton btnBackgroundDebug; private JLabel lblFreeLandscape; private JRadioButton btnFreeLandscapeHide; private JRadioButton btnFreeLandscapeShow; private JRadioButton btnFreeLandscapeDebug; private JLabel lblLandscape; private JRadioButton btnLandscapeHide; private JRadioButton btnLandscapeShow; private JRadioButton btnLandscapeDebug; private JLabel lblBuilding; private JRadioButton btnBuildingHide; private JRadioButton btnBuildingShow; private JRadioButton btnBuildingDebug; private JLabel lblResourceCreation; private JRadioButton btnResourceCreationHide; private JRadioButton btnResourceCreationDebug; private JLabel lblMapValues; private JRadioButton btnMapValuesHide; private JRadioButton btnMapValuesDebug; private final ButtonGroup backgroundButtonGroup = new ButtonGroup(); private final ButtonGroup freeLandscapeButtonGroup = new ButtonGroup(); private final ButtonGroup landscapeButtonGroup = new ButtonGroup(); private final ButtonGroup buildingButtonGroup = new ButtonGroup(); private final ButtonGroup resourceCreationButtonGroup = new ButtonGroup(); private final ButtonGroup mapValuesButtonGroup = new ButtonGroup(); /** * Launch the application. * @throws IOException */ public static void main(String[] args) throws IOException { TSOExpert.launchProxy(); final Thread proxy = new Thread(new Runnable() { @Override public void run() { try { InputStream stream = new FileInputStream(new File("2.amf")); GameHandler gameHandler = (GameHandler) TSOExpert.getHandler("GameHandler"); gameHandler.parseAMF(stream); } catch (IOException e) { e.printStackTrace(); } } }); TSOExpert.launchWindow(); proxy.start(); } /** * Create the application. * @wbp.parser.entryPoint */ public MainWindow() { GameHandler gameHandler = (GameHandler) TSOExpert.getHandler("GameHandler"); gameHandler.addDataHandler(1001, this.buildingTableModel); gameHandler.addDataHandler(1001, this.resourceTableModel); gameHandler.addDataHandler(1001, this.depositTableModel); this.initialize(); gameHandler.addDataHandler(1001, this.zoneMapFrame); } public void show() { this.frame.setVisible(true); } /** * Initialize the contents of the frame. */ private void initialize() { this.frame = new JFrame(); this.frame.setBounds(100, 100, 700, 450); this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.tabbedPane = new JTabbedPane(JTabbedPane.TOP); this.frame.getContentPane().add(this.tabbedPane, BorderLayout.CENTER); this.splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); this.tabbedPane.addTab("Map", null, this.splitPane, null); this.zoneMapSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); this.splitPane.setLeftComponent(this.zoneMapSplit); this.zoneMapFrame = new ZoneMapFrame(); this.splitPane.setRightComponent(this.zoneMapFrame); this.zoneMapPanel = new JPanel(); GridBagLayout gbl_zoneMapPanel = new GridBagLayout(); gbl_zoneMapPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; gbl_zoneMapPanel.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0}; this.zoneMapPanel.setLayout(gbl_zoneMapPanel); this.zoneMapSplit.setLeftComponent(this.zoneMapPanel); this.zoneText = new JTextPane(); this.zoneMapSplit.setRightComponent(this.zoneText); this.lblBackground = new JLabel("Background"); GridBagConstraints gbc_lblBackground = new GridBagConstraints(); gbc_lblBackground.insets = new Insets(0, 0, 5, 5); gbc_lblBackground.gridx = 0; gbc_lblBackground.gridy = 0; this.zoneMapPanel.add(this.lblBackground, gbc_lblBackground); this.btnBackgroundShow = new JRadioButton("Show"); this.btnBackgroundShow.setSelected(true); this.btnBackgroundShow.addPropertyChangeListener(this); backgroundButtonGroup.add(this.btnBackgroundShow); GridBagConstraints gbc_btnBackgroundShow = new GridBagConstraints(); gbc_btnBackgroundShow.insets = new Insets(0, 0, 5, 5); gbc_btnBackgroundShow.gridx = 2; gbc_btnBackgroundShow.gridy = 0; this.zoneMapPanel.add(this.btnBackgroundShow, gbc_btnBackgroundShow); this.btnBackgroundDebug = new JRadioButton("Debug"); this.btnBackgroundDebug.addPropertyChangeListener(this); backgroundButtonGroup.add(this.btnBackgroundDebug); GridBagConstraints gbc_btnBackgroundDebug = new GridBagConstraints(); gbc_btnBackgroundDebug.insets = new Insets(0, 0, 5, 0); gbc_btnBackgroundDebug.gridx = 3; gbc_btnBackgroundDebug.gridy = 0; this.zoneMapPanel.add(this.btnBackgroundDebug, gbc_btnBackgroundDebug); this.lblFreeLandscape = new JLabel("Free Landscape"); GridBagConstraints gbc_lblFreeLandscape = new GridBagConstraints(); gbc_lblFreeLandscape.insets = new Insets(0, 0, 5, 5); gbc_lblFreeLandscape.gridx = 0; gbc_lblFreeLandscape.gridy = 1; this.zoneMapPanel.add(this.lblFreeLandscape, gbc_lblFreeLandscape); this.btnFreeLandscapeHide = new JRadioButton("Hide"); this.btnFreeLandscapeHide.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeHide); GridBagConstraints gbc_btnFreeLandscapeHide = new GridBagConstraints(); gbc_btnFreeLandscapeHide.insets = new Insets(0, 0, 5, 5); gbc_btnFreeLandscapeHide.gridx = 1; gbc_btnFreeLandscapeHide.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeHide, gbc_btnFreeLandscapeHide); this.btnFreeLandscapeShow = new JRadioButton("Show"); this.btnFreeLandscapeShow.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeShow); GridBagConstraints gbc_btnFreeLandscapeShow = new GridBagConstraints(); gbc_btnFreeLandscapeShow.insets = new Insets(0, 0, 5, 5); gbc_btnFreeLandscapeShow.gridx = 2; gbc_btnFreeLandscapeShow.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeShow, gbc_btnFreeLandscapeShow); this.btnFreeLandscapeDebug = new JRadioButton("Debug"); this.btnFreeLandscapeDebug.setSelected(true); this.btnFreeLandscapeDebug.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeDebug); GridBagConstraints gbc_btnFreeLandscapeDebug = new GridBagConstraints(); gbc_btnFreeLandscapeDebug.insets = new Insets(0, 0, 5, 0); gbc_btnFreeLandscapeDebug.gridx = 3; gbc_btnFreeLandscapeDebug.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeDebug, gbc_btnFreeLandscapeDebug); this.lblLandscape = new JLabel("Landscape"); GridBagConstraints gbc_lblLandscape = new GridBagConstraints(); gbc_lblLandscape.insets = new Insets(0, 0, 5, 5); gbc_lblLandscape.gridx = 0; gbc_lblLandscape.gridy = 2; this.zoneMapPanel.add(this.lblLandscape, gbc_lblLandscape); this.btnLandscapeHide = new JRadioButton("Hide"); this.btnLandscapeHide.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeHide); GridBagConstraints gbc_btnLandscapeHide = new GridBagConstraints(); gbc_btnLandscapeHide.insets = new Insets(0, 0, 5, 5); gbc_btnLandscapeHide.gridx = 1; gbc_btnLandscapeHide.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeHide, gbc_btnLandscapeHide); this.btnLandscapeShow = new JRadioButton("Show"); this.btnLandscapeShow.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeShow); GridBagConstraints gbc_btnLandscapeShow = new GridBagConstraints(); gbc_btnLandscapeShow.insets = new Insets(0, 0, 5, 5); gbc_btnLandscapeShow.gridx = 2; gbc_btnLandscapeShow.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeShow, gbc_btnLandscapeShow); this.btnLandscapeDebug = new JRadioButton("Debug"); this.btnLandscapeDebug.setSelected(true); this.btnLandscapeDebug.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeDebug); GridBagConstraints gbc_btnLandscapeDebug = new GridBagConstraints(); gbc_btnLandscapeDebug.insets = new Insets(0, 0, 5, 0); gbc_btnLandscapeDebug.gridx = 3; gbc_btnLandscapeDebug.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeDebug, gbc_btnLandscapeDebug); this.lblBuilding = new JLabel("Building"); GridBagConstraints gbc_lblBuilding = new GridBagConstraints(); gbc_lblBuilding.insets = new Insets(0, 0, 5, 5); gbc_lblBuilding.gridx = 0; gbc_lblBuilding.gridy = 3; this.zoneMapPanel.add(this.lblBuilding, gbc_lblBuilding); this.btnBuildingHide = new JRadioButton("Hide"); this.btnBuildingHide.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingHide); GridBagConstraints gbc_btnBuildingHide = new GridBagConstraints(); gbc_btnBuildingHide.insets = new Insets(0, 0, 5, 5); gbc_btnBuildingHide.gridx = 1; gbc_btnBuildingHide.gridy = 3; this.zoneMapPanel.add(this.btnBuildingHide, gbc_btnBuildingHide); this.btnBuildingShow = new JRadioButton("Show"); this.btnBuildingShow.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingShow); GridBagConstraints gbc_btnBuildingShow = new GridBagConstraints(); gbc_btnBuildingShow.insets = new Insets(0, 0, 5, 5); gbc_btnBuildingShow.gridx = 2; gbc_btnBuildingShow.gridy = 3; this.zoneMapPanel.add(this.btnBuildingShow, gbc_btnBuildingShow); this.btnBuildingDebug = new JRadioButton("Debug"); this.btnBuildingDebug.setSelected(true); this.btnBuildingDebug.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingDebug); GridBagConstraints gbc_btnBuildingDebug = new GridBagConstraints(); gbc_btnBuildingDebug.insets = new Insets(0, 0, 5, 0); gbc_btnBuildingDebug.gridx = 3; gbc_btnBuildingDebug.gridy = 3; this.zoneMapPanel.add(this.btnBuildingDebug, gbc_btnBuildingDebug); this.lblResourceCreation = new JLabel("Resource Creation"); GridBagConstraints gbc_lblResourceCreation = new GridBagConstraints(); gbc_lblResourceCreation.insets = new Insets(0, 0, 5, 5); gbc_lblResourceCreation.gridx = 0; gbc_lblResourceCreation.gridy = 4; this.zoneMapPanel.add(this.lblResourceCreation, gbc_lblResourceCreation); this.btnResourceCreationHide = new JRadioButton("Hide"); this.btnResourceCreationHide.setSelected(true); this.btnResourceCreationHide.addPropertyChangeListener(this); resourceCreationButtonGroup.add(this.btnResourceCreationHide); GridBagConstraints gbc_btnResourceCreationHide = new GridBagConstraints(); gbc_btnResourceCreationHide.insets = new Insets(0, 0, 5, 5); gbc_btnResourceCreationHide.gridx = 2; gbc_btnResourceCreationHide.gridy = 4; this.zoneMapPanel.add(this.btnResourceCreationHide, gbc_btnResourceCreationHide); this.btnResourceCreationDebug = new JRadioButton("Debug"); this.btnResourceCreationDebug.addPropertyChangeListener(this); resourceCreationButtonGroup.add(this.btnResourceCreationDebug); GridBagConstraints gbc_btnResourceCreationDebug = new GridBagConstraints(); gbc_btnResourceCreationDebug.insets = new Insets(0, 0, 5, 0); gbc_btnResourceCreationDebug.gridx = 3; gbc_btnResourceCreationDebug.gridy = 4; this.zoneMapPanel.add(this.btnResourceCreationDebug, gbc_btnResourceCreationDebug); this.lblMapValues = new JLabel("Map Values"); GridBagConstraints gbc_lblMapValues = new GridBagConstraints(); gbc_lblMapValues.insets = new Insets(0, 0, 5, 5); gbc_lblMapValues.gridx = 0; gbc_lblMapValues.gridy = 5; this.zoneMapPanel.add(this.lblMapValues, gbc_lblMapValues); this.btnMapValuesHide = new JRadioButton("Hide"); this.btnMapValuesHide.setSelected(true); this.btnMapValuesHide.addPropertyChangeListener(this); mapValuesButtonGroup.add(this.btnMapValuesHide); GridBagConstraints gbc_btnMapValuesHide = new GridBagConstraints(); gbc_btnMapValuesHide.insets = new Insets(0, 0, 5, 5); gbc_btnMapValuesHide.gridx = 2; gbc_btnMapValuesHide.gridy = 5; this.zoneMapPanel.add(this.btnMapValuesHide, gbc_btnMapValuesHide); this.btnMapValuesDebug = new JRadioButton("Debug"); this.btnMapValuesDebug.addPropertyChangeListener(this); mapValuesButtonGroup.add(this.btnMapValuesDebug); GridBagConstraints gbc_btnMapValuesDebug = new GridBagConstraints(); gbc_btnMapValuesDebug.insets = new Insets(0, 0, 5, 0); gbc_btnMapValuesDebug.gridx = 3; gbc_btnMapValuesDebug.gridy = 5; this.zoneMapPanel.add(this.btnMapValuesDebug, gbc_btnMapValuesDebug); this.zoneBuildingTable = new JTable(); this.zoneBuildingTable.setAutoCreateColumnsFromModel(true); this.zoneBuildingTable.setModel(this.buildingTableModel); this.tabbedPane.addTab("Buildings", null, new JScrollPane(this.zoneBuildingTable), null); this.zoneResourceTable = new JTable(); this.zoneResourceTable.setAutoCreateColumnsFromModel(true); this.zoneResourceTable.setModel(this.resourceTableModel); this.tabbedPane.addTab("Resources", null, new JScrollPane(this.zoneResourceTable), null); this.zoneDepositTable = new JTable(); this.zoneDepositTable.setAutoCreateColumnsFromModel(true); this.zoneDepositTable.setModel(this.depositTableModel); this.tabbedPane.addTab("Deposits", null, new JScrollPane(this.zoneDepositTable), null); } public void propertyChange(PropertyChangeEvent event) { ZoneMap zoneMap = this.zoneMapFrame.getZoneMap(); if (zoneMap != null) { zoneMap.setShowBackground(this.btnBackgroundShow.isSelected()); zoneMap.setShowFreeLandscape(this.btnFreeLandscapeShow.isSelected()); zoneMap.setShowLandscape(this.btnLandscapeShow.isSelected()); zoneMap.setShowBuilding(this.btnBuildingShow.isSelected()); zoneMap.setDebugBackground(this.btnBackgroundDebug.isSelected()); zoneMap.setDebugFreeLandscape(this.btnFreeLandscapeDebug.isSelected()); zoneMap.setDebugLandscape(this.btnLandscapeDebug.isSelected()); zoneMap.setDebugBuilding(this.btnBuildingDebug.isSelected()); zoneMap.setDebugResourceCreations(this.btnResourceCreationDebug.isSelected()); zoneMap.setDebugMapValues(this.btnMapValuesDebug.isSelected()); this.zoneMapFrame.repaint(); } } }
src/de/uxnr/tsoexpert/ui/MainWindow.java
package de.uxnr.tsoexpert.ui; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import de.uxnr.tsoexpert.TSOExpert; import de.uxnr.tsoexpert.proxy.GameHandler; import de.uxnr.tsoexpert.ui.zone.ZoneMap; import de.uxnr.tsoexpert.ui.zone.ZoneMapFrame; import de.uxnr.tsoexpert.ui.zone.table.BuildingTableModel; import de.uxnr.tsoexpert.ui.zone.table.DepositTableModel; import de.uxnr.tsoexpert.ui.zone.table.ResourceTableModel; public class MainWindow implements PropertyChangeListener { private BuildingTableModel buildingTableModel = new BuildingTableModel(); private ResourceTableModel resourceTableModel = new ResourceTableModel(); private DepositTableModel depositTableModel = new DepositTableModel(); private ZoneMapFrame zoneMapFrame; private JFrame frame; private JTabbedPane tabbedPane; private JSplitPane splitPane; private JTable zoneBuildingTable; private JTable zoneResourceTable; private JTable zoneDepositTable; private JPanel zoneMapPanel; private JLabel lblBackground; private JRadioButton btnBackgroundShow; private JRadioButton btnBackgroundDebug; private JLabel lblFreeLandscape; private JRadioButton btnFreeLandscapeHide; private JRadioButton btnFreeLandscapeShow; private JRadioButton btnFreeLandscapeDebug; private JLabel lblLandscape; private JRadioButton btnLandscapeHide; private JRadioButton btnLandscapeShow; private JRadioButton btnLandscapeDebug; private JLabel lblBuilding; private JRadioButton btnBuildingHide; private JRadioButton btnBuildingShow; private JRadioButton btnBuildingDebug; private JLabel lblResourceCreation; private JRadioButton btnResourceCreationHide; private JRadioButton btnResourceCreationDebug; private JLabel lblMapValues; private JRadioButton btnMapValuesHide; private JRadioButton btnMapValuesDebug; private final ButtonGroup backgroundButtonGroup = new ButtonGroup(); private final ButtonGroup freeLandscapeButtonGroup = new ButtonGroup(); private final ButtonGroup landscapeButtonGroup = new ButtonGroup(); private final ButtonGroup buildingButtonGroup = new ButtonGroup(); private final ButtonGroup resourceCreationButtonGroup = new ButtonGroup(); private final ButtonGroup mapValuesButtonGroup = new ButtonGroup(); /** * Launch the application. * @throws IOException */ public static void main(String[] args) throws IOException { TSOExpert.launchProxy(); final Thread proxy = new Thread(new Runnable() { @Override public void run() { try { InputStream stream = new FileInputStream(new File("2.amf")); GameHandler gameHandler = (GameHandler) TSOExpert.getHandler("GameHandler"); gameHandler.parseAMF(stream); } catch (IOException e) { e.printStackTrace(); } } }); TSOExpert.launchWindow(); proxy.start(); } /** * Create the application. * @wbp.parser.entryPoint */ public MainWindow() { GameHandler gameHandler = (GameHandler) TSOExpert.getHandler("GameHandler"); gameHandler.addDataHandler(1001, this.buildingTableModel); gameHandler.addDataHandler(1001, this.resourceTableModel); gameHandler.addDataHandler(1001, this.depositTableModel); this.initialize(); gameHandler.addDataHandler(1001, this.zoneMapFrame); } public void show() { this.frame.setVisible(true); } /** * Initialize the contents of the frame. */ private void initialize() { this.frame = new JFrame(); this.frame.setBounds(100, 100, 700, 450); this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.tabbedPane = new JTabbedPane(JTabbedPane.TOP); this.frame.getContentPane().add(this.tabbedPane, BorderLayout.CENTER); this.splitPane = new JSplitPane(); this.tabbedPane.addTab("Map", null, this.splitPane, null); this.zoneMapFrame = new ZoneMapFrame(); this.splitPane.setRightComponent(this.zoneMapFrame); this.zoneMapPanel = new JPanel(); this.splitPane.setLeftComponent(this.zoneMapPanel); GridBagLayout gbl_zoneMapPanel = new GridBagLayout(); this.zoneMapPanel.setLayout(gbl_zoneMapPanel); this.lblBackground = new JLabel("Background"); GridBagConstraints gbc_lblBackground = new GridBagConstraints(); gbc_lblBackground.insets = new Insets(0, 0, 5, 5); gbc_lblBackground.gridx = 0; gbc_lblBackground.gridy = 0; this.zoneMapPanel.add(this.lblBackground, gbc_lblBackground); this.btnBackgroundShow = new JRadioButton("Show"); this.btnBackgroundShow.setSelected(true); this.btnBackgroundShow.addPropertyChangeListener(this); backgroundButtonGroup.add(this.btnBackgroundShow); GridBagConstraints gbc_btnBackgroundShow = new GridBagConstraints(); gbc_btnBackgroundShow.insets = new Insets(0, 0, 5, 5); gbc_btnBackgroundShow.gridx = 2; gbc_btnBackgroundShow.gridy = 0; this.zoneMapPanel.add(this.btnBackgroundShow, gbc_btnBackgroundShow); this.btnBackgroundDebug = new JRadioButton("Debug"); this.btnBackgroundDebug.addPropertyChangeListener(this); backgroundButtonGroup.add(this.btnBackgroundDebug); GridBagConstraints gbc_btnBackgroundDebug = new GridBagConstraints(); gbc_btnBackgroundDebug.insets = new Insets(0, 0, 5, 0); gbc_btnBackgroundDebug.gridx = 3; gbc_btnBackgroundDebug.gridy = 0; this.zoneMapPanel.add(this.btnBackgroundDebug, gbc_btnBackgroundDebug); this.lblFreeLandscape = new JLabel("Free Landscape"); GridBagConstraints gbc_lblFreeLandscape = new GridBagConstraints(); gbc_lblFreeLandscape.insets = new Insets(0, 0, 5, 5); gbc_lblFreeLandscape.gridx = 0; gbc_lblFreeLandscape.gridy = 1; this.zoneMapPanel.add(this.lblFreeLandscape, gbc_lblFreeLandscape); this.btnFreeLandscapeHide = new JRadioButton("Hide"); this.btnFreeLandscapeHide.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeHide); GridBagConstraints gbc_btnFreeLandscapeHide = new GridBagConstraints(); gbc_btnFreeLandscapeHide.insets = new Insets(0, 0, 5, 5); gbc_btnFreeLandscapeHide.gridx = 1; gbc_btnFreeLandscapeHide.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeHide, gbc_btnFreeLandscapeHide); this.btnFreeLandscapeShow = new JRadioButton("Show"); this.btnFreeLandscapeShow.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeShow); GridBagConstraints gbc_btnFreeLandscapeShow = new GridBagConstraints(); gbc_btnFreeLandscapeShow.insets = new Insets(0, 0, 5, 5); gbc_btnFreeLandscapeShow.gridx = 2; gbc_btnFreeLandscapeShow.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeShow, gbc_btnFreeLandscapeShow); this.btnFreeLandscapeDebug = new JRadioButton("Debug"); this.btnFreeLandscapeDebug.setSelected(true); this.btnFreeLandscapeDebug.addPropertyChangeListener(this); freeLandscapeButtonGroup.add(this.btnFreeLandscapeDebug); GridBagConstraints gbc_btnFreeLandscapeDebug = new GridBagConstraints(); gbc_btnFreeLandscapeDebug.insets = new Insets(0, 0, 5, 0); gbc_btnFreeLandscapeDebug.gridx = 3; gbc_btnFreeLandscapeDebug.gridy = 1; this.zoneMapPanel.add(this.btnFreeLandscapeDebug, gbc_btnFreeLandscapeDebug); this.lblLandscape = new JLabel("Landscape"); GridBagConstraints gbc_lblLandscape = new GridBagConstraints(); gbc_lblLandscape.insets = new Insets(0, 0, 5, 5); gbc_lblLandscape.gridx = 0; gbc_lblLandscape.gridy = 2; this.zoneMapPanel.add(this.lblLandscape, gbc_lblLandscape); this.btnLandscapeHide = new JRadioButton("Hide"); this.btnLandscapeHide.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeHide); GridBagConstraints gbc_btnLandscapeHide = new GridBagConstraints(); gbc_btnLandscapeHide.insets = new Insets(0, 0, 5, 5); gbc_btnLandscapeHide.gridx = 1; gbc_btnLandscapeHide.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeHide, gbc_btnLandscapeHide); this.btnLandscapeShow = new JRadioButton("Show"); this.btnLandscapeShow.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeShow); GridBagConstraints gbc_btnLandscapeShow = new GridBagConstraints(); gbc_btnLandscapeShow.insets = new Insets(0, 0, 5, 5); gbc_btnLandscapeShow.gridx = 2; gbc_btnLandscapeShow.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeShow, gbc_btnLandscapeShow); this.btnLandscapeDebug = new JRadioButton("Debug"); this.btnLandscapeDebug.setSelected(true); this.btnLandscapeDebug.addPropertyChangeListener(this); landscapeButtonGroup.add(this.btnLandscapeDebug); GridBagConstraints gbc_btnLandscapeDebug = new GridBagConstraints(); gbc_btnLandscapeDebug.insets = new Insets(0, 0, 5, 0); gbc_btnLandscapeDebug.gridx = 3; gbc_btnLandscapeDebug.gridy = 2; this.zoneMapPanel.add(this.btnLandscapeDebug, gbc_btnLandscapeDebug); this.lblBuilding = new JLabel("Building"); GridBagConstraints gbc_lblBuilding = new GridBagConstraints(); gbc_lblBuilding.insets = new Insets(0, 0, 5, 5); gbc_lblBuilding.gridx = 0; gbc_lblBuilding.gridy = 3; this.zoneMapPanel.add(this.lblBuilding, gbc_lblBuilding); this.btnBuildingHide = new JRadioButton("Hide"); this.btnBuildingHide.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingHide); GridBagConstraints gbc_btnBuildingHide = new GridBagConstraints(); gbc_btnBuildingHide.insets = new Insets(0, 0, 5, 5); gbc_btnBuildingHide.gridx = 1; gbc_btnBuildingHide.gridy = 3; this.zoneMapPanel.add(this.btnBuildingHide, gbc_btnBuildingHide); this.btnBuildingShow = new JRadioButton("Show"); this.btnBuildingShow.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingShow); GridBagConstraints gbc_btnBuildingShow = new GridBagConstraints(); gbc_btnBuildingShow.insets = new Insets(0, 0, 5, 5); gbc_btnBuildingShow.gridx = 2; gbc_btnBuildingShow.gridy = 3; this.zoneMapPanel.add(this.btnBuildingShow, gbc_btnBuildingShow); this.btnBuildingDebug = new JRadioButton("Debug"); this.btnBuildingDebug.setSelected(true); this.btnBuildingDebug.addPropertyChangeListener(this); buildingButtonGroup.add(this.btnBuildingDebug); GridBagConstraints gbc_btnBuildingDebug = new GridBagConstraints(); gbc_btnBuildingDebug.insets = new Insets(0, 0, 5, 0); gbc_btnBuildingDebug.gridx = 3; gbc_btnBuildingDebug.gridy = 3; this.zoneMapPanel.add(this.btnBuildingDebug, gbc_btnBuildingDebug); this.lblResourceCreation = new JLabel("Resource Creation"); GridBagConstraints gbc_lblResourceCreation = new GridBagConstraints(); gbc_lblResourceCreation.insets = new Insets(0, 0, 5, 5); gbc_lblResourceCreation.gridx = 0; gbc_lblResourceCreation.gridy = 4; this.zoneMapPanel.add(this.lblResourceCreation, gbc_lblResourceCreation); this.btnResourceCreationHide = new JRadioButton("Hide"); this.btnResourceCreationHide.setSelected(true); this.btnResourceCreationHide.addPropertyChangeListener(this); resourceCreationButtonGroup.add(this.btnResourceCreationHide); GridBagConstraints gbc_btnResourceCreationHide = new GridBagConstraints(); gbc_btnResourceCreationHide.insets = new Insets(0, 0, 5, 5); gbc_btnResourceCreationHide.gridx = 2; gbc_btnResourceCreationHide.gridy = 4; this.zoneMapPanel.add(this.btnResourceCreationHide, gbc_btnResourceCreationHide); this.btnResourceCreationDebug = new JRadioButton("Debug"); this.btnResourceCreationDebug.addPropertyChangeListener(this); resourceCreationButtonGroup.add(this.btnResourceCreationDebug); GridBagConstraints gbc_btnResourceCreationDebug = new GridBagConstraints(); gbc_btnResourceCreationDebug.insets = new Insets(0, 0, 5, 0); gbc_btnResourceCreationDebug.gridx = 3; gbc_btnResourceCreationDebug.gridy = 4; this.zoneMapPanel.add(this.btnResourceCreationDebug, gbc_btnResourceCreationDebug); this.lblMapValues = new JLabel("Map Values"); GridBagConstraints gbc_lblMapValues = new GridBagConstraints(); gbc_lblMapValues.insets = new Insets(0, 0, 0, 5); gbc_lblMapValues.gridx = 0; gbc_lblMapValues.gridy = 5; this.zoneMapPanel.add(this.lblMapValues, gbc_lblMapValues); this.btnMapValuesHide = new JRadioButton("Hide"); this.btnMapValuesHide.setSelected(true); this.btnMapValuesHide.addPropertyChangeListener(this); mapValuesButtonGroup.add(this.btnMapValuesHide); GridBagConstraints gbc_btnMapValuesHide = new GridBagConstraints(); gbc_btnMapValuesHide.insets = new Insets(0, 0, 0, 5); gbc_btnMapValuesHide.gridx = 2; gbc_btnMapValuesHide.gridy = 5; this.zoneMapPanel.add(this.btnMapValuesHide, gbc_btnMapValuesHide); this.btnMapValuesDebug = new JRadioButton("Debug"); this.btnMapValuesDebug.addPropertyChangeListener(this); mapValuesButtonGroup.add(this.btnMapValuesDebug); GridBagConstraints gbc_btnMapValuesDebug = new GridBagConstraints(); gbc_btnMapValuesDebug.gridx = 3; gbc_btnMapValuesDebug.gridy = 5; this.zoneMapPanel.add(this.btnMapValuesDebug, gbc_btnMapValuesDebug); this.zoneBuildingTable = new JTable(); this.zoneBuildingTable.setAutoCreateColumnsFromModel(true); this.zoneBuildingTable.setModel(this.buildingTableModel); this.tabbedPane.addTab("Buildings", null, new JScrollPane(this.zoneBuildingTable), null); this.zoneResourceTable = new JTable(); this.zoneResourceTable.setAutoCreateColumnsFromModel(true); this.zoneResourceTable.setModel(this.resourceTableModel); this.tabbedPane.addTab("Resources", null, new JScrollPane(this.zoneResourceTable), null); this.zoneDepositTable = new JTable(); this.zoneDepositTable.setAutoCreateColumnsFromModel(true); this.zoneDepositTable.setModel(this.depositTableModel); this.tabbedPane.addTab("Deposits", null, new JScrollPane(this.zoneDepositTable), null); } public void propertyChange(PropertyChangeEvent event) { ZoneMap zoneMap = this.zoneMapFrame.getZoneMap(); if (zoneMap != null) { zoneMap.setShowBackground(this.btnBackgroundShow.isSelected()); zoneMap.setShowFreeLandscape(this.btnFreeLandscapeShow.isSelected()); zoneMap.setShowLandscape(this.btnLandscapeShow.isSelected()); zoneMap.setShowBuilding(this.btnBuildingShow.isSelected()); zoneMap.setDebugBackground(this.btnBackgroundDebug.isSelected()); zoneMap.setDebugFreeLandscape(this.btnFreeLandscapeDebug.isSelected()); zoneMap.setDebugLandscape(this.btnLandscapeDebug.isSelected()); zoneMap.setDebugBuilding(this.btnBuildingDebug.isSelected()); zoneMap.setDebugResourceCreations(this.btnResourceCreationDebug.isSelected()); zoneMap.setDebugMapValues(this.btnMapValuesDebug.isSelected()); this.zoneMapFrame.repaint(); } } }
Added text panel to map GUI
src/de/uxnr/tsoexpert/ui/MainWindow.java
Added text panel to map GUI
Java
mit
23d9816c7b3f417c9fd236ece1a6b63bfc22e335
0
amarkrishna/demo1,amarkrishna/demo1,amarkrishna/demo1,amarkrishna/demo1
package magpie.user.server; import magpie.data.Dataset; import magpie.models.BaseModel; import magpie.models.classification.AbstractClassifier; import magpie.user.server.thrift.ModelInfo; /** * Holds information about a model. * @author Logan Ward */ public class ModelPackage { /** Dataset used to generate attributes */ final public Dataset Dataset; /** Model to be evaluated */ final public BaseModel Model; /** Name of property being modeled. HTML format suggested */ public String Property = "Unspecified"; /** Units for property */ public String Units = "Unspecified"; /** Training set description */ public String TrainingSet = "Unspecified"; /** Author of this model */ public String Author = "Unspecified"; /** Citation for this model */ public String Citation = "Unspecified"; /** Short description of this model */ public String Description = ""; /** Long form description of model */ public String Notes; /** * Initialize model package * @param data Dataset used to generate attributes * @param model Model to be evaluated */ public ModelPackage(Dataset data, BaseModel model) { this.Dataset = data; this.Model = model; } /** * Generate model info in a format suitable for Thrift interface * @return Model info in Thrift format */ public ModelInfo generateInfo() { ModelInfo info = new ModelInfo(); // Store basic info info.author = Author; info.citation = Citation; info.description = Description; info.property = Property; info.training = Model.TrainingStats.NumberTested + " entries: " + TrainingSet; info.notes = Notes; // Store units or class names if (Model instanceof AbstractClassifier) { info.classifier = true; info.units = ""; AbstractClassifier clfr = (AbstractClassifier) Model; boolean started = false; for (String name : clfr.getClassNames()) { if (started) { info.units += ";"; } info.units += name; started = true; } } else { info.classifier = false; info.units = Units; } // Store names of models info.dataType = Dataset.getClass().getName(); info.modelType = Model.printDescription(true); // Store validation performance data info.valMethod = Model.getValidationMethod(); if (Model.isValidated()) { info.valScore = Model.ValidationStats.getStatistics(); } return info; } }
src/magpie/user/server/ModelPackage.java
package magpie.user.server; import magpie.data.Dataset; import magpie.models.BaseModel; import magpie.models.classification.AbstractClassifier; import magpie.user.server.thrift.ModelInfo; /** * Holds information about a model. * @author Logan Ward */ public class ModelPackage { /** Dataset used to generate attributes */ final public Dataset Dataset; /** Model to be evaluated */ final public BaseModel Model; /** Name of property being modeled. HTML format suggested */ public String Property = "Unspecified"; /** Units for property */ public String Units = "Unspecified"; /** Training set description */ public String TrainingSet = "Unspecified"; /** Author of this model */ public String Author = "Unspecified"; /** Citation for this model */ public String Citation = "Unspecified"; /** Short description of this model */ public String Description = ""; /** Long form description of model */ public String Notes; /** * Initialize model package * @param data Dataset used to generate attributes * @param model Model to be evaluated */ public ModelPackage(Dataset data, BaseModel model) { this.Dataset = data; this.Model = model; } /** * Generate model info in a format suitable for Thrift interface * @return Model info in Thrift format */ public ModelInfo generateInfo() { ModelInfo info = new ModelInfo(); // Store basic info info.author = Author; info.citation = Citation; info.description = Description; info.property = Property; info.training = TrainingSet; info.notes = Notes; // Store units or class names if (Model instanceof AbstractClassifier) { info.classifier = true; info.units = ""; AbstractClassifier clfr = (AbstractClassifier) Model; boolean started = false; for (String name : clfr.getClassNames()) { if (started) { info.units += ";"; } info.units += name; started = true; } } else { info.classifier = false; info.units = Units; } // Store names of models info.dataType = Dataset.getClass().getName(); info.modelType = Model.printDescription(true); // Store validation performance data info.valMethod = Model.getValidationMethod(); if (Model.isValidated()) { info.valScore = Model.ValidationStats.getStatistics(); } return info; } }
Print out training set size in description
src/magpie/user/server/ModelPackage.java
Print out training set size in description
Java
mit
4e6873df198e7ced4ff1eafd48337e86c54e99d5
0
Bitseller/jrpg-2017b-cliente
package estados; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; import com.google.gson.Gson; import dominio.Asesino; import dominio.Casta; import dominio.Elfo; import dominio.Guerrero; import dominio.Hechicero; import dominio.Humano; import dominio.Orco; import dominio.Personaje; import interfaz.EstadoDePersonaje; import interfaz.MenuBatalla; import interfaz.MenuInfoPersonaje; import juego.Juego; import mensajeria.Comando; import mensajeria.PaqueteAtacar; import mensajeria.PaqueteBatalla; import mensajeria.PaqueteFinalizarBatalla; import mensajeria.PaquetePersonaje; import mundo.Mundo; import recursos.Recursos; /** * The Class EstadoBatalla. */ public class EstadoBatalla extends Estado { private static final int CONSTANTE_ENERGIZANTE = 10; private static final int Y_ESTADO_ENEMIGO = 5; private static final int X_ESTADO_ENEMIGO = 550; private static final int Y_ESTADO_PJ = 5; private static final int X_ESTADO_PJ = 25; private static final int H_ENEMIGO = 256; private static final int W_ENEMIGO = 256; private static final int Y_ENEMIGO = 75; private static final int X_ENEMIGO = 550; private static final int H_PERSONAJE = 256; private static final int W_PERSONAJE = 256; private static final int Y_PERSONAJE = 175; private static final int X_PERSONAJE = 0; private static final int ENEMIGOBUFFERFRENTE = 7; private static final int PERSONAJEBUFFERESPALDA = 3; private static final int PUNTOS_A_ASIGNAR = 3; private static final int CONSTANTEEXP = 40; private static final int PRIMERHABILIDAD = 1; private static final int SEGUNDAHABILIDAD = 2; private static final int TERCERAHABILIDAD = 3; private static final int CUARTAHABILIDAD = 4; private static final int QUINTAHABILIDAD = 5; private static final int SEXTAHABILIDAD = 6; private static final int Y_OFFSET = 150; private static final int X_OFFSET = -350; private static final int ENEMIGOBUFFERED = 5; private static final int PERSONAJEBUFFERED = 5; private Mundo mundo; private Personaje personaje; private Personaje enemigo; private int[] posMouse; private PaquetePersonaje paquetePersonaje; private PaquetePersonaje paqueteEnemigo; private PaqueteAtacar paqueteAtacar; private PaqueteFinalizarBatalla paqueteFinalizarBatalla; private boolean miTurno; private boolean haySpellSeleccionada; private boolean seRealizoAccion; private Gson gson = new Gson(); private BufferedImage miniaturaPersonaje; private BufferedImage miniaturaEnemigo; private MenuBatalla menuBatalla; /** * Instantiates a new estado batalla. * * @param juego * the juego * @param paqueteBatalla * the paquete batalla */ public EstadoBatalla(final Juego juego, final PaqueteBatalla paqueteBatalla) { super(juego); mundo = new Mundo(juego, "recursos/mundoBatalla.txt", "recursos/mundoBatallaCapaDos.txt"); miTurno = paqueteBatalla.isMiTurno(); paquetePersonaje = juego.getPersonajesConectados().get(paqueteBatalla.getId()); paqueteEnemigo = juego.getPersonajesConectados().get(paqueteBatalla.getIdEnemigo()); crearPersonajes(); menuBatalla = new MenuBatalla(miTurno, personaje); miniaturaEnemigo = Recursos.getPersonaje().get(enemigo.getNombreRaza()).get(ENEMIGOBUFFERED)[0]; miniaturaPersonaje = Recursos.getPersonaje().get(personaje.getNombreRaza()).get(PERSONAJEBUFFERED)[0]; paqueteFinalizarBatalla = new PaqueteFinalizarBatalla(); paqueteFinalizarBatalla.setId(personaje.getIdPersonaje()); paqueteFinalizarBatalla.setIdEnemigo(enemigo.getIdPersonaje()); // por defecto batalla perdida juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_PERDER_BATALLA); // limpio la accion del mouse juego.getHandlerMouse().setNuevoClick(false); } @Override public void actualizar() { juego.getCamara().setxOffset(X_OFFSET); juego.getCamara().setyOffset(Y_OFFSET); seRealizoAccion = false; haySpellSeleccionada = false; if (miTurno) { if (juego.getHandlerMouse().getNuevoClick()) { posMouse = juego.getHandlerMouse().getPosMouse(); if (menuBatalla.clickEnMenu(posMouse[0], posMouse[1])) { if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == PRIMERHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadRaza1(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == SEGUNDAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadRaza2(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == TERCERAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta1(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == CUARTAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta2(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == QUINTAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta3(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == SEXTAHABILIDAD) { seRealizoAccion = true; personaje.serEnergizado(CONSTANTE_ENERGIZANTE); haySpellSeleccionada = true; } } if (haySpellSeleccionada && seRealizoAccion) { if (!enemigo.estaVivo()) { juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_GANAR_BATALLA); if (personaje.ganarExperiencia(enemigo.getNivel() * CONSTANTEEXP)) { juego.getPersonaje().setNivel(personaje.getNivel()); juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_SUBIR_NIVEL); // Actualiza los puntos del personaje. juego.getPersonaje().setPuntosSkill(personaje.getPuntosSkill() + PUNTOS_A_ASIGNAR); } paqueteFinalizarBatalla.setGanadorBatalla(juego.getPersonaje().getId()); finalizarBatalla(); Estado.setEstado(juego.getEstadoJuego()); } else { paqueteAtacar = new PaqueteAtacar(paquetePersonaje.getId(), paqueteEnemigo.getId(), personaje.getSalud(), personaje.getEnergia(), enemigo.getSalud(), enemigo.getEnergia(), personaje.getDefensa(), enemigo.getDefensa(), personaje.getCasta().getProbabilidadEvitarAtaque(), enemigo.getCasta().getProbabilidadEvitarAtaque()); enviarAtaque(paqueteAtacar); miTurno = false; menuBatalla.setHabilitado(false); } } else if (haySpellSeleccionada && !seRealizoAccion) { JOptionPane.showMessageDialog(null, "No posees la energรญa suficiente para realizar esta habilidad."); } juego.getHandlerMouse().setNuevoClick(false); } } } @Override public void graficar(final Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, juego.getAncho(), juego.getAlto()); mundo.graficar(g); g.drawImage(Recursos.getPersonaje().get(paquetePersonaje.getRaza()).get(PERSONAJEBUFFERESPALDA)[0] , X_PERSONAJE, Y_PERSONAJE, W_PERSONAJE, H_PERSONAJE, null); g.drawImage(Recursos.getPersonaje().get(paqueteEnemigo.getRaza()).get(ENEMIGOBUFFERFRENTE)[0] , X_ENEMIGO, Y_ENEMIGO, W_ENEMIGO, H_ENEMIGO, null); mundo.graficarObstaculos(g); menuBatalla.graficar(g); g.setColor(Color.GREEN); EstadoDePersonaje.dibujarEstadoDePersonaje(g, X_ESTADO_PJ, Y_ESTADO_PJ , personaje, miniaturaPersonaje); EstadoDePersonaje.dibujarEstadoDePersonaje(g, X_ESTADO_ENEMIGO, Y_ESTADO_ENEMIGO , enemigo, miniaturaEnemigo); } /** * Crear personajes. */ private void crearPersonajes() { String nombre = paquetePersonaje.getNombre(); int salud = paquetePersonaje.getSaludTope(); int energia = paquetePersonaje.getEnergiaTope(); int fuerza = paquetePersonaje.getFuerza(); int destreza = paquetePersonaje.getDestreza(); int inteligencia = paquetePersonaje.getInteligencia(); int experiencia = paquetePersonaje.getExperiencia(); int nivel = paquetePersonaje.getNivel(); int id = paquetePersonaje.getId(); Casta casta = null; try { casta = (Casta) Class.forName("dominio" + "." + paquetePersonaje.getCasta()).newInstance(); personaje = (Personaje) Class.forName("dominio" + "." + paquetePersonaje.getRaza()) .getConstructor(String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Casta.class, Integer.TYPE, Integer.TYPE, Integer.TYPE) .newInstance(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { JOptionPane.showMessageDialog(null, "Error al crear la batalla"); } nombre = paqueteEnemigo.getNombre(); salud = paqueteEnemigo.getSaludTope(); energia = paqueteEnemigo.getEnergiaTope(); fuerza = paqueteEnemigo.getFuerza(); destreza = paqueteEnemigo.getDestreza(); inteligencia = paqueteEnemigo.getInteligencia(); experiencia = paqueteEnemigo.getExperiencia(); nivel = paqueteEnemigo.getNivel(); id = paqueteEnemigo.getId(); casta = null; if (paqueteEnemigo.getCasta().equals("Guerrero")) { casta = new Guerrero(); } else if (paqueteEnemigo.getCasta().equals("Hechicero")) { casta = new Hechicero(); } else if (paqueteEnemigo.getCasta().equals("Asesino")) { casta = new Asesino(); } if (paqueteEnemigo.getRaza().equals("Humano")) { enemigo = new Humano(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } else if (paqueteEnemigo.getRaza().equals("Orco")) { enemigo = new Orco(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } else if (paqueteEnemigo.getRaza().equals("Elfo")) { enemigo = new Elfo(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } } /** * Enviar ataque. * * @param pAtacar * the paquete atacar */ public void enviarAtaque(final PaqueteAtacar pAtacar) { try { juego.getCliente().getSalida().writeObject(gson.toJson(pAtacar)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexion con el servidor."); } } /** * Finalizar batalla. */ private void finalizarBatalla() { try { juego.getCliente().getSalida().writeObject(gson.toJson(paqueteFinalizarBatalla)); paquetePersonaje.setSaludTope(personaje.getSaludTope()); paquetePersonaje.setEnergiaTope(personaje.getEnergiaTope()); paquetePersonaje.setNivel(personaje.getNivel()); paquetePersonaje.setExperiencia(personaje.getExperiencia()); paquetePersonaje.setDestreza(personaje.getDestreza()); paquetePersonaje.setFuerza(personaje.getFuerza()); paquetePersonaje.setInteligencia(personaje.getInteligencia()); paquetePersonaje.removerBonus(); paqueteEnemigo.setSaludTope(enemigo.getSaludTope()); paqueteEnemigo.setEnergiaTope(enemigo.getEnergiaTope()); paqueteEnemigo.setNivel(enemigo.getNivel()); paqueteEnemigo.setExperiencia(enemigo.getExperiencia()); paqueteEnemigo.setDestreza(enemigo.getDestreza()); paqueteEnemigo.setFuerza(enemigo.getFuerza()); paqueteEnemigo.setInteligencia(enemigo.getInteligencia()); paqueteEnemigo.removerBonus(); paquetePersonaje.setComando(Comando.ACTUALIZARPERSONAJE); paqueteEnemigo.setComando(Comando.ACTUALIZARPERSONAJE); juego.getCliente().getSalida().writeObject(gson.toJson(paquetePersonaje)); juego.getCliente().getSalida().writeObject(gson.toJson(paqueteEnemigo)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexiรณn con el servidor"); } } /** * Gets the paquete personaje. * * @return the paquete personaje */ public PaquetePersonaje getPaquetePersonaje() { return paquetePersonaje; } /** * Gets the paquete enemigo. * * @return the paquete enemigo */ public PaquetePersonaje getPaqueteEnemigo() { return paqueteEnemigo; } /** * Sets the mi turno. * * @param b * the new mi turno */ public void setMiTurno(final boolean b) { miTurno = b; menuBatalla.setHabilitado(b); juego.getHandlerMouse().setNuevoClick(false); } /** * Gets the personaje. * * @return the personaje */ public Personaje getPersonaje() { return personaje; } /** * Gets the enemigo. * * @return the enemigo */ public Personaje getEnemigo() { return enemigo; } @Override public boolean esEstadoDeJuego() { return false; } }
src/main/java/estados/EstadoBatalla.java
package estados; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import javax.swing.JOptionPane; import com.google.gson.Gson; import dominio.Asesino; import dominio.Casta; import dominio.Elfo; import dominio.Guerrero; import dominio.Hechicero; import dominio.Humano; import dominio.Orco; import dominio.Personaje; import interfaz.EstadoDePersonaje; import interfaz.MenuBatalla; import interfaz.MenuInfoPersonaje; import juego.Juego; import mensajeria.Comando; import mensajeria.PaqueteAtacar; import mensajeria.PaqueteBatalla; import mensajeria.PaqueteFinalizarBatalla; import mensajeria.PaquetePersonaje; import mundo.Mundo; import recursos.Recursos; /** * The Class EstadoBatalla. */ public class EstadoBatalla extends Estado { private static final int CONSTANTE_ENERGIZANTE = 10; private static final int Y_ESTADO_ENEMIGO = 5; private static final int X_ESTADO_ENEMIGO = 550; private static final int Y_ESTADO_PJ = 5; private static final int X_ESTADO_PJ = 25; private static final int H_ENEMIGO = 256; private static final int W_ENEMIGO = 256; private static final int Y_ENEMIGO = 75; private static final int X_ENEMIGO = 550; private static final int H_PERSONAJE = 256; private static final int W_PERSONAJE = 256; private static final int Y_PERSONAJE = 175; private static final int X_PERSONAJE = 0; private static final int ENEMIGOBUFFERFRENTE = 7; private static final int PERSONAJEBUFFERESPALDA = 3; private static final int PUNTOS_A_ASIGNAR = 3; private static final int CONSTANTEEXP = 40; private static final int PRIMERHABILIDAD = 1; private static final int SEGUNDAHABILIDAD = 2; private static final int TERCERAHABILIDAD = 3; private static final int CUARTAHABILIDAD = 4; private static final int QUINTAHABILIDAD = 5; private static final int SEXTAHABILIDAD = 6; private static final int Y_OFFSET = 150; private static final int X_OFFSET = -350; private static final int ENEMIGOBUFFERED = 5; private static final int PERSONAJEBUFFERED = 5; private Mundo mundo; private Personaje personaje; private Personaje enemigo; private int[] posMouse; private PaquetePersonaje paquetePersonaje; private PaquetePersonaje paqueteEnemigo; private PaqueteAtacar paqueteAtacar; private PaqueteFinalizarBatalla paqueteFinalizarBatalla; private boolean miTurno; private boolean haySpellSeleccionada; private boolean seRealizoAccion; private Gson gson = new Gson(); private BufferedImage miniaturaPersonaje; private BufferedImage miniaturaEnemigo; private MenuBatalla menuBatalla; /** * Instantiates a new estado batalla. * * @param juego * the juego * @param paqueteBatalla * the paquete batalla */ public EstadoBatalla(final Juego juego, final PaqueteBatalla paqueteBatalla) { super(juego); mundo = new Mundo(juego, "recursos/mundoBatalla.txt", "recursos/mundoBatallaCapaDos.txt"); miTurno = paqueteBatalla.isMiTurno(); paquetePersonaje = juego.getPersonajesConectados().get(paqueteBatalla.getId()); paqueteEnemigo = juego.getPersonajesConectados().get(paqueteBatalla.getIdEnemigo()); crearPersonajes(); menuBatalla = new MenuBatalla(miTurno, personaje); miniaturaEnemigo = Recursos.getPersonaje().get(enemigo.getNombreRaza()).get(ENEMIGOBUFFERED)[0]; miniaturaPersonaje = Recursos.getPersonaje().get(personaje.getNombreRaza()).get(PERSONAJEBUFFERED)[0]; paqueteFinalizarBatalla = new PaqueteFinalizarBatalla(); paqueteFinalizarBatalla.setId(personaje.getIdPersonaje()); paqueteFinalizarBatalla.setIdEnemigo(enemigo.getIdPersonaje()); // por defecto batalla perdida juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_PERDER_BATALLA); // limpio la accion del mouse juego.getHandlerMouse().setNuevoClick(false); } @Override public void actualizar() { juego.getCamara().setxOffset(X_OFFSET); juego.getCamara().setyOffset(Y_OFFSET); seRealizoAccion = false; haySpellSeleccionada = false; if (miTurno) { if (juego.getHandlerMouse().getNuevoClick()) { posMouse = juego.getHandlerMouse().getPosMouse(); if (menuBatalla.clickEnMenu(posMouse[0], posMouse[1])) { if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == PRIMERHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadRaza1(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == SEGUNDAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadRaza2(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == TERCERAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta1(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == CUARTAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta2(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == QUINTAHABILIDAD) { if (personaje.puedeAtacar()) { seRealizoAccion = true; personaje.habilidadCasta3(enemigo); } haySpellSeleccionada = true; } if (menuBatalla.getBotonClickeado(posMouse[0], posMouse[1]) == SEXTAHABILIDAD) { seRealizoAccion = true; personaje.serEnergizado(CONSTANTE_ENERGIZANTE); haySpellSeleccionada = true; } } if (haySpellSeleccionada && seRealizoAccion) { if (!enemigo.estaVivo()) { juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_GANAR_BATALLA); if (personaje.ganarExperiencia(enemigo.getNivel() * CONSTANTEEXP)) { juego.getPersonaje().setNivel(personaje.getNivel()); juego.getEstadoJuego().setHaySolicitud(true, juego.getPersonaje(), MenuInfoPersonaje.MENU_SUBIR_NIVEL); // Actualiza los puntos del personaje. juego.getPersonaje().setPuntosSkill(personaje.getPuntosSkill() + PUNTOS_A_ASIGNAR); } paqueteFinalizarBatalla.setGanadorBatalla(juego.getPersonaje().getId()); finalizarBatalla(); Estado.setEstado(juego.getEstadoJuego()); } else { paqueteAtacar = new PaqueteAtacar(paquetePersonaje.getId(), paqueteEnemigo.getId(), personaje.getSalud(), personaje.getEnergia(), enemigo.getSalud(), enemigo.getEnergia(), personaje.getDefensa(), enemigo.getDefensa(), personaje.getCasta().getProbabilidadEvitarDaรฑo(), enemigo.getCasta().getProbabilidadEvitarDaรฑo()); enviarAtaque(paqueteAtacar); miTurno = false; menuBatalla.setHabilitado(false); } } else if (haySpellSeleccionada && !seRealizoAccion) { JOptionPane.showMessageDialog(null, "No posees la energรญa suficiente para realizar esta habilidad."); } juego.getHandlerMouse().setNuevoClick(false); } } } @Override public void graficar(final Graphics g) { g.setColor(Color.BLACK); g.fillRect(0, 0, juego.getAncho(), juego.getAlto()); mundo.graficar(g); g.drawImage(Recursos.getPersonaje().get(paquetePersonaje.getRaza()).get(PERSONAJEBUFFERESPALDA)[0] , X_PERSONAJE, Y_PERSONAJE, W_PERSONAJE, H_PERSONAJE, null); g.drawImage(Recursos.getPersonaje().get(paqueteEnemigo.getRaza()).get(ENEMIGOBUFFERFRENTE)[0] , X_ENEMIGO, Y_ENEMIGO, W_ENEMIGO, H_ENEMIGO, null); mundo.graficarObstaculos(g); menuBatalla.graficar(g); g.setColor(Color.GREEN); EstadoDePersonaje.dibujarEstadoDePersonaje(g, X_ESTADO_PJ, Y_ESTADO_PJ , personaje, miniaturaPersonaje); EstadoDePersonaje.dibujarEstadoDePersonaje(g, X_ESTADO_ENEMIGO, Y_ESTADO_ENEMIGO , enemigo, miniaturaEnemigo); } /** * Crear personajes. */ private void crearPersonajes() { String nombre = paquetePersonaje.getNombre(); int salud = paquetePersonaje.getSaludTope(); int energia = paquetePersonaje.getEnergiaTope(); int fuerza = paquetePersonaje.getFuerza(); int destreza = paquetePersonaje.getDestreza(); int inteligencia = paquetePersonaje.getInteligencia(); int experiencia = paquetePersonaje.getExperiencia(); int nivel = paquetePersonaje.getNivel(); int id = paquetePersonaje.getId(); Casta casta = null; try { casta = (Casta) Class.forName("dominio" + "." + paquetePersonaje.getCasta()).newInstance(); personaje = (Personaje) Class.forName("dominio" + "." + paquetePersonaje.getRaza()) .getConstructor(String.class, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE, Casta.class, Integer.TYPE, Integer.TYPE, Integer.TYPE) .newInstance(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { JOptionPane.showMessageDialog(null, "Error al crear la batalla"); } nombre = paqueteEnemigo.getNombre(); salud = paqueteEnemigo.getSaludTope(); energia = paqueteEnemigo.getEnergiaTope(); fuerza = paqueteEnemigo.getFuerza(); destreza = paqueteEnemigo.getDestreza(); inteligencia = paqueteEnemigo.getInteligencia(); experiencia = paqueteEnemigo.getExperiencia(); nivel = paqueteEnemigo.getNivel(); id = paqueteEnemigo.getId(); casta = null; if (paqueteEnemigo.getCasta().equals("Guerrero")) { casta = new Guerrero(); } else if (paqueteEnemigo.getCasta().equals("Hechicero")) { casta = new Hechicero(); } else if (paqueteEnemigo.getCasta().equals("Asesino")) { casta = new Asesino(); } if (paqueteEnemigo.getRaza().equals("Humano")) { enemigo = new Humano(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } else if (paqueteEnemigo.getRaza().equals("Orco")) { enemigo = new Orco(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } else if (paqueteEnemigo.getRaza().equals("Elfo")) { enemigo = new Elfo(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, id); } } /** * Enviar ataque. * * @param pAtacar * the paquete atacar */ public void enviarAtaque(final PaqueteAtacar pAtacar) { try { juego.getCliente().getSalida().writeObject(gson.toJson(pAtacar)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexion con el servidor."); } } /** * Finalizar batalla. */ private void finalizarBatalla() { try { juego.getCliente().getSalida().writeObject(gson.toJson(paqueteFinalizarBatalla)); paquetePersonaje.setSaludTope(personaje.getSaludTope()); paquetePersonaje.setEnergiaTope(personaje.getEnergiaTope()); paquetePersonaje.setNivel(personaje.getNivel()); paquetePersonaje.setExperiencia(personaje.getExperiencia()); paquetePersonaje.setDestreza(personaje.getDestreza()); paquetePersonaje.setFuerza(personaje.getFuerza()); paquetePersonaje.setInteligencia(personaje.getInteligencia()); paquetePersonaje.removerBonus(); paqueteEnemigo.setSaludTope(enemigo.getSaludTope()); paqueteEnemigo.setEnergiaTope(enemigo.getEnergiaTope()); paqueteEnemigo.setNivel(enemigo.getNivel()); paqueteEnemigo.setExperiencia(enemigo.getExperiencia()); paqueteEnemigo.setDestreza(enemigo.getDestreza()); paqueteEnemigo.setFuerza(enemigo.getFuerza()); paqueteEnemigo.setInteligencia(enemigo.getInteligencia()); paqueteEnemigo.removerBonus(); paquetePersonaje.setComando(Comando.ACTUALIZARPERSONAJE); paqueteEnemigo.setComando(Comando.ACTUALIZARPERSONAJE); juego.getCliente().getSalida().writeObject(gson.toJson(paquetePersonaje)); juego.getCliente().getSalida().writeObject(gson.toJson(paqueteEnemigo)); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Fallo la conexiรณn con el servidor"); } } /** * Gets the paquete personaje. * * @return the paquete personaje */ public PaquetePersonaje getPaquetePersonaje() { return paquetePersonaje; } /** * Gets the paquete enemigo. * * @return the paquete enemigo */ public PaquetePersonaje getPaqueteEnemigo() { return paqueteEnemigo; } /** * Sets the mi turno. * * @param b * the new mi turno */ public void setMiTurno(final boolean b) { miTurno = b; menuBatalla.setHabilitado(b); juego.getHandlerMouse().setNuevoClick(false); } /** * Gets the personaje. * * @return the personaje */ public Personaje getPersonaje() { return personaje; } /** * Gets the enemigo. * * @return the enemigo */ public Personaje getEnemigo() { return enemigo; } @Override public boolean esEstadoDeJuego() { return false; } }
Cambiado Daรฑo por Ataque en unos metodos de Casta
src/main/java/estados/EstadoBatalla.java
Cambiado Daรฑo por Ataque en unos metodos de Casta
Java
mit
81a82a47fb70333421ea58e3cfc9ffa838102654
0
cryptomator/siv-mode,cryptomator/siv-mode
package org.cryptomator.siv; /******************************************************************************* * Copyright (c) 2015 Sebastian Stenzel * This file is licensed under the terms of the MIT license. * See the LICENSE.txt file for more info. * * Contributors: * Sebastian Stenzel - initial API and implementation ******************************************************************************/ import java.security.InvalidKeyException; import javax.crypto.AEADBadTagException; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.junit.Assert; import org.junit.Test; /** * Official RFC 5297 test vector taken from https://tools.ietf.org/html/rfc5297#appendix-A.1 */ public class SivModeTest { @Test public void testS2v() { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] plaintext = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] expected = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93}; final byte[] result = new SivMode().s2v(macKey, plaintext, ad); Assert.assertArrayEquals(expected, result); } @Test public void testSivEncrypt() throws InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0xff}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] plaintext = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] expected = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] result = new SivMode().encrypt(aesKey, macKey, plaintext, ad); Assert.assertArrayEquals(expected, result); } @Test public void testSivDecrypt() throws AEADBadTagException, InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0xff}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] ciphertext = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] expected = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] result = new SivMode().decrypt(aesKey, macKey, ciphertext, ad); Assert.assertArrayEquals(expected, result); } @Test(expected = AEADBadTagException.class) public void testSivDecryptWithInvalidKey() throws AEADBadTagException, InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0x00}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] ciphertext = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] expected = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] result = new SivMode().decrypt(aesKey, macKey, ciphertext, ad); Assert.assertArrayEquals(expected, result); } /** * https://tools.ietf.org/html/rfc5297#appendix-A.2 */ @Test public void testNonceBasedAuthenticatedEncryption() throws InvalidKeyException { final byte[] macKey = {(byte) 0x7f, (byte) 0x7e, (byte) 0x7d, (byte) 0x7c, // (byte) 0x7b, (byte) 0x7a, (byte) 0x79, (byte) 0x78, // (byte) 0x77, (byte) 0x76, (byte) 0x75, (byte) 0x74, // (byte) 0x73, (byte) 0x72, (byte) 0x71, (byte) 0x70}; final byte[] aesKey = {(byte) 0x40, (byte) 0x41, (byte) 0x42, (byte) 0x43, // (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, // (byte) 0x48, (byte) 0x49, (byte) 0x4a, (byte) 0x4b, // (byte) 0x4c, (byte) 0x4d, (byte) 0x4e, (byte) 0x4f}; final byte[] ad1 = {(byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33, // (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77, // (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, // (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff, // (byte) 0xde, (byte) 0xad, (byte) 0xda, (byte) 0xda, // (byte) 0xde, (byte) 0xad, (byte) 0xda, (byte) 0xda, // (byte) 0xff, (byte) 0xee, (byte) 0xdd, (byte) 0xcc, // (byte) 0xbb, (byte) 0xaa, (byte) 0x99, (byte) 0x88, // (byte) 0x77, (byte) 0x66, (byte) 0x55, (byte) 0x44, // (byte) 0x33, (byte) 0x22, (byte) 0x11, (byte) 0x00}; final byte[] ad2 = {(byte) 0x10, (byte) 0x20, (byte) 0x30, (byte) 0x40, // (byte) 0x50, (byte) 0x60, (byte) 0x70, (byte) 0x80, // (byte) 0x90, (byte) 0xa0}; final byte[] nonce = {(byte) 0x09, (byte) 0xf9, (byte) 0x11, (byte) 0x02, // (byte) 0x9d, (byte) 0x74, (byte) 0xe3, (byte) 0x5b, // (byte) 0xd8, (byte) 0x41, (byte) 0x56, (byte) 0xc5, // (byte) 0x63, (byte) 0x56, (byte) 0x88, (byte) 0xc0}; final byte[] plaintext = {(byte) 0x74, (byte) 0x68, (byte) 0x69, (byte) 0x73, // (byte) 0x20, (byte) 0x69, (byte) 0x73, (byte) 0x20, // (byte) 0x73, (byte) 0x6f, (byte) 0x6d, (byte) 0x65, // (byte) 0x20, (byte) 0x70, (byte) 0x6c, (byte) 0x61, // (byte) 0x69, (byte) 0x6e, (byte) 0x74, (byte) 0x65, // (byte) 0x78, (byte) 0x74, (byte) 0x20, (byte) 0x74, // (byte) 0x6f, (byte) 0x20, (byte) 0x65, (byte) 0x6e, // (byte) 0x63, (byte) 0x72, (byte) 0x79, (byte) 0x70, // (byte) 0x74, (byte) 0x20, (byte) 0x75, (byte) 0x73, // (byte) 0x69, (byte) 0x6e, (byte) 0x67, (byte) 0x20, // (byte) 0x53, (byte) 0x49, (byte) 0x56, (byte) 0x2d, // (byte) 0x41, (byte) 0x45, (byte) 0x53}; final byte[] result = new SivMode().encrypt(aesKey, macKey, plaintext, ad1, ad2, nonce); final byte[] expected = {(byte) 0x7b, (byte) 0xdb, (byte) 0x6e, (byte) 0x3b, // (byte) 0x43, (byte) 0x26, (byte) 0x67, (byte) 0xeb, // (byte) 0x06, (byte) 0xf4, (byte) 0xd1, (byte) 0x4b, // (byte) 0xff, (byte) 0x2f, (byte) 0xbd, (byte) 0x0f, // (byte) 0xcb, (byte) 0x90, (byte) 0x0f, (byte) 0x2f, // (byte) 0xdd, (byte) 0xbe, (byte) 0x40, (byte) 0x43, // (byte) 0x26, (byte) 0x60, (byte) 0x19, (byte) 0x65, // (byte) 0xc8, (byte) 0x89, (byte) 0xbf, (byte) 0x17, // (byte) 0xdb, (byte) 0xa7, (byte) 0x7c, (byte) 0xeb, // (byte) 0x09, (byte) 0x4f, (byte) 0xa6, (byte) 0x63, // (byte) 0xb7, (byte) 0xa3, (byte) 0xf7, (byte) 0x48, // (byte) 0xba, (byte) 0x8a, (byte) 0xf8, (byte) 0x29, // (byte) 0xea, (byte) 0x64, (byte) 0xad, (byte) 0x54, // (byte) 0x4a, (byte) 0x27, (byte) 0x2e, (byte) 0x9c, // (byte) 0x48, (byte) 0x5b, (byte) 0x62, (byte) 0xa3, // (byte) 0xfd, (byte) 0x5c, (byte) 0x0d}; Assert.assertArrayEquals(expected, result); } @Test public void testEncryptionAndDecryptionUsingJavaxCryptoApi() throws AEADBadTagException { final byte[] dummyKey = new byte[16]; final SecretKey ctrKey = new SecretKeySpec(dummyKey, "AES"); final SecretKey macKey = new SecretKeySpec(dummyKey, "AES"); final SivMode sivMode = new SivMode(); final byte[] cleartext = "hello world".getBytes(); final byte[] ciphertext = sivMode.encrypt(ctrKey, macKey, cleartext); final byte[] decrypted = sivMode.decrypt(ctrKey, macKey, ciphertext); Assert.assertArrayEquals(cleartext, decrypted); } }
src/test/java/org/cryptomator/siv/SivModeTest.java
package org.cryptomator.siv; /******************************************************************************* * Copyright (c) 2015 Sebastian Stenzel * This file is licensed under the terms of the MIT license. * See the LICENSE.txt file for more info. * * Contributors: * Sebastian Stenzel - initial API and implementation ******************************************************************************/ import java.security.InvalidKeyException; import javax.crypto.AEADBadTagException; import org.junit.Assert; import org.junit.Test; /** * Official RFC 5297 test vector taken from https://tools.ietf.org/html/rfc5297#appendix-A.1 */ public class SivModeTest { @Test public void testS2v() { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] plaintext = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] expected = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93}; final byte[] result = new SivMode().s2v(macKey, plaintext, ad); Assert.assertArrayEquals(expected, result); } @Test public void testSivEncrypt() throws InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0xff}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] plaintext = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] expected = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] result = new SivMode().encrypt(aesKey, macKey, plaintext, ad); Assert.assertArrayEquals(expected, result); } @Test public void testSivDecrypt() throws AEADBadTagException, InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0xff}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] ciphertext = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] expected = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] result = new SivMode().decrypt(aesKey, macKey, ciphertext, ad); Assert.assertArrayEquals(expected, result); } @Test(expected = AEADBadTagException.class) public void testSivDecryptWithInvalidKey() throws AEADBadTagException, InvalidKeyException { final byte[] macKey = {(byte) 0xff, (byte) 0xfe, (byte) 0xfd, (byte) 0xfc, // (byte) 0xfb, (byte) 0xfa, (byte) 0xf9, (byte) 0xf8, // (byte) 0xf7, (byte) 0xf6, (byte) 0xf5, (byte) 0xf4, // (byte) 0xf3, (byte) 0xf2, (byte) 0xf1, (byte) 0xf0}; final byte[] aesKey = {(byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, // (byte) 0xf4, (byte) 0xf5, (byte) 0xf6, (byte) 0xf7, // (byte) 0xf8, (byte) 0xf9, (byte) 0xfa, (byte) 0xfb, // (byte) 0xfc, (byte) 0xfd, (byte) 0xfe, (byte) 0x00}; final byte[] ad = {(byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, // (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, // (byte) 0x18, (byte) 0x19, (byte) 0x1a, (byte) 0x1b, // (byte) 0x1c, (byte) 0x1d, (byte) 0x1e, (byte) 0x1f, // (byte) 0x20, (byte) 0x21, (byte) 0x22, (byte) 0x23, // (byte) 0x24, (byte) 0x25, (byte) 0x26, (byte) 0x27}; final byte[] ciphertext = {(byte) 0x85, (byte) 0x63, (byte) 0x2d, (byte) 0x07, // (byte) 0xc6, (byte) 0xe8, (byte) 0xf3, (byte) 0x7f, // (byte) 0x95, (byte) 0x0a, (byte) 0xcd, (byte) 0x32, // (byte) 0x0a, (byte) 0x2e, (byte) 0xcc, (byte) 0x93, // (byte) 0x40, (byte) 0xc0, (byte) 0x2b, (byte) 0x96, // (byte) 0x90, (byte) 0xc4, (byte) 0xdc, (byte) 0x04, // (byte) 0xda, (byte) 0xef, (byte) 0x7f, (byte) 0x6a, // (byte) 0xfe, (byte) 0x5c}; final byte[] expected = {(byte) 0x11, (byte) 0x22, (byte) 0x33, (byte) 0x44, // (byte) 0x55, (byte) 0x66, (byte) 0x77, (byte) 0x88, // (byte) 0x99, (byte) 0xaa, (byte) 0xbb, (byte) 0xcc, // (byte) 0xdd, (byte) 0xee}; final byte[] result = new SivMode().decrypt(aesKey, macKey, ciphertext, ad); Assert.assertArrayEquals(expected, result); } /** * https://tools.ietf.org/html/rfc5297#appendix-A.2 */ @Test public void testNonceBasedAuthenticatedEncryption() throws InvalidKeyException { final byte[] macKey = {(byte) 0x7f, (byte) 0x7e, (byte) 0x7d, (byte) 0x7c, // (byte) 0x7b, (byte) 0x7a, (byte) 0x79, (byte) 0x78, // (byte) 0x77, (byte) 0x76, (byte) 0x75, (byte) 0x74, // (byte) 0x73, (byte) 0x72, (byte) 0x71, (byte) 0x70}; final byte[] aesKey = {(byte) 0x40, (byte) 0x41, (byte) 0x42, (byte) 0x43, // (byte) 0x44, (byte) 0x45, (byte) 0x46, (byte) 0x47, // (byte) 0x48, (byte) 0x49, (byte) 0x4a, (byte) 0x4b, // (byte) 0x4c, (byte) 0x4d, (byte) 0x4e, (byte) 0x4f}; final byte[] ad1 = {(byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33, // (byte) 0x44, (byte) 0x55, (byte) 0x66, (byte) 0x77, // (byte) 0x88, (byte) 0x99, (byte) 0xaa, (byte) 0xbb, // (byte) 0xcc, (byte) 0xdd, (byte) 0xee, (byte) 0xff, // (byte) 0xde, (byte) 0xad, (byte) 0xda, (byte) 0xda, // (byte) 0xde, (byte) 0xad, (byte) 0xda, (byte) 0xda, // (byte) 0xff, (byte) 0xee, (byte) 0xdd, (byte) 0xcc, // (byte) 0xbb, (byte) 0xaa, (byte) 0x99, (byte) 0x88, // (byte) 0x77, (byte) 0x66, (byte) 0x55, (byte) 0x44, // (byte) 0x33, (byte) 0x22, (byte) 0x11, (byte) 0x00}; final byte[] ad2 = {(byte) 0x10, (byte) 0x20, (byte) 0x30, (byte) 0x40, // (byte) 0x50, (byte) 0x60, (byte) 0x70, (byte) 0x80, // (byte) 0x90, (byte) 0xa0}; final byte[] nonce = {(byte) 0x09, (byte) 0xf9, (byte) 0x11, (byte) 0x02, // (byte) 0x9d, (byte) 0x74, (byte) 0xe3, (byte) 0x5b, // (byte) 0xd8, (byte) 0x41, (byte) 0x56, (byte) 0xc5, // (byte) 0x63, (byte) 0x56, (byte) 0x88, (byte) 0xc0}; final byte[] plaintext = {(byte) 0x74, (byte) 0x68, (byte) 0x69, (byte) 0x73, // (byte) 0x20, (byte) 0x69, (byte) 0x73, (byte) 0x20, // (byte) 0x73, (byte) 0x6f, (byte) 0x6d, (byte) 0x65, // (byte) 0x20, (byte) 0x70, (byte) 0x6c, (byte) 0x61, // (byte) 0x69, (byte) 0x6e, (byte) 0x74, (byte) 0x65, // (byte) 0x78, (byte) 0x74, (byte) 0x20, (byte) 0x74, // (byte) 0x6f, (byte) 0x20, (byte) 0x65, (byte) 0x6e, // (byte) 0x63, (byte) 0x72, (byte) 0x79, (byte) 0x70, // (byte) 0x74, (byte) 0x20, (byte) 0x75, (byte) 0x73, // (byte) 0x69, (byte) 0x6e, (byte) 0x67, (byte) 0x20, // (byte) 0x53, (byte) 0x49, (byte) 0x56, (byte) 0x2d, // (byte) 0x41, (byte) 0x45, (byte) 0x53}; final byte[] result = new SivMode().encrypt(aesKey, macKey, plaintext, ad1, ad2, nonce); final byte[] expected = {(byte) 0x7b, (byte) 0xdb, (byte) 0x6e, (byte) 0x3b, // (byte) 0x43, (byte) 0x26, (byte) 0x67, (byte) 0xeb, // (byte) 0x06, (byte) 0xf4, (byte) 0xd1, (byte) 0x4b, // (byte) 0xff, (byte) 0x2f, (byte) 0xbd, (byte) 0x0f, // (byte) 0xcb, (byte) 0x90, (byte) 0x0f, (byte) 0x2f, // (byte) 0xdd, (byte) 0xbe, (byte) 0x40, (byte) 0x43, // (byte) 0x26, (byte) 0x60, (byte) 0x19, (byte) 0x65, // (byte) 0xc8, (byte) 0x89, (byte) 0xbf, (byte) 0x17, // (byte) 0xdb, (byte) 0xa7, (byte) 0x7c, (byte) 0xeb, // (byte) 0x09, (byte) 0x4f, (byte) 0xa6, (byte) 0x63, // (byte) 0xb7, (byte) 0xa3, (byte) 0xf7, (byte) 0x48, // (byte) 0xba, (byte) 0x8a, (byte) 0xf8, (byte) 0x29, // (byte) 0xea, (byte) 0x64, (byte) 0xad, (byte) 0x54, // (byte) 0x4a, (byte) 0x27, (byte) 0x2e, (byte) 0x9c, // (byte) 0x48, (byte) 0x5b, (byte) 0x62, (byte) 0xa3, // (byte) 0xfd, (byte) 0x5c, (byte) 0x0d}; Assert.assertArrayEquals(expected, result); } }
added unit test for javax.crypto API
src/test/java/org/cryptomator/siv/SivModeTest.java
added unit test for javax.crypto API
Java
mit
e25e126a00fead77de361873f3019b1ae9526ab7
0
wisthy/BeeBreedingManager
package be.shoktan.BeeBreedingManager.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import org.apache.commons.lang3.builder.CompareToBuilder; import org.hibernate.annotations.GenericGenerator; /** * Basic class to hold common methods for all the Entity * @author Wisthy * */ @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public abstract class ABaseEntity { @Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") private Long id; /** * @return the id */ public Long getId() { return id; } public int compareTo(ABaseEntity o) { return new CompareToBuilder().append(this.id, o.id) .toComparison(); } }
src/main/java/be/shoktan/BeeBreedingManager/model/ABaseEntity.java
package be.shoktan.BeeBreedingManager.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; /** * Basic class to hold common methods for all the Entity * @author Wisthy * */ @Entity @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public abstract class ABaseEntity { @Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") private Long id; /** * @return the id */ public Long getId() { return id; } }
Update ABaseEntity.java add compareTo() method
src/main/java/be/shoktan/BeeBreedingManager/model/ABaseEntity.java
Update ABaseEntity.java
Java
mit
353c6993621d8ed26fce31ef33f2e185825ccf71
0
zbeboy/ISY,zbeboy/ISY,zbeboy/ISY,zbeboy/ISY
package top.zbeboy.isy.web.graduate.design.reorder; import lombok.extern.slf4j.Slf4j; import org.jooq.Record; import org.jooq.Result; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import top.zbeboy.isy.config.Workbook; import top.zbeboy.isy.domain.tables.pojos.*; import top.zbeboy.isy.domain.tables.records.DefenseRateRecord; import top.zbeboy.isy.service.common.CommonControllerMethodService; import top.zbeboy.isy.service.data.StaffService; import top.zbeboy.isy.service.graduate.design.*; import top.zbeboy.isy.service.platform.RoleService; import top.zbeboy.isy.service.platform.UsersService; import top.zbeboy.isy.service.platform.UsersTypeService; import top.zbeboy.isy.service.util.DateTimeUtils; import top.zbeboy.isy.web.bean.error.ErrorBean; import top.zbeboy.isy.web.bean.graduate.design.reorder.DefenseRateBean; import top.zbeboy.isy.web.bean.graduate.design.replan.DefenseGroupBean; import top.zbeboy.isy.web.bean.graduate.design.replan.DefenseGroupMemberBean; import top.zbeboy.isy.web.util.AjaxUtils; import top.zbeboy.isy.web.vo.graduate.design.reorder.DefenseOrderVo; import javax.annotation.Resource; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; /** * Created by zbeboy on 2017/7/19. */ @Slf4j @Controller public class GraduationDesignReorderController { @Resource private GraduationDesignReleaseService graduationDesignReleaseService; @Resource private DefenseArrangementService defenseArrangementService; @Resource private DefenseTimeService defenseTimeService; @Resource private CommonControllerMethodService commonControllerMethodService; @Resource private DefenseGroupService defenseGroupService; @Resource private DefenseGroupMemberService defenseGroupMemberService; @Resource private DefenseOrderService defenseOrderService; @Resource private RoleService roleService; @Resource private UsersTypeService usersTypeService; @Resource private UsersService usersService; @Resource private GraduationDesignTeacherService graduationDesignTeacherService; @Resource private StaffService staffService; @Resource private DefenseRateService defenseRateService; /** * ๆฏ•ไธš็ญ”่พฉ้กบๅบ * * @return ๆฏ•ไธš็ญ”่พฉ้กบๅบ้กต้ข */ @RequestMapping(value = "/web/menu/graduate/design/reorder", method = RequestMethod.GET) public String reorder() { return "web/graduate/design/reorder/design_reorder::#page-wrapper"; } /** * ๆฏ•ไธš็ญ”่พฉๅฎ‰ๆŽ’ * * @return ๆฏ•ไธš็ญ”่พฉๅฎ‰ๆŽ’้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/arrange", method = RequestMethod.GET) public String arrange(@RequestParam("id") String graduationDesignReleaseId, ModelMap modelMap) { String page; ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { Optional<Record> record = defenseArrangementService.findByGraduationDesignReleaseId(graduationDesignReleaseId); if (record.isPresent()) { DefenseArrangement defenseArrangement = record.get().into(DefenseArrangement.class); Result<Record> defenseTimeRecord = defenseTimeService.findByDefenseArrangementId(defenseArrangement.getDefenseArrangementId()); List<DefenseTime> defenseTimes = defenseTimeRecord.into(DefenseTime.class); modelMap.addAttribute("defenseArrangement", defenseArrangement); modelMap.addAttribute("defenseTimes", defenseTimes); page = "web/graduate/design/reorder/design_reorder_arrange::#page-wrapper"; } else { page = commonControllerMethodService.showTip(modelMap, "ๆœช่ฟ›่กŒๆฏ•ไธš็ญ”่พฉ่ฎพ็ฝฎ"); } } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } return page; } /** * ๆฏ•ไธš่ฎพ่ฎก็ญ”่พฉ้กบๅบ * * @return ๆฏ•ไธš่ฎพ่ฎก็ญ”่พฉ้กบๅบ้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/order", method = RequestMethod.GET) public String orderLook(@RequestParam("id") String graduationDesignReleaseId, @RequestParam("defenseGroupId") String defenseGroupId, ModelMap modelMap) { String page; ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { // ๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ boolean reorderIsSuper = false; // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ˜ฏ็ง˜ไนฆ boolean reorderIsSecretary = false; // ๆ˜ฏ็ป„ๅ‘˜ boolean reorderIsMember = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { reorderIsSuper = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseGroupId); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { reorderIsLeader = true; } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseGroupId, graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { reorderIsMember = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { reorderIsSecretary = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { reorderIsSecretary = true; } } } } modelMap.addAttribute("reorderIsSuper", reorderIsSuper); modelMap.addAttribute("reorderIsLeader", reorderIsLeader); modelMap.addAttribute("reorderIsSecretary", reorderIsSecretary); modelMap.addAttribute("reorderIsMember", reorderIsMember); modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId); modelMap.addAttribute("defenseGroupId", defenseGroupId); page = "web/graduate/design/reorder/design_reorder_order::#page-wrapper"; } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } return page; } /** * ่ฎกๆ—ถ้กต้ข * * @param defenseOrderId ๅบๅทid * @param modelMap ้กต้ขๅฏน่ฑก * @return ้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/timer", method = RequestMethod.GET) public String timer(@RequestParam("defenseOrderId") String defenseOrderId, int timer, ModelMap modelMap) { String page; DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderId); if (!ObjectUtils.isEmpty(defenseOrder)) { modelMap.addAttribute("defenseOrder", defenseOrder); modelMap.addAttribute("timer", timer); page = "web/graduate/design/reorder/design_reorder_timer"; } else { modelMap.put("msg", "ๆœชๆŸฅ่ฏขๅˆฐ็ป„ไฟกๆฏ"); page = "msg"; } return page; } /** * ๆŸฅ่ฏข้กบๅบไฟกๆฏ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @param defenseOrderId ้กบๅบid * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils info(@RequestParam("id") String graduationDesignReleaseId, @RequestParam("defenseOrderId") String defenseOrderId) { AjaxUtils ajaxUtils = AjaxUtils.of(); ErrorBean<GraduationDesignRelease> errorBean = accessCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderId); if (!ObjectUtils.isEmpty(defenseOrder)) { ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ").obj(defenseOrder); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } return ajaxUtils; } /** * ๆ›ดๆ–ฐ็ญ”่พฉ้กบๅบ็Šถๆ€ * * @param defenseOrderVo ้กต้ขๅ‚ๆ•ฐ * @param bindingResult ๆฃ€้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/status", method = RequestMethod.POST) @ResponseBody public AjaxUtils status(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { Optional<Record> defenseArrangementRecord = defenseArrangementService.findByGraduationDesignReleaseId(defenseOrderVo.getGraduationDesignReleaseId()); if (defenseArrangementRecord.isPresent()) { DefenseArrangement defenseArrangement = defenseArrangementRecord.get().into(DefenseArrangement.class); // ็ญ”่พฉๅผ€ๅง‹ๆ—ถ้—ดไน‹ๅŽๅฏ็”จ if (DateTimeUtils.timestampAfterDecide(defenseArrangement.getDefenseStartTime())) { if (groupCondition(defenseOrderVo)) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setDefenseStatus(defenseOrderVo.getDefenseStatus()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ๆ›ดๆ–ฐ็Šถๆ€ๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆ›ดๆ”นๆกไปถ"); } } else { ajaxUtils.fail().msg("่ฏทๅœจ็ญ”่พฉๅผ€ๅง‹ไน‹ๅŽๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ่Žทๅ–ๅฝ“ๅ‰ๆ•™ๅธˆๆ‰“ๅˆ†ไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/grade/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils gradeInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { // ็ญ”่พฉ็Šถๆ€ไธบ ๅทฒ่ฟ›่กŒ if (!ObjectUtils.isEmpty(defenseOrder.getDefenseStatus()) && defenseOrder.getDefenseStatus() == 1) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); String graduationDesignTeacherId = null; if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; reorderIsLeader = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(defenseOrderVo.getGraduationDesignReleaseId(), staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseGroupId(), graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { canUse = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } } } if (canUse) { double grade = 0d; DefenseRateRecord defenseRateRecord = defenseRateService.findByDefenseOrderIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseOrderId(), graduationDesignTeacherId); if (!ObjectUtils.isEmpty(defenseRateRecord)) { grade = defenseRateRecord.getGrade(); } ajaxUtils.success().msg("่Žทๅ–ๅˆ†ๆ•ฐๆˆๅŠŸ").obj(grade); } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆŸฅ่ฏขๆกไปถ"); } } else { ajaxUtils.fail().msg("ๆœชๅผ€ๅง‹็ญ”่พฉ๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ๆ›ดๆ–ฐๅฝ“ๅ‰ๆ•™ๅธˆๆ‰“ๅˆ†ไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/grade", method = RequestMethod.POST) @ResponseBody public AjaxUtils grade(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { // ็ญ”่พฉ็Šถๆ€ไธบ ๅทฒ่ฟ›่กŒ if (!ObjectUtils.isEmpty(defenseOrder.getDefenseStatus()) && defenseOrder.getDefenseStatus() == 1) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); String graduationDesignTeacherId = null; if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; reorderIsLeader = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(defenseOrderVo.getGraduationDesignReleaseId(), staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseGroupId(), graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { canUse = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } } } if (canUse) { DefenseRate defenseRate; DefenseRateRecord defenseRateRecord = defenseRateService.findByDefenseOrderIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseOrderId(), graduationDesignTeacherId); if (!ObjectUtils.isEmpty(defenseRateRecord)) { defenseRate = defenseRateRecord.into(DefenseRate.class); defenseRate.setGrade(defenseOrderVo.getGrade()); } else { defenseRate = new DefenseRate(); defenseRate.setDefenseOrderId(defenseOrderVo.getDefenseOrderId()); defenseRate.setGraduationDesignTeacherId(graduationDesignTeacherId); defenseRate.setGrade(defenseOrderVo.getGrade()); } defenseRateService.save(defenseRate); ajaxUtils.success().msg("ไฟๅญ˜ๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆ›ดๆ”นๆกไปถ"); } } else { ajaxUtils.fail().msg("ๆœชๅผ€ๅง‹็ญ”่พฉ๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ่Žทๅ–็ป„ๅŠ็ป„ๅ‘˜ไฟกๆฏ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/groups", method = RequestMethod.POST) @ResponseBody public AjaxUtils<DefenseGroupBean> groups(@RequestParam("id") String graduationDesignReleaseId) { AjaxUtils<DefenseGroupBean> ajaxUtils = AjaxUtils.of(); ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { List<DefenseGroupBean> defenseGroupBeens = defenseGroupService.findByGraduationDesignReleaseIdRelation(graduationDesignReleaseId); defenseGroupBeens.forEach(defenseGroupBean -> { List<String> memberName = new ArrayList<>(); List<DefenseGroupMemberBean> defenseGroupMemberBeens = defenseGroupMemberService.findByDefenseGroupIdForStaff(defenseGroupBean.getDefenseGroupId()); defenseGroupMemberBeens.forEach(defenseGroupMemberBean -> memberName.add(defenseGroupMemberBean.getStaffName()) ); defenseGroupBean.setMemberName(memberName); }); ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ๏ผ").listData(defenseGroupBeens); } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } return ajaxUtils; } /** * ๆŸฅ่ฏขๅ„ๆ•™ๅธˆๆ‰“ๅˆ†ๅŠๆˆ็ปฉไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆฃ€้ชŒ * @return ็ป“ๆžœ */ @RequestMapping(value = "/web/graduate/design/reorder/mark/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils<DefenseRateBean> markInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils<DefenseRateBean> ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { List<DefenseRateBean> defenseRateBeans = defenseRateService.findByDefenseOrderIdAndDefenseGroupId(defenseOrderVo.getDefenseOrderId(), defenseOrderVo.getDefenseGroupId()); ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ๏ผ").listData(defenseRateBeans).obj(defenseOrder); } else { ajaxUtils.fail().msg("ๆœช่Žทๅ–ๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ไฟฎๆ”นๆˆ็ปฉ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆฃ€้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/mark", method = RequestMethod.POST) @ResponseBody public AjaxUtils mark(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setScoreTypeId(defenseOrderVo.getScoreTypeId()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ไฟฎๆ”นๆˆ็ปฉๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœช่Žทๅ–ๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ้—ฎ้ข˜ๆกไปถ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/question/info", method = RequestMethod.GET) public String questionInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult, ModelMap modelMap) { String page; if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { modelMap.addAttribute("defenseOrder", defenseOrder); modelMap.addAttribute("defenseOrderVo", defenseOrderVo); if (groupCondition(defenseOrderVo)) { page = "web/graduate/design/reorder/design_reorder_question_edit::#page-wrapper"; } else { page = "web/graduate/design/reorder/design_reorder_question::#page-wrapper"; } } else { page = commonControllerMethodService.showTip(modelMap, "ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } } else { page = commonControllerMethodService.showTip(modelMap, "ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return page; } /** * ๆ›ดๆ–ฐ้—ฎ้ข˜ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/question", method = RequestMethod.POST) @ResponseBody public AjaxUtils question(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { // ๅˆคๆ–ญ่ต„ๆ ผ if (groupCondition(defenseOrderVo)) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setDefenseQuestion(defenseOrderVo.getDefenseQuestion()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ๆ›ดๆ–ฐๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg("ไธ็ฌฆๅˆ็ผ–่พ‘ๆกไปถ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ็ป„ๆกไปถ * * @param defenseOrderVo ๆ•ฐๆฎ * @return true or false */ private boolean groupCondition(DefenseOrderVo defenseOrderVo) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { canUse = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } } } return canUse; } /** * ่ฟ›ๅ…ฅๅ…ฅๅฃๆกไปถ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @return true or false */ private ErrorBean<GraduationDesignRelease> accessCondition(String graduationDesignReleaseId) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { GraduationDesignRelease graduationDesignRelease = errorBean.getData(); // ๆฏ•ไธšๆ—ถ้—ด่Œƒๅ›ด if (DateTimeUtils.timestampRangeDecide(graduationDesignRelease.getStartTime(), graduationDesignRelease.getEndTime())) { errorBean.setHasError(false); } else { errorBean.setHasError(true); errorBean.setErrorMsg("ไธๅœจๆฏ•ไธšๆ—ถ้—ด่Œƒๅ›ด๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } return errorBean; } }
src/main/java/top/zbeboy/isy/web/graduate/design/reorder/GraduationDesignReorderController.java
package top.zbeboy.isy.web.graduate.design.reorder; import lombok.extern.slf4j.Slf4j; import org.jooq.Record; import org.jooq.Result; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import top.zbeboy.isy.config.Workbook; import top.zbeboy.isy.domain.tables.pojos.*; import top.zbeboy.isy.domain.tables.records.DefenseRateRecord; import top.zbeboy.isy.service.common.CommonControllerMethodService; import top.zbeboy.isy.service.data.StaffService; import top.zbeboy.isy.service.graduate.design.*; import top.zbeboy.isy.service.platform.RoleService; import top.zbeboy.isy.service.platform.UsersService; import top.zbeboy.isy.service.platform.UsersTypeService; import top.zbeboy.isy.service.util.DateTimeUtils; import top.zbeboy.isy.web.bean.error.ErrorBean; import top.zbeboy.isy.web.bean.graduate.design.reorder.DefenseRateBean; import top.zbeboy.isy.web.bean.graduate.design.replan.DefenseGroupBean; import top.zbeboy.isy.web.bean.graduate.design.replan.DefenseGroupMemberBean; import top.zbeboy.isy.web.util.AjaxUtils; import top.zbeboy.isy.web.vo.graduate.design.reorder.DefenseOrderVo; import javax.annotation.Resource; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Optional; /** * Created by zbeboy on 2017/7/19. */ @Slf4j @Controller public class GraduationDesignReorderController { @Resource private GraduationDesignReleaseService graduationDesignReleaseService; @Resource private DefenseArrangementService defenseArrangementService; @Resource private DefenseTimeService defenseTimeService; @Resource private CommonControllerMethodService commonControllerMethodService; @Resource private DefenseGroupService defenseGroupService; @Resource private DefenseGroupMemberService defenseGroupMemberService; @Resource private DefenseOrderService defenseOrderService; @Resource private RoleService roleService; @Resource private UsersTypeService usersTypeService; @Resource private UsersService usersService; @Resource private GraduationDesignTeacherService graduationDesignTeacherService; @Resource private StaffService staffService; @Resource private DefenseRateService defenseRateService; /** * ๆฏ•ไธš็ญ”่พฉ้กบๅบ * * @return ๆฏ•ไธš็ญ”่พฉ้กบๅบ้กต้ข */ @RequestMapping(value = "/web/menu/graduate/design/reorder", method = RequestMethod.GET) public String reorder() { return "web/graduate/design/reorder/design_reorder::#page-wrapper"; } /** * ๆฏ•ไธš็ญ”่พฉๅฎ‰ๆŽ’ * * @return ๆฏ•ไธš็ญ”่พฉๅฎ‰ๆŽ’้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/arrange", method = RequestMethod.GET) public String arrange(@RequestParam("id") String graduationDesignReleaseId, ModelMap modelMap) { String page; ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { Optional<Record> record = defenseArrangementService.findByGraduationDesignReleaseId(graduationDesignReleaseId); if (record.isPresent()) { DefenseArrangement defenseArrangement = record.get().into(DefenseArrangement.class); Result<Record> defenseTimeRecord = defenseTimeService.findByDefenseArrangementId(defenseArrangement.getDefenseArrangementId()); List<DefenseTime> defenseTimes = defenseTimeRecord.into(DefenseTime.class); modelMap.addAttribute("defenseArrangement", defenseArrangement); modelMap.addAttribute("defenseTimes", defenseTimes); page = "web/graduate/design/reorder/design_reorder_arrange::#page-wrapper"; } else { page = commonControllerMethodService.showTip(modelMap, "ๆœช่ฟ›่กŒๆฏ•ไธš็ญ”่พฉ่ฎพ็ฝฎ"); } } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } return page; } /** * ๆฏ•ไธš่ฎพ่ฎก็ญ”่พฉ้กบๅบ * * @return ๆฏ•ไธš่ฎพ่ฎก็ญ”่พฉ้กบๅบ้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/order", method = RequestMethod.GET) public String orderLook(@RequestParam("id") String graduationDesignReleaseId, @RequestParam("defenseGroupId") String defenseGroupId, ModelMap modelMap) { String page; ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { // ๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ boolean reorderIsSuper = false; // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ˜ฏ็ง˜ไนฆ boolean reorderIsSecretary = false; // ๆ˜ฏ็ป„ๅ‘˜ boolean reorderIsMember = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { reorderIsSuper = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseGroupId); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { reorderIsLeader = true; } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId, staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseGroupId, graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { reorderIsMember = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { reorderIsSecretary = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { reorderIsSecretary = true; } } } } modelMap.addAttribute("reorderIsSuper", reorderIsSuper); modelMap.addAttribute("reorderIsLeader", reorderIsLeader); modelMap.addAttribute("reorderIsSecretary", reorderIsSecretary); modelMap.addAttribute("reorderIsMember", reorderIsMember); modelMap.addAttribute("graduationDesignReleaseId", graduationDesignReleaseId); modelMap.addAttribute("defenseGroupId", defenseGroupId); page = "web/graduate/design/reorder/design_reorder_order::#page-wrapper"; } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } return page; } /** * ่ฎกๆ—ถ้กต้ข * * @param defenseOrderId ๅบๅทid * @param modelMap ้กต้ขๅฏน่ฑก * @return ้กต้ข */ @RequestMapping(value = "/web/graduate/design/reorder/timer", method = RequestMethod.GET) public String timer(@RequestParam("defenseOrderId") String defenseOrderId, int timer, ModelMap modelMap) { String page; DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderId); if (!ObjectUtils.isEmpty(defenseOrder)) { modelMap.addAttribute("defenseOrder", defenseOrder); modelMap.addAttribute("timer", timer); page = "web/graduate/design/reorder/design_reorder_timer"; } else { modelMap.put("msg", "ๆœชๆŸฅ่ฏขๅˆฐ็ป„ไฟกๆฏ"); page = "msg"; } return page; } /** * ๆŸฅ่ฏข้กบๅบไฟกๆฏ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @param defenseOrderId ้กบๅบid * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils info(@RequestParam("id") String graduationDesignReleaseId, @RequestParam("defenseOrderId") String defenseOrderId) { AjaxUtils ajaxUtils = AjaxUtils.of(); ErrorBean<GraduationDesignRelease> errorBean = accessCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderId); if (!ObjectUtils.isEmpty(defenseOrder)) { ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ").obj(defenseOrder); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } return ajaxUtils; } /** * ๆ›ดๆ–ฐ็ญ”่พฉ้กบๅบ็Šถๆ€ * * @param defenseOrderVo ้กต้ขๅ‚ๆ•ฐ * @param bindingResult ๆฃ€้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/status", method = RequestMethod.POST) @ResponseBody public AjaxUtils status(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { Optional<Record> defenseArrangementRecord = defenseArrangementService.findByGraduationDesignReleaseId(defenseOrderVo.getGraduationDesignReleaseId()); if (defenseArrangementRecord.isPresent()) { DefenseArrangement defenseArrangement = defenseArrangementRecord.get().into(DefenseArrangement.class); // ็ญ”่พฉๅผ€ๅง‹ๆ—ถ้—ดไน‹ๅŽๅฏ็”จ if (DateTimeUtils.timestampAfterDecide(defenseArrangement.getDefenseStartTime())) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { canUse = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } } } if (canUse) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setDefenseStatus(defenseOrderVo.getDefenseStatus()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ๆ›ดๆ–ฐ็Šถๆ€ๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆ›ดๆ”นๆกไปถ"); } } else { ajaxUtils.fail().msg("่ฏทๅœจ็ญ”่พฉๅผ€ๅง‹ไน‹ๅŽๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ่Žทๅ–ๅฝ“ๅ‰ๆ•™ๅธˆๆ‰“ๅˆ†ไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/grade/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils gradeInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { // ็ญ”่พฉ็Šถๆ€ไธบ ๅทฒ่ฟ›่กŒ if (!ObjectUtils.isEmpty(defenseOrder.getDefenseStatus()) && defenseOrder.getDefenseStatus() == 1) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); String graduationDesignTeacherId = null; if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; reorderIsLeader = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(defenseOrderVo.getGraduationDesignReleaseId(), staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseGroupId(), graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { canUse = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } } } if (canUse) { double grade = 0d; DefenseRateRecord defenseRateRecord = defenseRateService.findByDefenseOrderIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseOrderId(), graduationDesignTeacherId); if (!ObjectUtils.isEmpty(defenseRateRecord)) { grade = defenseRateRecord.getGrade(); } ajaxUtils.success().msg("่Žทๅ–ๅˆ†ๆ•ฐๆˆๅŠŸ").obj(grade); } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆŸฅ่ฏขๆกไปถ"); } } else { ajaxUtils.fail().msg("ๆœชๅผ€ๅง‹็ญ”่พฉ๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ๆ›ดๆ–ฐๅฝ“ๅ‰ๆ•™ๅธˆๆ‰“ๅˆ†ไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/grade", method = RequestMethod.POST) @ResponseBody public AjaxUtils grade(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = accessCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { // ็ญ”่พฉ็Šถๆ€ไธบ ๅทฒ่ฟ›่กŒ if (!ObjectUtils.isEmpty(defenseOrder.getDefenseStatus()) && defenseOrder.getDefenseStatus() == 1) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); String graduationDesignTeacherId = null; if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ˜ฏ็ป„้•ฟ boolean reorderIsLeader = false; // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; reorderIsLeader = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } // ๆ˜ฏๅฆไธบ็ป„ๅ‘˜ if (!reorderIsLeader) { if (!ObjectUtils.isEmpty(staff)) { Optional<Record> record = graduationDesignTeacherService.findByGraduationDesignReleaseIdAndStaffId(defenseOrderVo.getGraduationDesignReleaseId(), staff.getStaffId()); if (record.isPresent()) { GraduationDesignTeacher graduationDesignTeacher = record.get().into(GraduationDesignTeacher.class); Optional<Record> groupMemberRecord = defenseGroupMemberService.findByDefenseGroupIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseGroupId(), graduationDesignTeacher.getGraduationDesignTeacherId()); if (groupMemberRecord.isPresent()) { canUse = true; graduationDesignTeacherId = graduationDesignTeacher.getGraduationDesignTeacherId(); } } } } } } if (canUse) { DefenseRate defenseRate; DefenseRateRecord defenseRateRecord = defenseRateService.findByDefenseOrderIdAndGraduationDesignTeacherId(defenseOrderVo.getDefenseOrderId(), graduationDesignTeacherId); if (!ObjectUtils.isEmpty(defenseRateRecord)) { defenseRate = defenseRateRecord.into(DefenseRate.class); defenseRate.setGrade(defenseOrderVo.getGrade()); } else { defenseRate = new DefenseRate(); defenseRate.setDefenseOrderId(defenseOrderVo.getDefenseOrderId()); defenseRate.setGraduationDesignTeacherId(graduationDesignTeacherId); defenseRate.setGrade(defenseOrderVo.getGrade()); } defenseRateService.save(defenseRate); ajaxUtils.success().msg("ไฟๅญ˜ๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆ‚จไธ็ฌฆๅˆๆ›ดๆ”นๆกไปถ"); } } else { ajaxUtils.fail().msg("ๆœชๅผ€ๅง‹็ญ”่พฉ๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ็ญ”่พฉ่ฎพ็ฝฎ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ่Žทๅ–็ป„ๅŠ็ป„ๅ‘˜ไฟกๆฏ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @return ๆ•ฐๆฎ */ @RequestMapping(value = "/web/graduate/design/reorder/groups", method = RequestMethod.POST) @ResponseBody public AjaxUtils<DefenseGroupBean> groups(@RequestParam("id") String graduationDesignReleaseId) { AjaxUtils<DefenseGroupBean> ajaxUtils = AjaxUtils.of(); ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { List<DefenseGroupBean> defenseGroupBeens = defenseGroupService.findByGraduationDesignReleaseIdRelation(graduationDesignReleaseId); defenseGroupBeens.forEach(defenseGroupBean -> { List<String> memberName = new ArrayList<>(); List<DefenseGroupMemberBean> defenseGroupMemberBeens = defenseGroupMemberService.findByDefenseGroupIdForStaff(defenseGroupBean.getDefenseGroupId()); defenseGroupMemberBeens.forEach(defenseGroupMemberBean -> memberName.add(defenseGroupMemberBean.getStaffName()) ); defenseGroupBean.setMemberName(memberName); }); ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ๏ผ").listData(defenseGroupBeens); } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } return ajaxUtils; } /** * ๆŸฅ่ฏขๅ„ๆ•™ๅธˆๆ‰“ๅˆ†ๅŠๆˆ็ปฉไฟกๆฏ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆฃ€้ชŒ * @return ็ป“ๆžœ */ @RequestMapping(value = "/web/graduate/design/reorder/mark/info", method = RequestMethod.POST) @ResponseBody public AjaxUtils<DefenseRateBean> markInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils<DefenseRateBean> ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { List<DefenseRateBean> defenseRateBeans = defenseRateService.findByDefenseOrderIdAndDefenseGroupId(defenseOrderVo.getDefenseOrderId(), defenseOrderVo.getDefenseGroupId()); ajaxUtils.success().msg("่Žทๅ–ๆ•ฐๆฎๆˆๅŠŸ๏ผ").listData(defenseRateBeans).obj(defenseOrder); } else { ajaxUtils.fail().msg("ๆœช่Žทๅ–ๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ไฟฎๆ”นๆˆ็ปฉ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆฃ€้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/mark", method = RequestMethod.POST) @ResponseBody public AjaxUtils mark(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setScoreTypeId(defenseOrderVo.getScoreTypeId()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ไฟฎๆ”นๆˆ็ปฉๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœช่Žทๅ–ๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ้—ฎ้ข˜ๆกไปถ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/question/info", method = RequestMethod.GET) public String questionInfo(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult, ModelMap modelMap) { String page; if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { canUse = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } } } DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { modelMap.addAttribute("defenseOrder", defenseOrder); modelMap.addAttribute("defenseOrderVo", defenseOrderVo); if (canUse) { page = "web/graduate/design/reorder/design_reorder_question_edit::#page-wrapper"; } else { page = "web/graduate/design/reorder/design_reorder_question::#page-wrapper"; } } else { page = commonControllerMethodService.showTip(modelMap, "ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { page = commonControllerMethodService.showTip(modelMap, errorBean.getErrorMsg()); } } else { page = commonControllerMethodService.showTip(modelMap, "ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return page; } /** * ๆ›ดๆ–ฐ้—ฎ้ข˜ * * @param defenseOrderVo ๆ•ฐๆฎ * @param bindingResult ๆ ก้ชŒ * @return true or false */ @RequestMapping(value = "/web/graduate/design/reorder/question", method = RequestMethod.POST) @ResponseBody public AjaxUtils question(@Valid DefenseOrderVo defenseOrderVo, BindingResult bindingResult) { AjaxUtils ajaxUtils = AjaxUtils.of(); if (!bindingResult.hasErrors()) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(defenseOrderVo.getGraduationDesignReleaseId()); if (!errorBean.isHasError()) { // ๅˆคๆ–ญ่ต„ๆ ผ boolean canUse = false; // ๆ˜ฏๅฆๆ˜ฏ็ฎก็†ๅ‘˜ๆˆ–็ณป็ปŸ if (roleService.isCurrentUserInRole(Workbook.SYSTEM_AUTHORITIES) || roleService.isCurrentUserInRole(Workbook.ADMIN_AUTHORITIES)) { canUse = true; } else { Users users = usersService.getUserFromSession(); DefenseGroup defenseGroup = defenseGroupService.findById(defenseOrderVo.getDefenseGroupId()); if (!ObjectUtils.isEmpty(defenseGroup)) { // ๆ•™่Œๅทฅ if (usersTypeService.isCurrentUsersTypeName(Workbook.STAFF_USERS_TYPE)) { Staff staff = staffService.findByUsername(users.getUsername()); // ๆ˜ฏๅฆไธบ็ป„้•ฟ if (StringUtils.hasLength(defenseGroup.getLeaderId())) { GraduationDesignTeacher graduationDesignTeacher = graduationDesignTeacherService.findById(defenseGroup.getLeaderId()); if (!ObjectUtils.isEmpty(graduationDesignTeacher)) { if (!ObjectUtils.isEmpty(staff)) { if (Objects.equals(graduationDesignTeacher.getStaffId(), staff.getStaffId())) { canUse = true; } } } } // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } else if (usersTypeService.isCurrentUsersTypeName(Workbook.STUDENT_USERS_TYPE)) { // ๅญฆ็”Ÿ // ๆ˜ฏๅฆ็ง˜ไนฆ if (users.getUsername().equals(defenseGroup.getSecretaryId())) { canUse = true; } } } } if (canUse) { DefenseOrder defenseOrder = defenseOrderService.findById(defenseOrderVo.getDefenseOrderId()); if (!ObjectUtils.isEmpty(defenseOrder)) { defenseOrder.setDefenseQuestion(defenseOrderVo.getDefenseQuestion()); defenseOrderService.update(defenseOrder); ajaxUtils.success().msg("ๆ›ดๆ–ฐๆˆๅŠŸ"); } else { ajaxUtils.fail().msg("ๆœชๆŸฅ่ฏขๅˆฐ็›ธๅ…ณ้กบๅบ"); } } else { ajaxUtils.fail().msg("ไธ็ฌฆๅˆ็ผ–่พ‘ๆกไปถ"); } } else { ajaxUtils.fail().msg(errorBean.getErrorMsg()); } } else { ajaxUtils.fail().msg("ๅ‚ๆ•ฐๅผ‚ๅธธ"); } return ajaxUtils; } /** * ่ฟ›ๅ…ฅๅ…ฅๅฃๆกไปถ * * @param graduationDesignReleaseId ๆฏ•ไธš่ฎพ่ฎกๅ‘ๅธƒid * @return true or false */ private ErrorBean<GraduationDesignRelease> accessCondition(String graduationDesignReleaseId) { ErrorBean<GraduationDesignRelease> errorBean = graduationDesignReleaseService.basicCondition(graduationDesignReleaseId); if (!errorBean.isHasError()) { GraduationDesignRelease graduationDesignRelease = errorBean.getData(); // ๆฏ•ไธšๆ—ถ้—ด่Œƒๅ›ด if (DateTimeUtils.timestampRangeDecide(graduationDesignRelease.getStartTime(), graduationDesignRelease.getEndTime())) { errorBean.setHasError(false); } else { errorBean.setHasError(true); errorBean.setErrorMsg("ไธๅœจๆฏ•ไธšๆ—ถ้—ด่Œƒๅ›ด๏ผŒๆ— ๆณ•ๆ“ไฝœ"); } } return errorBean; } }
ๆฏ•ไธš่ฎพ่ฎก้กบๅบ้—ฎ้ข˜ๅฎŒๆˆ
src/main/java/top/zbeboy/isy/web/graduate/design/reorder/GraduationDesignReorderController.java
ๆฏ•ไธš่ฎพ่ฎก้กบๅบ้—ฎ้ข˜ๅฎŒๆˆ
Java
mpl-2.0
be54402b62b5deda6ca07500284a7d5e1f7f9669
0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: OTimeModel.java,v $ * * $Revision: 1.2 $ * * last change:$Date: 2003-05-27 12:46:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package mod._forms; import com.sun.star.beans.XPropertySet; import com.sun.star.lang.XMultiServiceFactory; import com.sun.star.drawing.XControlShape; import com.sun.star.drawing.XShape; import com.sun.star.form.XBoundComponent; import com.sun.star.form.XLoadable; import com.sun.star.sdbc.XResultSetUpdate; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.DBTools; import util.FormTools; import util.WriterTools; /** * Test for object which is represented by service * <code>com.sun.star.form.component.TimeField</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::awt::UnoControlTimeFieldModel</code></li> * <li> <code>com::sun::star::io::XPersistObject</code></li> * <li> <code>com::sun::star::form::component::TimeField</code></li> * <li> <code>com::sun::star::form::XReset</code></li> * <li> <code>com::sun::star::form::XBoundComponent</code></li> * <li> <code>com::sun::star::form::FormComponent</code></li> * <li> <code>com::sun::star::beans::XFastPropertySet</code></li> * <li> <code>com::sun::star::beans::XMultiPropertySet</code></li> * <li> <code>com::sun::star::form::XUpdateBroadcaster</code></li> * <li> <code>com::sun::star::form::DataAwareControlModel</code></li> * <li> <code>com::sun::star::beans::XPropertyState</code></li> * <li> <code>com::sun::star::form::FormControlModel</code></li> * <li> <code>com::sun::star::container::XNamed</code></li> * <li> <code>com::sun::star::lang::XComponent</code></li> * <li> <code>com::sun::star::lang::XEventListener</code></li> * <li> <code>com::sun::star::beans::XPropertySet</code></li> * <li> <code>com::sun::star::form::XLoadListener</code></li> * <li> <code>com::sun::star::container::XChild</code></li> * </ul> * The following files used by this test : * <ul> * <li><b> TestDB </b> (directory) : directory with test database </li> * <li><b> TestDB/TestDB.dbf </b> : table file. See * {@link util.DBTools DBTools} class for more information.</li> * </ul> <p> * This object test <b> is NOT </b> designed to be run in several * threads concurently. * @see com.sun.star.awt.UnoControlTimeFieldModel * @see com.sun.star.io.XPersistObject * @see com.sun.star.form.component.TimeField * @see com.sun.star.form.XReset * @see com.sun.star.form.XBoundComponent * @see com.sun.star.form.FormComponent * @see com.sun.star.beans.XFastPropertySet * @see com.sun.star.beans.XMultiPropertySet * @see com.sun.star.form.XUpdateBroadcaster * @see com.sun.star.form.DataAwareControlModel * @see com.sun.star.beans.XPropertyState * @see com.sun.star.form.FormControlModel * @see com.sun.star.container.XNamed * @see com.sun.star.lang.XComponent * @see com.sun.star.lang.XEventListener * @see com.sun.star.beans.XPropertySet * @see com.sun.star.form.XLoadListener * @see com.sun.star.container.XChild * @see ifc.awt._UnoControlTimeFieldModel * @see ifc.io._XPersistObject * @see ifc.form.component._TimeField * @see ifc.form._XReset * @see ifc.form._XBoundComponent * @see ifc.form._FormComponent * @see ifc.beans._XFastPropertySet * @see ifc.beans._XMultiPropertySet * @see ifc.form._XUpdateBroadcaster * @see ifc.form._DataAwareControlModel * @see ifc.beans._XPropertyState * @see ifc.form._FormControlModel * @see ifc.container._XNamed * @see ifc.lang._XComponent * @see ifc.lang._XEventListener * @see ifc.beans._XPropertySet * @see ifc.form._XLoadListener * @see ifc.container._XChild */ public class OTimeModel extends TestCase { XTextDocument xTextDoc; /** * Creates Writer document where controls are placed. */ protected void initialize( TestParameters tParam, PrintWriter log ) { log.println( "creating a textdocument" ); xTextDoc = WriterTools.createTextDoc((XMultiServiceFactory)tParam.getMSF()); } /** * Disposes Writer document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xTextDoc " ); xTextDoc.dispose(); } /** * Creating a Testenvironment for the interfaces to be tested. * First <code>TestDB</code> database is registered. * Creates Pattern field in the Form, then binds it to TestDB * database and returns Field's control. <p> * Object relations created : * <ul> * <li> <code>'OBJNAME'</code> for * {@link ifc.io._XPersistObject} : name of service which is * represented by this object. </li> * <li> <code>'LC'</code> for {@link ifc.form._DataAwareControlModel}. * Specifies the value for LabelControl property. It is * <code>FixedText</code> component added to the document.</li> * <li> <code>'FL'</code> for * {@link ifc.form._DataAwareControlModel} interface. * Specifies XLoadable implementation which connects form to * the data source.</li> * <li> <code>'XUpdateBroadcaster.Checker'</code> : <code> * _XUpdateBroadcaster.UpdateChecker</code> interface implementation * which can update, commit data and check if the data was successfully * commited.</li> * <li> <code>'DataAwareControlModel.NewFieldName'</code> : for * <code>com.sun.star.form.DataAwareControlModel</code> service * which contains new name of the field to bind control to. * </li> * <li> <code>'XFastPropertySet.ExcludeProps'</code> : for * <code>com.sun.star.beans.XFastPropertySet</code> interface * the property FormatKey can have only restricted set of values. * </li> * </ul> * @see ifc.form._XUpdateBroadcaster */ public synchronized TestEnvironment createTestEnvironment( TestParameters Param, PrintWriter log ) throws StatusException { XInterface oObj = null; XControlShape aShape = FormTools.createControlShape( xTextDoc,3000,4500,15000,10000,"TimeField"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); oObj = aShape.getControl(); XLoadable formLoader = null ; try { DBTools dbTools = new DBTools((XMultiServiceFactory)Param.getMSF()) ; dbTools.registerTestDB((String) System.getProperty("DOCPTH")) ; formLoader = FormTools.bindForm(xTextDoc, "APITestDatabase", "TestDB"); } catch (com.sun.star.uno.Exception e) { log.println("!!! Can't access TestDB !!!") ; e.printStackTrace(log) ; throw new StatusException("Can't access TestDB", e) ; } log.println( "creating a new environment for object" ); TestEnvironment tEnv = new TestEnvironment( oObj ); String objName = "TimeField"; tEnv.addObjRelation("OBJNAME", "stardiv.one.form.component." + objName); aShape = FormTools.createControlShape( xTextDoc,6000,4500,15000,10000,"FixedText"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); final XPropertySet ps = (XPropertySet)UnoRuntime.queryInterface (XPropertySet.class, oObj); try { ps.setPropertyValue("DataField", DBTools.TST_INT_F) ; } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.beans.PropertyVetoException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.beans.UnknownPropertyException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } // added LabelControl for 'DataAwareControlModel' tEnv.addObjRelation("LC",aShape.getControl()); // added FormLoader for 'DataAwareControlModel' tEnv.addObjRelation("FL",formLoader); // adding relation for XUpdateBroadcaster final XInterface ctrl = oObj ; final XLoadable formLoaderF = formLoader ; tEnv.addObjRelation("XUpdateBroadcaster.Checker", new ifc.form._XUpdateBroadcaster.UpdateChecker() { private int lastTime = 0 ; public void update() throws com.sun.star.uno.Exception { if (!formLoaderF.isLoaded()) { formLoaderF.load() ; } Integer time = (Integer)ps.getPropertyValue("Time") ; if (time != null) lastTime = time.intValue() + 150000 ; ps.setPropertyValue("Time", new Integer(lastTime)) ; } public void commit() throws com.sun.star.sdbc.SQLException { XBoundComponent bound = (XBoundComponent) UnoRuntime. queryInterface(XBoundComponent.class, ctrl) ; XResultSetUpdate update = (XResultSetUpdate) UnoRuntime. queryInterface(XResultSetUpdate.class, formLoaderF) ; bound.commit() ; update.updateRow() ; } public boolean wasCommited() throws com.sun.star.uno.Exception { formLoaderF.reload() ; Integer getT = (Integer) ps.getPropertyValue("Time") ; return getT != null && Math.abs(getT.intValue() - lastTime) < 100 ; } }) ; // adding relation for DataAwareControlModel service tEnv.addObjRelation("DataAwareControlModel.NewFieldName", DBTools.TST_INT_F) ; //adding ObjRelation for XPersistObject tEnv.addObjRelation("PSEUDOPERSISTENT", new Boolean(true)); // adding relation for XFastPropertySet java.util.HashSet exclude = new java.util.HashSet() ; exclude.add("FormatKey") ; tEnv.addObjRelation("XFastPropertySet.ExcludeProps", exclude); return tEnv; } // finish method getTestEnvironment } // finish class OTimeModel
qadevOOo/tests/java/mod/_forms/OTimeModel.java
/************************************************************************* * * $RCSfile: OTimeModel.java,v $ * * $Revision: 1.1 $ * * last change:$Date: 2003-01-27 18:14:59 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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 * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package mod._forms; import com.sun.star.beans.XPropertySet; import com.sun.star.drawing.XControlShape; import com.sun.star.drawing.XShape; import com.sun.star.form.XBoundComponent; import com.sun.star.form.XLoadable; import com.sun.star.sdbc.XResultSetUpdate; import com.sun.star.text.XTextDocument; import com.sun.star.uno.UnoRuntime; import com.sun.star.uno.XInterface; import java.io.PrintWriter; import lib.StatusException; import lib.TestCase; import lib.TestEnvironment; import lib.TestParameters; import util.DBTools; import util.FormTools; import util.WriterTools; /** * Test for object which is represented by service * <code>com.sun.star.form.component.TimeField</code>. <p> * Object implements the following interfaces : * <ul> * <li> <code>com::sun::star::awt::UnoControlTimeFieldModel</code></li> * <li> <code>com::sun::star::io::XPersistObject</code></li> * <li> <code>com::sun::star::form::component::TimeField</code></li> * <li> <code>com::sun::star::form::XReset</code></li> * <li> <code>com::sun::star::form::XBoundComponent</code></li> * <li> <code>com::sun::star::form::FormComponent</code></li> * <li> <code>com::sun::star::beans::XFastPropertySet</code></li> * <li> <code>com::sun::star::beans::XMultiPropertySet</code></li> * <li> <code>com::sun::star::form::XUpdateBroadcaster</code></li> * <li> <code>com::sun::star::form::DataAwareControlModel</code></li> * <li> <code>com::sun::star::beans::XPropertyState</code></li> * <li> <code>com::sun::star::form::FormControlModel</code></li> * <li> <code>com::sun::star::container::XNamed</code></li> * <li> <code>com::sun::star::lang::XComponent</code></li> * <li> <code>com::sun::star::lang::XEventListener</code></li> * <li> <code>com::sun::star::beans::XPropertySet</code></li> * <li> <code>com::sun::star::form::XLoadListener</code></li> * <li> <code>com::sun::star::container::XChild</code></li> * </ul> * The following files used by this test : * <ul> * <li><b> TestDB </b> (directory) : directory with test database </li> * <li><b> TestDB/TestDB.dbf </b> : table file. See * {@link util.DBTools DBTools} class for more information.</li> * </ul> <p> * This object test <b> is NOT </b> designed to be run in several * threads concurently. * @see com.sun.star.awt.UnoControlTimeFieldModel * @see com.sun.star.io.XPersistObject * @see com.sun.star.form.component.TimeField * @see com.sun.star.form.XReset * @see com.sun.star.form.XBoundComponent * @see com.sun.star.form.FormComponent * @see com.sun.star.beans.XFastPropertySet * @see com.sun.star.beans.XMultiPropertySet * @see com.sun.star.form.XUpdateBroadcaster * @see com.sun.star.form.DataAwareControlModel * @see com.sun.star.beans.XPropertyState * @see com.sun.star.form.FormControlModel * @see com.sun.star.container.XNamed * @see com.sun.star.lang.XComponent * @see com.sun.star.lang.XEventListener * @see com.sun.star.beans.XPropertySet * @see com.sun.star.form.XLoadListener * @see com.sun.star.container.XChild * @see ifc.awt._UnoControlTimeFieldModel * @see ifc.io._XPersistObject * @see ifc.form.component._TimeField * @see ifc.form._XReset * @see ifc.form._XBoundComponent * @see ifc.form._FormComponent * @see ifc.beans._XFastPropertySet * @see ifc.beans._XMultiPropertySet * @see ifc.form._XUpdateBroadcaster * @see ifc.form._DataAwareControlModel * @see ifc.beans._XPropertyState * @see ifc.form._FormControlModel * @see ifc.container._XNamed * @see ifc.lang._XComponent * @see ifc.lang._XEventListener * @see ifc.beans._XPropertySet * @see ifc.form._XLoadListener * @see ifc.container._XChild */ public class OTimeModel extends TestCase { XTextDocument xTextDoc; /** * Creates Writer document where controls are placed. */ protected void initialize( TestParameters tParam, PrintWriter log ) { log.println( "creating a textdocument" ); xTextDoc = WriterTools.createTextDoc(tParam.getMSF()); } /** * Disposes Writer document. */ protected void cleanup( TestParameters tParam, PrintWriter log ) { log.println( " disposing xTextDoc " ); xTextDoc.dispose(); } /** * Creating a Testenvironment for the interfaces to be tested. * First <code>TestDB</code> database is registered. * Creates Pattern field in the Form, then binds it to TestDB * database and returns Field's control. <p> * Object relations created : * <ul> * <li> <code>'OBJNAME'</code> for * {@link ifc.io._XPersistObject} : name of service which is * represented by this object. </li> * <li> <code>'LC'</code> for {@link ifc.form._DataAwareControlModel}. * Specifies the value for LabelControl property. It is * <code>FixedText</code> component added to the document.</li> * <li> <code>'FL'</code> for * {@link ifc.form._DataAwareControlModel} interface. * Specifies XLoadable implementation which connects form to * the data source.</li> * <li> <code>'XUpdateBroadcaster.Checker'</code> : <code> * _XUpdateBroadcaster.UpdateChecker</code> interface implementation * which can update, commit data and check if the data was successfully * commited.</li> * <li> <code>'DataAwareControlModel.NewFieldName'</code> : for * <code>com.sun.star.form.DataAwareControlModel</code> service * which contains new name of the field to bind control to. * </li> * <li> <code>'XFastPropertySet.ExcludeProps'</code> : for * <code>com.sun.star.beans.XFastPropertySet</code> interface * the property FormatKey can have only restricted set of values. * </li> * </ul> * @see ifc.form._XUpdateBroadcaster */ public synchronized TestEnvironment createTestEnvironment( TestParameters Param, PrintWriter log ) throws StatusException { XInterface oObj = null; XControlShape aShape = FormTools.createControlShape( xTextDoc,3000,4500,15000,10000,"TimeField"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); oObj = aShape.getControl(); XLoadable formLoader = null ; try { DBTools dbTools = new DBTools(Param.getMSF()) ; dbTools.registerTestDB((String) System.getProperty("DOCPTH")) ; formLoader = FormTools.bindForm(xTextDoc, "APITestDatabase", "TestDB"); } catch (com.sun.star.uno.Exception e) { log.println("!!! Can't access TestDB !!!") ; e.printStackTrace(log) ; throw new StatusException("Can't access TestDB", e) ; } log.println( "creating a new environment for object" ); TestEnvironment tEnv = new TestEnvironment( oObj ); String objName = "TimeField"; tEnv.addObjRelation("OBJNAME", "stardiv.one.form.component." + objName); aShape = FormTools.createControlShape( xTextDoc,6000,4500,15000,10000,"FixedText"); WriterTools.getDrawPage(xTextDoc).add((XShape) aShape); final XPropertySet ps = (XPropertySet)UnoRuntime.queryInterface (XPropertySet.class, oObj); try { ps.setPropertyValue("DataField", DBTools.TST_INT_F) ; } catch (com.sun.star.lang.WrappedTargetException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.lang.IllegalArgumentException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.beans.PropertyVetoException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } catch (com.sun.star.beans.UnknownPropertyException e) { e.printStackTrace( log ); throw new StatusException( "Couldn't set Default Date", e ); } // added LabelControl for 'DataAwareControlModel' tEnv.addObjRelation("LC",aShape.getControl()); // added FormLoader for 'DataAwareControlModel' tEnv.addObjRelation("FL",formLoader); // adding relation for XUpdateBroadcaster final XInterface ctrl = oObj ; final XLoadable formLoaderF = formLoader ; tEnv.addObjRelation("XUpdateBroadcaster.Checker", new ifc.form._XUpdateBroadcaster.UpdateChecker() { private int lastTime = 0 ; public void update() throws com.sun.star.uno.Exception { if (!formLoaderF.isLoaded()) { formLoaderF.load() ; } Integer time = (Integer)ps.getPropertyValue("Time") ; if (time != null) lastTime = time.intValue() + 150000 ; ps.setPropertyValue("Time", new Integer(lastTime)) ; } public void commit() throws com.sun.star.sdbc.SQLException { XBoundComponent bound = (XBoundComponent) UnoRuntime. queryInterface(XBoundComponent.class, ctrl) ; XResultSetUpdate update = (XResultSetUpdate) UnoRuntime. queryInterface(XResultSetUpdate.class, formLoaderF) ; bound.commit() ; update.updateRow() ; } public boolean wasCommited() throws com.sun.star.uno.Exception { formLoaderF.reload() ; Integer getT = (Integer) ps.getPropertyValue("Time") ; return getT != null && Math.abs(getT.intValue() - lastTime) < 100 ; } }) ; // adding relation for DataAwareControlModel service tEnv.addObjRelation("DataAwareControlModel.NewFieldName", DBTools.TST_INT_F) ; //adding ObjRelation for XPersistObject tEnv.addObjRelation("PSEUDOPERSISTENT", new Boolean(true)); // adding relation for XFastPropertySet java.util.HashSet exclude = new java.util.HashSet() ; exclude.add("FormatKey") ; tEnv.addObjRelation("XFastPropertySet.ExcludeProps", exclude); return tEnv; } // finish method getTestEnvironment } // finish class OTimeModel
INTEGRATION: CWS qadev6 (1.1.8); FILE MERGED 2003/05/21 10:56:02 sg 1.1.8.1: #109819# prepare devide of runner
qadevOOo/tests/java/mod/_forms/OTimeModel.java
INTEGRATION: CWS qadev6 (1.1.8); FILE MERGED 2003/05/21 10:56:02 sg 1.1.8.1: #109819# prepare devide of runner
Java
lgpl-2.1
a837a8e678a75e427b9e3c8b109f82170b54ba28
0
jolie/jolie,jolie/jolie,jolie/jolie
/*************************************************************************** * Copyright (C) by Fabrizio Montesi * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * For details about the authors of this software, see the AUTHORS file. * ***************************************************************************/ package joliex.db; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import jolie.runtime.ByteArray; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.embedding.RequestResponse; import joliex.db.impl.NamedStatementParser; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server * 2009 - Claudio Guidi: added support for SQLite */ @CanUseJars( { "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar", // Microsoft SQLServer "jdbc-sqlite.jar", // SQLite "jt400.jar" //AS400 } ) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private String driver = null; private boolean mustCheckConnection = false; private final Object transactionMutex = new Object(); private final static String templateField = "_template"; @Override protected void finalize() { if ( connection != null ) { try { connection.close(); } catch( SQLException e ) { } } } @RequestResponse public void connect( Value request ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) { } } mustCheckConnection = request.getFirstChild( "checkConnection" ).intValue() > 0; driver = request.getChildren( "driver" ).first().strValue(); String host = request.getChildren( "host" ).first().strValue(); String port = request.getChildren( "port" ).first().strValue(); String databaseName = request.getChildren( "database" ).first().strValue(); username = request.getChildren( "username" ).first().strValue(); password = request.getChildren( "password" ).first().strValue(); String attributes = request.getFirstChild( "attributes" ).strValue(); String separator = "/"; boolean isDerbyEmbedded = false; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlite".equals( driver ) ) { Class.forName( "org.sqlite.JDBC" ); } else if ( "sqlserver".equals( driver ) ) { Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else if ( "derby_embedded".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.EmbeddedDriver" ); isDerbyEmbedded = true; driver = "derby"; } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } if ( isDerbyEmbedded ) { connectionString = "jdbc:" + driver + ":" + databaseName; if ( !attributes.isEmpty() ) { connectionString += ";" + attributes; } connection = DriverManager.getConnection( connectionString ); } else { connectionString = "jdbc:" + driver + "://" + host + (port.equals( "" ) ? "" : ":" + port) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); } if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } } private void _checkConnection() throws FaultException { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } if ( mustCheckConnection ) { try { if ( "postgresql".equals( driver ) ) { /* The JDBC4 driver for postgresql does not implemented isValid(). * We fallback to isClosed(). */ if ( connection.isClosed() ) { connection = DriverManager.getConnection( connectionString, username, password ); } } else { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } } catch( SQLException e ) { throw createFaultException( e ); } } } @RequestResponse public void checkConnection() throws FaultException { try { if ( "postgresql".equals( driver ) ) { /* The JDBC4 driver for postgresql does not implemented isValid(). * We fallback to isClosed(). */ if ( connection == null || connection.isClosed() ) { throw new FaultException( "ConnectionError" ); } } else { if ( connection == null || !connection.isValid( 0 ) ) { throw new FaultException( "ConnectionError" ); } } } catch( SQLException e ) { throw new FaultException( "ConnectionError" ); } } @RequestResponse public Value update( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); PreparedStatement stm = null; try { synchronized( transactionMutex ) { stm = new NamedStatementParser( connection, request.strValue(), request ).getPreparedStatement(); resultValue.setValue( stm.executeUpdate() ); } } catch( SQLException e ) { throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { } } } return resultValue; } private static void setValue( Value fieldValue, ResultSet result, int columnType, int index ) throws SQLException { switch( columnType ) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: fieldValue.setValue( result.getInt( index ) ); break; case java.sql.Types.BIGINT: // TODO: to be changed when getting support for Long in Jolie. fieldValue.setValue( result.getInt( index ) ); break; case java.sql.Types.REAL: case java.sql.Types.DOUBLE: fieldValue.setValue( result.getDouble( index ) ); break; case java.sql.Types.DECIMAL: { BigDecimal dec = result.getBigDecimal( index ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } } break; case java.sql.Types.FLOAT: fieldValue.setValue( result.getFloat( index ) ); break; case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( index ); fieldValue.setValue( clob.getSubString( 0L, (int) clob.length() ) ); break; case java.sql.Types.BINARY: ByteArray supportByteArray = new ByteArray(result.getBytes(index)); fieldValue.setValue(supportByteArray ); break; case java.sql.Types.VARBINARY: supportByteArray = new ByteArray(result.getBytes(index)); fieldValue.setValue(supportByteArray ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: String s = result.getNString( index ); if ( s == null ) { s = ""; } fieldValue.setValue( s ); break; case java.sql.Types.NUMERIC: { BigDecimal dec = result.getBigDecimal( index ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } } break; case java.sql.Types.BIT: case java.sql.Types.BOOLEAN: { Boolean bool = result.getBoolean( index ); if ( bool == null ) { fieldValue.setValue( false ); } else { fieldValue.setValue( bool ); } } break; case java.sql.Types.VARCHAR: default: String str = result.getString( index ); if ( str == null ) { str = ""; } fieldValue.setValue( str ); break; } } private static void resultSetToValueVector( ResultSet result, ValueVector vector ) throws SQLException { Value rowValue, fieldValue; ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getFirstChild( metadata.getColumnLabel( i ) ); setValue( fieldValue, result, metadata.getColumnType( i ), i ); } rowIndex++; } } private static void _rowToValueWithTemplate( Value resultValue, ResultSet result, ResultSetMetaData metadata, Map< String, Integer > colIndexes, Value template ) throws SQLException { Value templateNode; Value resultChild; int colIndex; for( Entry< String, ValueVector > child : template.children().entrySet() ) { templateNode = template.getFirstChild( child.getKey() ); resultChild = resultValue.getFirstChild( child.getKey() ); if ( templateNode.isString() ) { colIndex = colIndexes.get( templateNode.strValue() ); setValue( resultChild, result, metadata.getColumnType( colIndex ), colIndex ); } _rowToValueWithTemplate( resultChild, result, metadata, colIndexes, templateNode ); } } private static void resultSetToValueVectorWithTemplate( ResultSet result, ValueVector vector, Value template ) throws SQLException { Value rowValue; ResultSetMetaData metadata = result.getMetaData(); Map< String, Integer > colIndexes = new HashMap< String, Integer >(); int cols = metadata.getColumnCount(); for( int i = 0; i < cols; i++ ) { colIndexes.put( metadata.getColumnName( i ), i ); } int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); _rowToValueWithTemplate( rowValue, result, metadata, colIndexes, template ); rowIndex++; } } @RequestResponse public Value executeTransaction( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); ValueVector resultVector = resultValue.getChildren( "result" ); synchronized( transactionMutex ) { try { connection.setAutoCommit( false ); } catch( SQLException e ) { throw createFaultException( e ); } Value currResultValue; PreparedStatement stm; int updateCount; for( Value statementValue : request.getChildren( "statement" ) ) { currResultValue = Value.create(); stm = null; try { updateCount = -1; stm = new NamedStatementParser( connection, statementValue.strValue(), statementValue ).getPreparedStatement(); if ( stm.execute() == true ) { updateCount = stm.getUpdateCount(); if ( updateCount == -1 ) { if ( statementValue.hasChildren( templateField ) ) { resultSetToValueVectorWithTemplate( stm.getResultSet(), currResultValue.getChildren( "row" ), statementValue.getFirstChild( templateField ) ); } else { resultSetToValueVector( stm.getResultSet(), currResultValue.getChildren( "row" ) ); } } } currResultValue.setValue( updateCount ); resultVector.add( currResultValue ); } catch( SQLException e ) { try { connection.rollback(); } catch( SQLException e1 ) { connection = null; } throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { throw createFaultException( e ); } } } } try { connection.commit(); } catch( SQLException e ) { throw createFaultException( e ); } finally { try { connection.setAutoCommit( true ); } catch( SQLException e ) { throw createFaultException( e ); } } } return resultValue; } static FaultException createFaultException( SQLException e ) { Value v = Value.create(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); e.printStackTrace( new PrintStream( bs ) ); v.getNewChild( "stackTrace" ).setValue( bs.toString() ); v.getNewChild( "errorCode" ).setValue( e.getErrorCode() ); v.getNewChild( "SQLState" ).setValue( e.getSQLState() ); v.getNewChild( "message" ).setValue( e.getMessage() ); return new FaultException( "SQLException", v ); } @RequestResponse public Value query( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); PreparedStatement stm = null; try { synchronized( transactionMutex ) { stm = new NamedStatementParser( connection, request.strValue(), request ).getPreparedStatement(); ResultSet result = stm.executeQuery(); if ( request.hasChildren( templateField ) ) { resultSetToValueVectorWithTemplate( result, resultValue.getChildren( "row" ), request.getFirstChild( templateField ) ); } else { resultSetToValueVector( result, resultValue.getChildren( "row" ) ); } result.close(); } } catch( SQLException e ) { throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { } } } return resultValue; } }
javaServices/coreJavaServices/src/joliex/db/DatabaseService.java
/*************************************************************************** * Copyright (C) by Fabrizio Montesi * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library 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 Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * * For details about the authors of this software, see the AUTHORS file. * ***************************************************************************/ package joliex.db; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.math.BigDecimal; import java.sql.Clob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import jolie.runtime.ByteArray; import jolie.runtime.CanUseJars; import jolie.runtime.FaultException; import jolie.runtime.JavaService; import jolie.runtime.Value; import jolie.runtime.ValueVector; import jolie.runtime.embedding.RequestResponse; import joliex.db.impl.NamedStatementParser; /** * @author Fabrizio Montesi * 2008 - Marco Montesi: connection string fix for Microsoft SQL Server * 2009 - Claudio Guidi: added support for SQLite */ @CanUseJars( { "derby.jar", // Java DB - Embedded "derbyclient.jar", // Java DB - Client "jdbc-mysql.jar", // MySQL "jdbc-postgresql.jar", // PostgreSQL "jdbc-sqlserver.jar", // Microsoft SQLServer "jdbc-sqlite.jar", // SQLite "jt400.jar" //AS400 } ) public class DatabaseService extends JavaService { private Connection connection = null; private String connectionString = null; private String username = null; private String password = null; private String driver = null; private boolean mustCheckConnection = false; private final Object transactionMutex = new Object(); private final static String templateField = "_template"; @Override protected void finalize() { if ( connection != null ) { try { connection.close(); } catch( SQLException e ) { } } } @RequestResponse public void connect( Value request ) throws FaultException { if ( connection != null ) { try { connectionString = null; username = null; password = null; connection.close(); } catch( SQLException e ) { } } mustCheckConnection = request.getFirstChild( "checkConnection" ).intValue() > 0; driver = request.getChildren( "driver" ).first().strValue(); String host = request.getChildren( "host" ).first().strValue(); String port = request.getChildren( "port" ).first().strValue(); String databaseName = request.getChildren( "database" ).first().strValue(); username = request.getChildren( "username" ).first().strValue(); password = request.getChildren( "password" ).first().strValue(); String attributes = request.getFirstChild( "attributes" ).strValue(); String separator = "/"; boolean isDerbyEmbedded = false; try { if ( "postgresql".equals( driver ) ) { Class.forName( "org.postgresql.Driver" ); } else if ( "mysql".equals( driver ) ) { Class.forName( "com.mysql.jdbc.Driver" ); } else if ( "derby".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.ClientDriver" ); } else if ( "sqlite".equals( driver ) ) { Class.forName( "org.sqlite.JDBC" ); } else if ( "sqlserver".equals( driver ) ) { Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" ); separator = ";"; databaseName = "databaseName=" + databaseName; } else if ( "as400".equals( driver ) ) { Class.forName( "com.ibm.as400.access.AS400JDBCDriver" ); } else if ( "derby_embedded".equals( driver ) ) { Class.forName( "org.apache.derby.jdbc.EmbeddedDriver" ); isDerbyEmbedded = true; driver = "derby"; } else { throw new FaultException( "InvalidDriver", "Uknown driver: " + driver ); } if ( isDerbyEmbedded ) { connectionString = "jdbc:" + driver + ":" + databaseName; if ( !attributes.isEmpty() ) { connectionString += ";" + attributes; } connection = DriverManager.getConnection( connectionString ); } else { connectionString = "jdbc:" + driver + "://" + host + (port.equals( "" ) ? "" : ":" + port) + separator + databaseName; connection = DriverManager.getConnection( connectionString, username, password ); } if ( connection == null ) { throw new FaultException( "ConnectionError" ); } } catch( ClassNotFoundException e ) { throw new FaultException( "InvalidDriver", e ); } catch( SQLException e ) { throw new FaultException( "ConnectionError", e ); } } private void _checkConnection() throws FaultException { if ( connection == null ) { throw new FaultException( "ConnectionError" ); } if ( mustCheckConnection ) { try { if ( "postgresql".equals( driver ) ) { /* The JDBC4 driver for postgresql does not implemented isValid(). * We fallback to isClosed(). */ if ( connection.isClosed() ) { connection = DriverManager.getConnection( connectionString, username, password ); } } else { if ( !connection.isValid( 0 ) ) { connection = DriverManager.getConnection( connectionString, username, password ); } } } catch( SQLException e ) { throw createFaultException( e ); } } } @RequestResponse public void checkConnection() throws FaultException { try { if ( "postgresql".equals( driver ) ) { /* The JDBC4 driver for postgresql does not implemented isValid(). * We fallback to isClosed(). */ if ( connection == null || connection.isClosed() ) { throw new FaultException( "ConnectionError" ); } } else { if ( connection == null || !connection.isValid( 0 ) ) { throw new FaultException( "ConnectionError" ); } } } catch( SQLException e ) { throw new FaultException( "ConnectionError" ); } } @RequestResponse public Value update( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); PreparedStatement stm = null; try { synchronized( transactionMutex ) { stm = new NamedStatementParser( connection, request.strValue(), request ).getPreparedStatement(); resultValue.setValue( stm.executeUpdate() ); } } catch( SQLException e ) { throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { } } } return resultValue; } private static void setValue( Value fieldValue, ResultSet result, int columnType, int index ) throws SQLException { switch( columnType ) { case java.sql.Types.INTEGER: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: fieldValue.setValue( result.getInt( index ) ); break; case java.sql.Types.BIGINT: // TODO: to be changed when getting support for Long in Jolie. fieldValue.setValue( result.getInt( index ) ); break; case java.sql.Types.DOUBLE: fieldValue.setValue( result.getDouble( index ) ); break; case java.sql.Types.DECIMAL: { BigDecimal dec = result.getBigDecimal( index ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } } break; case java.sql.Types.FLOAT: fieldValue.setValue( result.getFloat( index ) ); break; case java.sql.Types.BLOB: //fieldValue.setStrValue( result.getBlob( i ).toString() ); break; case java.sql.Types.CLOB: Clob clob = result.getClob( index ); fieldValue.setValue( clob.getSubString( 0L, (int) clob.length() ) ); break; case java.sql.Types.BINARY: ByteArray supportByteArray = new ByteArray(result.getBytes(index)); fieldValue.setValue(supportByteArray ); break; case java.sql.Types.VARBINARY: supportByteArray = new ByteArray(result.getBytes(index)); fieldValue.setValue(supportByteArray ); break; case java.sql.Types.NVARCHAR: case java.sql.Types.NCHAR: case java.sql.Types.LONGNVARCHAR: String s = result.getNString( index ); if ( s == null ) { s = ""; } fieldValue.setValue( s ); break; case java.sql.Types.NUMERIC: { BigDecimal dec = result.getBigDecimal( index ); if ( dec == null ) { fieldValue.setValue( 0 ); } else { if ( dec.scale() <= 0 ) { // May lose information. // Pay some attention to this when Long becomes supported by JOLIE. fieldValue.setValue( dec.intValue() ); } else if ( dec.scale() > 0 ) { fieldValue.setValue( dec.doubleValue() ); } } } break; case java.sql.Types.BIT: case java.sql.Types.BOOLEAN: { Boolean bool = result.getBoolean( index ); if ( bool == null ) { fieldValue.setValue( false ); } else { fieldValue.setValue( bool ); } } break; case java.sql.Types.VARCHAR: default: String str = result.getString( index ); if ( str == null ) { str = ""; } fieldValue.setValue( str ); break; } } private static void resultSetToValueVector( ResultSet result, ValueVector vector ) throws SQLException { Value rowValue, fieldValue; ResultSetMetaData metadata = result.getMetaData(); int cols = metadata.getColumnCount(); int i; int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); for( i = 1; i <= cols; i++ ) { fieldValue = rowValue.getFirstChild( metadata.getColumnLabel( i ) ); setValue( fieldValue, result, metadata.getColumnType( i ), i ); } rowIndex++; } } private static void _rowToValueWithTemplate( Value resultValue, ResultSet result, ResultSetMetaData metadata, Map< String, Integer > colIndexes, Value template ) throws SQLException { Value templateNode; Value resultChild; int colIndex; for( Entry< String, ValueVector > child : template.children().entrySet() ) { templateNode = template.getFirstChild( child.getKey() ); resultChild = resultValue.getFirstChild( child.getKey() ); if ( templateNode.isString() ) { colIndex = colIndexes.get( templateNode.strValue() ); setValue( resultChild, result, metadata.getColumnType( colIndex ), colIndex ); } _rowToValueWithTemplate( resultChild, result, metadata, colIndexes, templateNode ); } } private static void resultSetToValueVectorWithTemplate( ResultSet result, ValueVector vector, Value template ) throws SQLException { Value rowValue; ResultSetMetaData metadata = result.getMetaData(); Map< String, Integer > colIndexes = new HashMap< String, Integer >(); int cols = metadata.getColumnCount(); for( int i = 0; i < cols; i++ ) { colIndexes.put( metadata.getColumnName( i ), i ); } int rowIndex = 0; while( result.next() ) { rowValue = vector.get( rowIndex ); _rowToValueWithTemplate( rowValue, result, metadata, colIndexes, template ); rowIndex++; } } @RequestResponse public Value executeTransaction( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); ValueVector resultVector = resultValue.getChildren( "result" ); synchronized( transactionMutex ) { try { connection.setAutoCommit( false ); } catch( SQLException e ) { throw createFaultException( e ); } Value currResultValue; PreparedStatement stm; int updateCount; for( Value statementValue : request.getChildren( "statement" ) ) { currResultValue = Value.create(); stm = null; try { updateCount = -1; stm = new NamedStatementParser( connection, statementValue.strValue(), statementValue ).getPreparedStatement(); if ( stm.execute() == true ) { updateCount = stm.getUpdateCount(); if ( updateCount == -1 ) { if ( statementValue.hasChildren( templateField ) ) { resultSetToValueVectorWithTemplate( stm.getResultSet(), currResultValue.getChildren( "row" ), statementValue.getFirstChild( templateField ) ); } else { resultSetToValueVector( stm.getResultSet(), currResultValue.getChildren( "row" ) ); } } } currResultValue.setValue( updateCount ); resultVector.add( currResultValue ); } catch( SQLException e ) { try { connection.rollback(); } catch( SQLException e1 ) { connection = null; } throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { throw createFaultException( e ); } } } } try { connection.commit(); } catch( SQLException e ) { throw createFaultException( e ); } finally { try { connection.setAutoCommit( true ); } catch( SQLException e ) { throw createFaultException( e ); } } } return resultValue; } static FaultException createFaultException( SQLException e ) { Value v = Value.create(); ByteArrayOutputStream bs = new ByteArrayOutputStream(); e.printStackTrace( new PrintStream( bs ) ); v.getNewChild( "stackTrace" ).setValue( bs.toString() ); v.getNewChild( "errorCode" ).setValue( e.getErrorCode() ); v.getNewChild( "SQLState" ).setValue( e.getSQLState() ); v.getNewChild( "message" ).setValue( e.getMessage() ); return new FaultException( "SQLException", v ); } @RequestResponse public Value query( Value request ) throws FaultException { _checkConnection(); Value resultValue = Value.create(); PreparedStatement stm = null; try { synchronized( transactionMutex ) { stm = new NamedStatementParser( connection, request.strValue(), request ).getPreparedStatement(); ResultSet result = stm.executeQuery(); if ( request.hasChildren( templateField ) ) { resultSetToValueVectorWithTemplate( result, resultValue.getChildren( "row" ), request.getFirstChild( templateField ) ); } else { resultSetToValueVector( result, resultValue.getChildren( "row" ) ); } result.close(); } } catch( SQLException e ) { throw createFaultException( e ); } finally { if ( stm != null ) { try { stm.close(); } catch( SQLException e ) { } } } return resultValue; } }
added REAL case into switch of setValue method Former-commit-id: 5890a6b9726dc98b2a1fa1e0fdb24811d9c230bf
javaServices/coreJavaServices/src/joliex/db/DatabaseService.java
added REAL case into switch of setValue method
Java
lgpl-2.1
fce56851f8ecf0c2e9a9425947e92694613bb192
0
brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty,brltty/brltty
/* * BRLTTY - A background process providing access to the console screen (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2018 by The BRLTTY Developers. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed 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. Please see the file LICENSE-LGPL for details. * * Web Page: http://brltty.com/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brltty.android; import org.a11y.brltty.core.*; import android.util.Log; import android.view.ViewConfiguration; import android.os.Build; import android.os.Bundle; import android.accessibilityservice.AccessibilityService; import android.view.accessibility.AccessibilityNodeInfo; import android.inputmethodservice.InputMethodService; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.EditorInfo; import android.view.View; import android.view.KeyEvent; import android.text.Editable; import android.text.SpannableStringBuilder; public class InputService extends InputMethodService { private static final String LOG_TAG = InputService.class.getName(); private static volatile InputService inputService = null; public static InputService getInputService () { return inputService; } @Override public void onCreate () { super.onCreate(); ApplicationContext.set(this); inputService = this; Log.d(LOG_TAG, "input service started"); } @Override public void onDestroy () { try { inputService = null; Log.d(LOG_TAG, "input service stopped"); } finally { super.onDestroy(); } } @Override public void onBindInput () { Log.d(LOG_TAG, "input service bound"); } @Override public void onUnbindInput () { Log.d(LOG_TAG, "input service unbound"); } @Override public void onStartInput (EditorInfo info, boolean restarting) { Log.d(LOG_TAG, "input service " + (restarting? "reconnected": "connected")); if (info.actionLabel != null) Log.d(LOG_TAG, "action label: " + info.actionLabel); Log.d(LOG_TAG, "action id: " + info.actionId); } @Override public void onFinishInput () { Log.d(LOG_TAG, "input service disconnected"); } public static void logKeyEvent (int code, boolean press, String description) { if (ApplicationSettings.LOG_KEYBOARD_EVENTS) { StringBuilder sb = new StringBuilder(); sb.append("key "); sb.append((press? "press": "release")); sb.append(' '); sb.append(description); sb.append(": "); sb.append(code); if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.HONEYCOMB_MR1)) { sb.append(" ("); sb.append(KeyEvent.keyCodeToString(code)); sb.append(")"); } Log.d(LOG_TAG, sb.toString()); } } public static void logKeyEventReceived (int code, boolean press) { logKeyEvent(code, press, "received"); } public static void logKeyEventSent (int code, boolean press) { logKeyEvent(code, press, "sent"); } public native boolean handleKeyEvent (int code, boolean press); public void forwardKeyEvent (int code, boolean press) { InputConnection connection = getCurrentInputConnection(); if (connection != null) { int action = press? KeyEvent.ACTION_DOWN: KeyEvent.ACTION_UP; KeyEvent event = new KeyEvent(action, code); event = KeyEvent.changeFlags(event, KeyEvent.FLAG_SOFT_KEYBOARD); if (connection.sendKeyEvent(event)) { logKeyEvent(code, press, "forwarded"); } else { logKeyEvent(code, press, "not forwarded"); } } else { logKeyEvent(code, press, "unforwardable"); } } public boolean acceptKeyEvent (final int code, final boolean press) { switch (code) { case KeyEvent.KEYCODE_POWER: case KeyEvent.KEYCODE_HOME: case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_MENU: logKeyEvent(code, press, "rejected"); return false; default: logKeyEvent(code, press, "accepted"); break; } if (BrailleService.getBrailleService() == null) { Log.w(LOG_TAG, "braille service not started"); return false; } CoreWrapper.runOnCoreThread( new Runnable() { @Override public void run () { logKeyEvent(code, press, "delivered"); if (handleKeyEvent(code, press)) { logKeyEvent(code, press, "handled"); } else { forwardKeyEvent(code, press); } } } ); return true; } public static boolean isSystemKeyCode (int code) { switch (code) { case KeyEvent.KEYCODE_HOME: case KeyEvent.KEYCODE_BACK: return true; default: return false; } } @Override public boolean onKeyDown (int code, KeyEvent event) { logKeyEventReceived(code, true); if (!isSystemKeyCode(code)) { if (acceptKeyEvent(code, true)) { return true; } } return super.onKeyDown(code, event); } @Override public boolean onKeyUp (int code, KeyEvent event) { logKeyEventReceived(code, false); if (!isSystemKeyCode(code)) { if (acceptKeyEvent(code, false)) { return true; } } return super.onKeyUp(code, event); } interface Action { public boolean performAction (); } private final static Action brlttySettingsAction = new Action() { @Override public boolean performAction () { return BrailleService.getBrailleService().launchSettingsActivity(); } }; private static boolean performGlobalAction (int action) { return BrailleService.getBrailleService().performGlobalAction(action); } private final static Action backAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); } return false; } }; private final static Action homeAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME); } return false; } }; private final static Action notificationsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS); } return false; } }; private final static Action powerDialogAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.LOLLIPOP)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG); } return false; } }; private final static Action quickSettingsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN_MR1)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS); } return false; } }; private final static Action recentApplicationsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS); } return false; } }; public static boolean changeFocus (RenderedScreen.ChangeFocusDirection direction) { RenderedScreen screen = ScreenDriver.getScreen(); if (screen != null) { if (screen.changeFocus(direction)) { return true; } } return false; } private final static Action backwardAction = new Action() { @Override public boolean performAction () { return changeFocus(RenderedScreen.ChangeFocusDirection.BACKWARD); } }; private final static Action forwardAction = new Action() { @Override public boolean performAction () { return changeFocus(RenderedScreen.ChangeFocusDirection.FORWARD); } }; public static InputMethodInfo getInputMethodInfo (Class classObject) { String className = classObject.getName(); for (InputMethodInfo info : ApplicationUtilities.getInputMethodManager().getEnabledInputMethodList()) { if (info.getComponent().getClassName().equals(className)) { return info; } } return null; } public static InputMethodInfo getInputMethodInfo () { return getInputMethodInfo(InputService.class); } public static boolean isInputServiceEnabled () { return getInputMethodInfo() != null; } public static boolean isInputServiceSelected () { InputMethodInfo info = getInputMethodInfo(); if (info != null) { if (info.getId().equals(ApplicationUtilities.getSelectedInputMethodIdentifier())) { return true; } } return false; } public static InputConnection getInputConnection () { InputService service = InputService.getInputService(); if (service != null) { InputConnection connection = service.getCurrentInputConnection(); if (connection != null) { return connection; } else { Log.w(LOG_TAG, "input service not connected"); } } else if (!isInputServiceEnabled()) { Log.w(LOG_TAG, "input service not enabled"); } else if (!isInputServiceSelected()) { Log.w(LOG_TAG, "input service not selected"); } else { Log.w(LOG_TAG, "input service not started"); } if (!isInputServiceSelected()) { Log.w(LOG_TAG, "showing input method picker"); ApplicationUtilities.getInputMethodManager().showInputMethodPicker(); } return null; } public static boolean inputCursor (int position) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.setSelection(position, position)) { return true; } } return false; } public static boolean inputCharacter (final char character) { try { return new InputTextEditor() { @Override protected Integer performEdit (Editable editor, int start, int end) { editor.replace(start, end, Character.toString(character)); return start + 1; } }.wasPerformed(); } catch (UnsupportedOperationException exception) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.commitText(Character.toString(character), 1)) { return true; } } return false; } } public static boolean inputKey (int keyCode, boolean longPress) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode))) { logKeyEventSent(keyCode, true); if (longPress) { try { Thread.sleep(ViewConfiguration.getLongPressTimeout() + ApplicationParameters.LONG_PRESS_DELAY); } catch (InterruptedException exception) { } } if (connection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyCode))) { logKeyEventSent(keyCode, false); return true; } } } return false; } private final static Action menuAction = new Action() { @Override public boolean performAction () { return inputKey(KeyEvent.KEYCODE_MENU); } }; private final static Action logScreenAction = new Action() { @Override public boolean performAction () { ScreenLogger.log(); return true; } }; public static boolean inputKey (int keyCode) { return inputKey(keyCode, false); } public static boolean inputKey_enter () { return inputKey(KeyEvent.KEYCODE_ENTER); } public static boolean inputKey_tab () { return inputKey(KeyEvent.KEYCODE_TAB); } public static boolean inputKey_backspace () { try { return new InputTextEditor() { @Override protected Integer performEdit (Editable editor, int start, int end) { if (start == end) { if (start < 1) return null; start -= 1; } editor.delete(start, end); return start; } }.wasPerformed(); } catch (UnsupportedOperationException exception) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.deleteSurroundingText(1, 0)) { return true; } } return false; } } public static boolean inputKey_escape () { return inputKey(KeyEvent.KEYCODE_ESCAPE); } public static boolean inputKey_cursorLeft () { return inputKey(KeyEvent.KEYCODE_DPAD_LEFT); } public static boolean inputKey_cursorRight () { return inputKey(KeyEvent.KEYCODE_DPAD_RIGHT); } public static boolean inputKey_cursorUp () { return inputKey(KeyEvent.KEYCODE_DPAD_UP); } public static boolean inputKey_cursorDown () { return inputKey(KeyEvent.KEYCODE_DPAD_DOWN); } public static boolean inputKey_pageUp () { return inputKey(KeyEvent.KEYCODE_PAGE_UP); } public static boolean inputKey_pageDown () { return inputKey(KeyEvent.KEYCODE_PAGE_DOWN); } public static boolean inputKey_home () { return inputKey(KeyEvent.KEYCODE_MOVE_HOME); } public static boolean inputKey_end () { return inputKey(KeyEvent.KEYCODE_MOVE_END); } public static boolean inputKey_insert () { return inputKey(KeyEvent.KEYCODE_INSERT); } public static boolean inputKey_delete () { try { return new InputTextEditor() { @Override protected Integer performEdit (Editable editor, int start, int end) { if (start == end) { if (end == editor.length()) return null; end += 1; } editor.delete(start, end); return start; } }.wasPerformed(); } catch (UnsupportedOperationException exception) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.deleteSurroundingText(0, 1)) { return true; } } return false; } } private final static Action[] functionKeyActions = new Action[] { homeAction, backAction, notificationsAction, recentApplicationsAction, brlttySettingsAction, quickSettingsAction, backwardAction, forwardAction, powerDialogAction, menuAction, logScreenAction }; public static boolean inputKey_function (int key) { if (key < 0) return false; if (key >= functionKeyActions.length) return false; Action action = functionKeyActions[key]; if (action == null) return false; return action.performAction(); } }
Android/Application/src/org/a11y/brltty/android/InputService.java
/* * BRLTTY - A background process providing access to the console screen (when in * text mode) for a blind person using a refreshable braille display. * * Copyright (C) 1995-2018 by The BRLTTY Developers. * * BRLTTY comes with ABSOLUTELY NO WARRANTY. * * This is free software, placed 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. Please see the file LICENSE-LGPL for details. * * Web Page: http://brltty.com/ * * This software is maintained by Dave Mielke <[email protected]>. */ package org.a11y.brltty.android; import org.a11y.brltty.core.*; import android.util.Log; import android.view.ViewConfiguration; import android.os.Build; import android.os.Bundle; import android.accessibilityservice.AccessibilityService; import android.view.accessibility.AccessibilityNodeInfo; import android.inputmethodservice.InputMethodService; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.EditorInfo; import android.view.View; import android.view.KeyEvent; import android.text.Editable; import android.text.SpannableStringBuilder; public class InputService extends InputMethodService { private static final String LOG_TAG = InputService.class.getName(); private static volatile InputService inputService = null; public static InputService getInputService () { return inputService; } @Override public void onCreate () { super.onCreate(); ApplicationContext.set(this); inputService = this; Log.d(LOG_TAG, "input service started"); } @Override public void onDestroy () { try { inputService = null; Log.d(LOG_TAG, "input service stopped"); } finally { super.onDestroy(); } } @Override public void onBindInput () { Log.d(LOG_TAG, "input service bound"); } @Override public void onUnbindInput () { Log.d(LOG_TAG, "input service unbound"); } @Override public void onStartInput (EditorInfo info, boolean restarting) { Log.d(LOG_TAG, "input service " + (restarting? "reconnected": "connected")); if (info.actionLabel != null) Log.d(LOG_TAG, "action label: " + info.actionLabel); Log.d(LOG_TAG, "action id: " + info.actionId); } @Override public void onFinishInput () { Log.d(LOG_TAG, "input service disconnected"); } public static void logKeyEvent (int code, boolean press, String description) { if (ApplicationSettings.LOG_KEYBOARD_EVENTS) { StringBuilder sb = new StringBuilder(); sb.append("key "); sb.append((press? "press": "release")); sb.append(' '); sb.append(description); sb.append(": "); sb.append(code); if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.HONEYCOMB_MR1)) { sb.append(" ("); sb.append(KeyEvent.keyCodeToString(code)); sb.append(")"); } Log.d(LOG_TAG, sb.toString()); } } public static void logKeyEventReceived (int code, boolean press) { logKeyEvent(code, press, "received"); } public static void logKeyEventSent (int code, boolean press) { logKeyEvent(code, press, "sent"); } public native boolean handleKeyEvent (int code, boolean press); public void forwardKeyEvent (int code, boolean press) { InputConnection connection = getCurrentInputConnection(); if (connection != null) { int action = press? KeyEvent.ACTION_DOWN: KeyEvent.ACTION_UP; KeyEvent event = new KeyEvent(action, code); event = KeyEvent.changeFlags(event, KeyEvent.FLAG_SOFT_KEYBOARD); if (connection.sendKeyEvent(event)) { logKeyEvent(code, press, "forwarded"); } else { logKeyEvent(code, press, "not forwarded"); } } else { logKeyEvent(code, press, "unforwardable"); } } public boolean acceptKeyEvent (final int code, final boolean press) { switch (code) { case KeyEvent.KEYCODE_POWER: case KeyEvent.KEYCODE_HOME: case KeyEvent.KEYCODE_BACK: case KeyEvent.KEYCODE_MENU: logKeyEvent(code, press, "rejected"); return false; default: logKeyEvent(code, press, "accepted"); break; } if (BrailleService.getBrailleService() == null) { Log.w(LOG_TAG, "braille service not started"); return false; } CoreWrapper.runOnCoreThread( new Runnable() { @Override public void run () { logKeyEvent(code, press, "delivered"); if (handleKeyEvent(code, press)) { logKeyEvent(code, press, "handled"); } else { forwardKeyEvent(code, press); } } } ); return true; } public static boolean isSystemKeyCode (int code) { switch (code) { case KeyEvent.KEYCODE_HOME: case KeyEvent.KEYCODE_BACK: return true; default: return false; } } @Override public boolean onKeyDown (int code, KeyEvent event) { logKeyEventReceived(code, true); if (!isSystemKeyCode(code)) { if (acceptKeyEvent(code, true)) { return true; } } return super.onKeyDown(code, event); } @Override public boolean onKeyUp (int code, KeyEvent event) { logKeyEventReceived(code, false); if (!isSystemKeyCode(code)) { if (acceptKeyEvent(code, false)) { return true; } } return super.onKeyUp(code, event); } interface Action { public boolean performAction (); } private final static Action brlttySettingsAction = new Action() { @Override public boolean performAction () { return BrailleService.getBrailleService().launchSettingsActivity(); } }; private static boolean performGlobalAction (int action) { return BrailleService.getBrailleService().performGlobalAction(action); } private final static Action backAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK); } return false; } }; private final static Action homeAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME); } return false; } }; private final static Action notificationsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS); } return false; } }; private final static Action powerDialogAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.LOLLIPOP)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_POWER_DIALOG); } return false; } }; private final static Action quickSettingsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN_MR1)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_QUICK_SETTINGS); } return false; } }; private final static Action recentApplicationsAction = new Action() { @Override public boolean performAction () { if (ApplicationUtilities.haveSdkVersion(Build.VERSION_CODES.JELLY_BEAN)) { return performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS); } return false; } }; public static boolean changeFocus (RenderedScreen.ChangeFocusDirection direction) { RenderedScreen screen = ScreenDriver.getScreen(); if (screen != null) { if (screen.changeFocus(direction)) { return true; } } return false; } private final static Action backwardAction = new Action() { @Override public boolean performAction () { return changeFocus(RenderedScreen.ChangeFocusDirection.BACKWARD); } }; private final static Action forwardAction = new Action() { @Override public boolean performAction () { return changeFocus(RenderedScreen.ChangeFocusDirection.FORWARD); } }; public static InputMethodInfo getInputMethodInfo (Class classObject) { String className = classObject.getName(); for (InputMethodInfo info : ApplicationUtilities.getInputMethodManager().getEnabledInputMethodList()) { if (info.getComponent().getClassName().equals(className)) { return info; } } return null; } public static InputMethodInfo getInputMethodInfo () { return getInputMethodInfo(InputService.class); } public static boolean isInputServiceEnabled () { return getInputMethodInfo() != null; } public static boolean isInputServiceSelected () { InputMethodInfo info = getInputMethodInfo(); if (info != null) { if (info.getId().equals(ApplicationUtilities.getSelectedInputMethodIdentifier())) { return true; } } return false; } public static InputConnection getInputConnection () { InputService service = InputService.getInputService(); if (service != null) { InputConnection connection = service.getCurrentInputConnection(); if (connection != null) { return connection; } else { Log.w(LOG_TAG, "input service not connected"); } } else if (!isInputServiceEnabled()) { Log.w(LOG_TAG, "input service not enabled"); } else if (!isInputServiceSelected()) { Log.w(LOG_TAG, "input service not selected"); } else { Log.w(LOG_TAG, "input service not started"); } if (!isInputServiceSelected()) { Log.w(LOG_TAG, "showing input method picker"); ApplicationUtilities.getInputMethodManager().showInputMethodPicker(); } return null; } public static boolean inputCursor (int position) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.setSelection(position, position)) { return true; } } return false; } public static boolean inputCharacter (final char character) { try { return new InputTextEditor() { @Override protected Integer performEdit (Editable editor, int start, int end) { editor.replace(start, end, Character.toString(character)); return start + 1; } }.wasPerformed(); } catch (UnsupportedOperationException exception) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.commitText(Character.toString(character), 1)) { return true; } } return false; } } public static boolean inputKey (int keyCode, boolean longPress) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode))) { logKeyEventSent(keyCode, true); if (longPress) { try { Thread.sleep(ViewConfiguration.getLongPressTimeout() + ApplicationParameters.LONG_PRESS_DELAY); } catch (InterruptedException exception) { } } if (connection.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyCode))) { logKeyEventSent(keyCode, false); return true; } } } return false; } private final static Action menuAction = new Action() { @Override public boolean performAction () { return inputKey(KeyEvent.KEYCODE_MENU); } }; private final static Action logScreenAction = new Action() { @Override public boolean performAction () { ScreenLogger.log(); return true; } }; public static boolean inputKey (int keyCode) { return inputKey(keyCode, false); } public static boolean inputKey_enter () { return inputKey(KeyEvent.KEYCODE_ENTER); } public static boolean inputKey_tab () { return inputKey(KeyEvent.KEYCODE_TAB); } public static boolean inputKey_backspace () { try { return new InputTextEditor() { @Override protected Integer performEdit (Editable editor, int start, int end) { if (start < 1) return null; if (start == end) start -= 1; editor.delete(start, end); return start; } }.wasPerformed(); } catch (UnsupportedOperationException exception) { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.deleteSurroundingText(1, 0)) { return true; } } return false; } } public static boolean inputKey_escape () { return inputKey(KeyEvent.KEYCODE_ESCAPE); } public static boolean inputKey_cursorLeft () { return inputKey(KeyEvent.KEYCODE_DPAD_LEFT); } public static boolean inputKey_cursorRight () { return inputKey(KeyEvent.KEYCODE_DPAD_RIGHT); } public static boolean inputKey_cursorUp () { return inputKey(KeyEvent.KEYCODE_DPAD_UP); } public static boolean inputKey_cursorDown () { return inputKey(KeyEvent.KEYCODE_DPAD_DOWN); } public static boolean inputKey_pageUp () { return inputKey(KeyEvent.KEYCODE_PAGE_UP); } public static boolean inputKey_pageDown () { return inputKey(KeyEvent.KEYCODE_PAGE_DOWN); } public static boolean inputKey_home () { return inputKey(KeyEvent.KEYCODE_MOVE_HOME); } public static boolean inputKey_end () { return inputKey(KeyEvent.KEYCODE_MOVE_END); } public static boolean inputKey_insert () { return inputKey(KeyEvent.KEYCODE_INSERT); } public static boolean inputKey_delete () { InputConnection connection = getInputConnection(); if (connection != null) { if (connection.deleteSurroundingText(0, 1)) { return true; } } return false; } private final static Action[] functionKeyActions = new Action[] { homeAction, backAction, notificationsAction, recentApplicationsAction, brlttySettingsAction, quickSettingsAction, backwardAction, forwardAction, powerDialogAction, menuAction, logScreenAction }; public static boolean inputKey_function (int key) { if (key < 0) return false; if (key >= functionKeyActions.length) return false; Action action = functionKeyActions[key]; if (action == null) return false; return action.performAction(); } }
The delete key no longer needs the input service as of Android 5.0 (Lollipop). (dm)
Android/Application/src/org/a11y/brltty/android/InputService.java
The delete key no longer needs the input service as of Android 5.0 (Lollipop). (dm)
Java
lgpl-2.1
f91c1077514d793d7b15ec1d4578e4b8a6792409
0
exedio/copernica,exedio/copernica,exedio/copernica
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * 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.exedio.cope; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; public final class ReportTable extends ReportNode { public final Report report; public final String name; final Table table; private boolean exists = false; private ReportLastAnalyzed lastAnalyzed = null; private final HashMap columnMap = new HashMap(); private final ArrayList columnList = new ArrayList(); private final HashMap constraintMap = new HashMap(); private final ArrayList constraintList = new ArrayList(); ReportTable(final Report report, final Table table) { this.report = report; this.name = table.id; this.table = table; this.exists = false; } ReportTable(final Report report, final String name) { this.report = report; this.name = name; this.table = null; this.exists = true; } final void register(final ReportColumn column) { if(columnMap.put(column.name, column)!=null) throw new RuntimeException(column.toString()); columnList.add(column); } final void setLastAnalyzed(final Date lastAnalyzed) { if(this.lastAnalyzed!=null) throw new RuntimeException(); this.lastAnalyzed = new ReportLastAnalyzed(lastAnalyzed, this); } final void notifyExists() { exists = true; } final void notifyRequiredColumn(final Column column) { final ReportColumn result = new ReportColumn(column.id, column.getDatabaseType(), true, this); if(column.primaryKey) { addRequiredConstraint( new ReportConstraint(column.getPrimaryKeyConstraintID(), ReportConstraint.TYPE_PRIMARY_KEY, this)); } else { final String checkConstraint = column.getCheckConstraint(); if(checkConstraint!=null) { addRequiredConstraint( new ReportConstraint(column.getCheckConstraintID(), ReportConstraint.TYPE_CHECK, this, checkConstraint)); } } if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; addRequiredConstraint( new ReportConstraint(itemColumn.integrityConstraintName, ReportConstraint.TYPE_FOREIGN_KEY, this)); } } final ReportColumn notifyExistentColumn(final String columnName, final String existingType) { ReportColumn result = (ReportColumn)columnMap.get(columnName); if(result==null) result = new ReportColumn(columnName, existingType, false, this); else result.notifyExists(existingType); return result; } private final void addRequiredConstraint(final ReportConstraint constraint) { if(constraintMap.put(constraint.name, constraint)!=null) throw new RuntimeException(constraint.name); constraintList.add(constraint); constraint.notifyRequired(); } final ReportConstraint notifyRequiredConstraint(final String constraintName, final int type, final String condition) { final ReportConstraint result = new ReportConstraint(constraintName, type, this, condition); addRequiredConstraint(result); return result; } private final ReportConstraint getOrCreateExistentConstraint(final String constraintName, final int type) { ReportConstraint result = (ReportConstraint)constraintMap.get(constraintName); if(result==null) { result = new ReportConstraint(constraintName, type, this); constraintMap.put(constraintName, result); constraintList.add(result); } return result; } final ReportConstraint notifyExistentConstraint(final String constraintName, final int type) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, type); result.notifyExists(); return result; } final ReportConstraint notifyExistentCheckConstraint(final String constraintName, final String condition) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, ReportConstraint.TYPE_CHECK); result.notifyExistsCondition(condition); return result; } final ReportConstraint notifyExistentUniqueConstraint(final String constraintName, final String condition) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, ReportConstraint.TYPE_UNIQUE); result.notifyExistsCondition(condition); return result; } public final boolean required() { return table!=null; } public final boolean exists() { return exists; } public final ReportLastAnalyzed getLastAnalyzed() { return lastAnalyzed; } public final Collection getColumns() { return columnList; } public final ReportColumn getColumn(final String columnName) { return (ReportColumn)columnMap.get(columnName); } public final Collection getConstraints() { return constraintList; } public final ReportConstraint getConstraint(final String constraintName) { return (ReportConstraint)constraintMap.get(constraintName); } protected void finish() { if(cumulativeColor!=COLOR_NOT_YET_CALC || particularColor!=COLOR_NOT_YET_CALC) throw new RuntimeException(); final String error; final int particularColor; if(!exists) { error = "MISSING !!!"; particularColor = COLOR_ERROR; } else if(table==null) { error = "not used"; particularColor = COLOR_WARNING; } else { error = null; particularColor = COLOR_OK; } this.error = error; this.particularColor = particularColor; cumulativeColor = particularColor; if(lastAnalyzed!=null) { lastAnalyzed.finish(); cumulativeColor = Math.max(cumulativeColor, lastAnalyzed.cumulativeColor); } for(Iterator i = columnList.iterator(); i.hasNext(); ) { final ReportColumn column = (ReportColumn)i.next(); column.finish(); cumulativeColor = Math.max(cumulativeColor, column.cumulativeColor); } for(Iterator i = constraintList.iterator(); i.hasNext(); ) { final ReportConstraint constraint = (ReportConstraint)i.next(); constraint.finish(); cumulativeColor = Math.max(cumulativeColor, constraint.cumulativeColor); } } public final void create() { report.database.createTable(table); } public final void renameTo(final String newName) { report.database.renameTable(name, newName); } public final void drop() { report.database.dropTable(name); } public final void analyze() { report.database.analyzeTable(name); } }
lib/src/com/exedio/cope/ReportTable.java
/* * Copyright (C) 2004-2005 exedio GmbH (www.exedio.com) * * 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.exedio.cope; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Iterator; public final class ReportTable extends ReportNode { public final Report report; public final String name; final Table table; private boolean exists = false; private ReportLastAnalyzed lastAnalyzed = null; private final HashMap columnMap = new HashMap(); private final ArrayList columnList = new ArrayList(); private final HashMap constraintMap = new HashMap(); private final ArrayList constraintList = new ArrayList(); ReportTable(final Report report, final Table table) { this.report = report; this.name = table.id; this.table = table; this.exists = false; } ReportTable(final Report report, final String name) { this.report = report; this.name = name; this.table = null; this.exists = true; } final void register(final ReportColumn column) { if(columnMap.put(column.name, column)!=null) throw new RuntimeException(column.toString()); columnList.add(column); } final void setLastAnalyzed(final Date lastAnalyzed) { if(this.lastAnalyzed!=null) throw new RuntimeException(); this.lastAnalyzed = new ReportLastAnalyzed(lastAnalyzed, this); } final void notifyExists() { exists = true; } final void notifyRequiredColumn(final Column column) { final ReportColumn result = new ReportColumn(column.id, column.getDatabaseType(), true, this); if(column.primaryKey) { addRequiredConstraint( new ReportConstraint(column.getPrimaryKeyConstraintID(), ReportConstraint.TYPE_PRIMARY_KEY, this)); } else { final String checkConstraint = column.getCheckConstraint(); if(checkConstraint!=null) { addRequiredConstraint( new ReportConstraint(column.getCheckConstraintID(), ReportConstraint.TYPE_CHECK, this, checkConstraint)); } } if(column instanceof ItemColumn) { final ItemColumn itemColumn = (ItemColumn)column; addRequiredConstraint( new ReportConstraint(itemColumn.integrityConstraintName, ReportConstraint.TYPE_FOREIGN_KEY, this)); } } final ReportColumn notifyExistentColumn(final String columnName, final String existingType) { ReportColumn result = (ReportColumn)columnMap.get(columnName); if(result==null) result = new ReportColumn(columnName, existingType, false, this); else result.notifyExists(existingType); return result; } private final void addRequiredConstraint(final ReportConstraint constraint) { if(constraintMap.put(constraint.name, constraint)!=null) throw new RuntimeException(constraint.name); constraintList.add(constraint); constraint.notifyRequired(); } final ReportConstraint notifyRequiredConstraint(final String constraintName, final int type) { final ReportConstraint result = new ReportConstraint(constraintName, type, this); addRequiredConstraint(result); return result; } final ReportConstraint notifyRequiredConstraint(final String constraintName, final int type, final String condition) { final ReportConstraint result = new ReportConstraint(constraintName, type, this, condition); addRequiredConstraint(result); return result; } private final ReportConstraint getOrCreateExistentConstraint(final String constraintName, final int type) { ReportConstraint result = (ReportConstraint)constraintMap.get(constraintName); if(result==null) { result = new ReportConstraint(constraintName, type, this); constraintMap.put(constraintName, result); constraintList.add(result); } return result; } final ReportConstraint notifyExistentConstraint(final String constraintName, final int type) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, type); result.notifyExists(); return result; } final ReportConstraint notifyExistentCheckConstraint(final String constraintName, final String condition) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, ReportConstraint.TYPE_CHECK); result.notifyExistsCondition(condition); return result; } final ReportConstraint notifyExistentUniqueConstraint(final String constraintName, final String condition) { final ReportConstraint result = getOrCreateExistentConstraint(constraintName, ReportConstraint.TYPE_UNIQUE); result.notifyExistsCondition(condition); return result; } public final boolean required() { return table!=null; } public final boolean exists() { return exists; } public final ReportLastAnalyzed getLastAnalyzed() { return lastAnalyzed; } public final Collection getColumns() { return columnList; } public final ReportColumn getColumn(final String columnName) { return (ReportColumn)columnMap.get(columnName); } public final Collection getConstraints() { return constraintList; } public final ReportConstraint getConstraint(final String constraintName) { return (ReportConstraint)constraintMap.get(constraintName); } protected void finish() { if(cumulativeColor!=COLOR_NOT_YET_CALC || particularColor!=COLOR_NOT_YET_CALC) throw new RuntimeException(); final String error; final int particularColor; if(!exists) { error = "MISSING !!!"; particularColor = COLOR_ERROR; } else if(table==null) { error = "not used"; particularColor = COLOR_WARNING; } else { error = null; particularColor = COLOR_OK; } this.error = error; this.particularColor = particularColor; cumulativeColor = particularColor; if(lastAnalyzed!=null) { lastAnalyzed.finish(); cumulativeColor = Math.max(cumulativeColor, lastAnalyzed.cumulativeColor); } for(Iterator i = columnList.iterator(); i.hasNext(); ) { final ReportColumn column = (ReportColumn)i.next(); column.finish(); cumulativeColor = Math.max(cumulativeColor, column.cumulativeColor); } for(Iterator i = constraintList.iterator(); i.hasNext(); ) { final ReportConstraint constraint = (ReportConstraint)i.next(); constraint.finish(); cumulativeColor = Math.max(cumulativeColor, constraint.cumulativeColor); } } public final void create() { report.database.createTable(table); } public final void renameTo(final String newName) { report.database.renameTable(name, newName); } public final void drop() { report.database.dropTable(name); } public final void analyze() { report.database.analyzeTable(name); } }
remove notifyRequiredConstraint, not needed git-svn-id: 9dbc6da3594b32e13bcf3b3752e372ea5bc7c2cc@2409 e7d4fc99-c606-0410-b9bf-843393a9eab7
lib/src/com/exedio/cope/ReportTable.java
remove notifyRequiredConstraint, not needed
Java
apache-2.0
0f7e1d0a4e6fb2cd14ca303fbb1d2b9a1e44cb11
0
SoftTech2018/06_del2
package functionality; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ReadFiles { private File log; private File store; public ReadFiles(){ log = new File("/files/Log.txt"); store = new File("/files.txt/store.txt"); } public String getProductName(int productNumber) throws FileNotFoundException{ // Read store.txt, find produktnummeret og returner produktnavnet Scanner scan = null; try { scan = new Scanner(store); int p =0; do { p = scan.nextInt(); } while (p != productNumber); } finally { scan.close(); } return null; } public void writeLog(String line){ // tilfรธj en linje til Log.txt } public void updProductInventory(int productNumber, double amountUsed){ // Ret i inventory i store.txt } public double getProductInventory(int productNumber){ // find mรฆngde pรฅ lager for det pรฅgรฆldende produkt return 0; } }
06_del2/WCU/functionality/ReadFiles.java
package functionality; public class ReadFiles { }
ReadFiles pรฅbegyndt
06_del2/WCU/functionality/ReadFiles.java
ReadFiles pรฅbegyndt
Java
apache-2.0
8672cafb3ffeefcd89455402fdb82d27b9804436
0
hrovira/addama-googlecode,hrovira/addama-googlecode,hrovira/addama-googlecode,hrovira/addama-googlecode,hrovira/addama-googlecode
package org.systemsbiology.addama.appengine.callbacks; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.urlfetch.HTTPResponse; import org.systemsbiology.addama.appengine.memcache.MemcacheLoaderCallback; import org.systemsbiology.addama.appengine.pojos.HTTPResponseContent; import java.io.Serializable; import java.net.URL; import java.util.logging.Logger; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.appengine.api.datastore.KeyFactory.createKey; import static com.google.appengine.api.urlfetch.URLFetchServiceFactory.getURLFetchService; import static javax.servlet.http.HttpServletResponse.SC_OK; import static org.apache.commons.lang.StringUtils.chomp; /** * @author hrovira */ public class AppsContentMemcacheLoaderCallback implements MemcacheLoaderCallback { private static final Logger log = Logger.getLogger(AppsContentMemcacheLoaderCallback.class.getName()); private final String appsId; private final boolean serveHomepage; public AppsContentMemcacheLoaderCallback(String appsId) { this(appsId, false); } public AppsContentMemcacheLoaderCallback(String appsId, boolean serveHomepage) { this.appsId = appsId; this.serveHomepage = serveHomepage; } public Serializable getCacheableObject(String contentUri) throws Exception { Entity e = getDatastoreService().get(createKey("apps-content", appsId)); if (serveHomepage) { if (e.hasProperty("homepage")) { contentUri = "/" + e.getProperty("homepage").toString(); } else { contentUri = "/index.html"; } } String url = chomp(e.getProperty("url").toString(), "/"); log.info("loading:" + url + contentUri); URL contentUrl = new URL(url + contentUri); HTTPResponse resp = getURLFetchService().fetch(contentUrl); if (resp.getResponseCode() == SC_OK) { log.info("loaded:" + contentUrl); return new HTTPResponseContent(resp); } return null; } }
gae-svcs/addama-registry/src/main/java/org/systemsbiology/addama/appengine/callbacks/AppsContentMemcacheLoaderCallback.java
package org.systemsbiology.addama.appengine.callbacks; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.urlfetch.HTTPResponse; import org.systemsbiology.addama.appengine.memcache.MemcacheLoaderCallback; import org.systemsbiology.addama.appengine.pojos.HTTPResponseContent; import java.io.Serializable; import java.net.URL; import java.util.logging.Logger; import static com.google.appengine.api.datastore.DatastoreServiceFactory.getDatastoreService; import static com.google.appengine.api.datastore.KeyFactory.createKey; import static com.google.appengine.api.urlfetch.URLFetchServiceFactory.getURLFetchService; import static javax.servlet.http.HttpServletResponse.SC_OK; import static org.apache.commons.lang.StringUtils.chomp; /** * @author hrovira */ public class AppsContentMemcacheLoaderCallback implements MemcacheLoaderCallback { private static final Logger log = Logger.getLogger(AppsContentMemcacheLoaderCallback.class.getName()); private final String appsId; private final boolean serveHomepage; public AppsContentMemcacheLoaderCallback(String appsId) { this(appsId, false); } public AppsContentMemcacheLoaderCallback(String appsId, boolean serveHomepage) { this.appsId = appsId; this.serveHomepage = serveHomepage; } public Serializable getCacheableObject(String contentUri) throws Exception { Entity e = getDatastoreService().get(createKey("apps-content", appsId)); if (serveHomepage) { if (e.hasProperty("homepage")) { contentUri = e.getProperty("homepage").toString(); } else { contentUri = "index.html"; } } String url = chomp(e.getProperty("url").toString(), "/"); log.info("loading:" + url + contentUri); URL contentUrl = new URL(url + contentUri); HTTPResponse resp = getURLFetchService().fetch(contentUrl); if (resp.getResponseCode() == SC_OK) { log.info("loaded:" + contentUrl); return new HTTPResponseContent(resp); } return null; } }
added slash in front of homepage
gae-svcs/addama-registry/src/main/java/org/systemsbiology/addama/appengine/callbacks/AppsContentMemcacheLoaderCallback.java
added slash in front of homepage
Java
apache-2.0
47ce99429f7021a759578961c1093dc03fc40e19
0
caot/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,kdwink/intellij-community,signed/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,jagguli/intellij-community,allotria/intellij-community,samthor/intellij-community,fitermay/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,allotria/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,semonte/intellij-community,supersven/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,caot/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,semonte/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,youdonghai/intellij-community,da1z/intellij-community,clumsy/intellij-community,slisson/intellij-community,vvv1559/intellij-community,allotria/intellij-community,slisson/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,kdwink/intellij-community,supersven/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,amith01994/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,vvv1559/intellij-community,izonder/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,semonte/intellij-community,ibinti/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,retomerz/intellij-community,ibinti/intellij-community,semonte/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,FHannes/intellij-community,dslomov/intellij-community,jagguli/intellij-community,semonte/intellij-community,apixandru/intellij-community,fitermay/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,supersven/intellij-community,kool79/intellij-community,amith01994/intellij-community,apixandru/intellij-community,semonte/intellij-community,slisson/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,FHannes/intellij-community,izonder/intellij-community,samthor/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,signed/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,clumsy/intellij-community,ibinti/intellij-community,supersven/intellij-community,jagguli/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,semonte/intellij-community,kool79/intellij-community,ibinti/intellij-community,fitermay/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,vvv1559/intellij-community,kool79/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,da1z/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,da1z/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,allotria/intellij-community,samthor/intellij-community,vvv1559/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,slisson/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,samthor/intellij-community,slisson/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,hurricup/intellij-community,clumsy/intellij-community,asedunov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,hurricup/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,signed/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,signed/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,amith01994/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,xfournet/intellij-community,apixandru/intellij-community,jagguli/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,slisson/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,supersven/intellij-community,kdwink/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,fitermay/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,samthor/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,samthor/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,vladmm/intellij-community,kdwink/intellij-community,FHannes/intellij-community,supersven/intellij-community,jagguli/intellij-community,izonder/intellij-community,izonder/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,da1z/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,supersven/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,retomerz/intellij-community,signed/intellij-community,ibinti/intellij-community,kool79/intellij-community,vladmm/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,izonder/intellij-community,signed/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,kdwink/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,da1z/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,caot/intellij-community,signed/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,asedunov/intellij-community,xfournet/intellij-community,caot/intellij-community,signed/intellij-community,slisson/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,slisson/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,kool79/intellij-community,tmpgit/intellij-community,supersven/intellij-community,apixandru/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,vladmm/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,caot/intellij-community,fitermay/intellij-community,da1z/intellij-community,fitermay/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,fnouama/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,caot/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,FHannes/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,vladmm/intellij-community,supersven/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,caot/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,dslomov/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,amith01994/intellij-community,ibinti/intellij-community,da1z/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,caot/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,signed/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community
/* * Copyright 2000-2015 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.openapi.wm.impl.status; import com.intellij.ide.ui.UISettings; import com.intellij.idea.ActionsBundle; import com.intellij.notification.EventLog; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.TaskInfo; import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonHandler; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.ui.Gray; import com.intellij.ui.TabbedPaneWrapper; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.labels.LinkListener; import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.Alarm; import com.intellij.util.ui.*; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidget { private final ProcessPopup myPopup; private final StatusPanel myInfoPanel = new StatusPanel(); private final JPanel myRefreshAndInfoPanel = new JPanel(); private final AnimatedIcon myProgressIcon; private final ArrayList<ProgressIndicatorEx> myOriginals = new ArrayList<ProgressIndicatorEx>(); private final ArrayList<TaskInfo> myInfos = new ArrayList<TaskInfo>(); private final Map<InlineProgressIndicator, ProgressIndicatorEx> myInline2Original = new HashMap<InlineProgressIndicator, ProgressIndicatorEx>(); private final MultiValuesMap<ProgressIndicatorEx, InlineProgressIndicator> myOriginal2Inlines = new MultiValuesMap<ProgressIndicatorEx, InlineProgressIndicator>(); private final MergingUpdateQueue myUpdateQueue; private final Alarm myQueryAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private boolean myShouldClosePopupAndOnProcessFinish; private final Alarm myRefreshAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private final AnimatedIcon myRefreshIcon; private String myCurrentRequestor; public InfoAndProgressPanel() { setOpaque(false); myRefreshIcon = new RefreshFileSystemIcon(); // new AsyncProcessIcon("Refreshing filesystem") { // protected Icon getPassiveIcon() { // return myEmptyRefreshIcon; // } // // @Override // public Dimension getPreferredSize() { // if (!isRunning()) return new Dimension(0, 0); // return super.getPreferredSize(); // } // // @Override // public void paint(Graphics g) { // g.translate(0, -1); // super.paint(g); // g.translate(0, 1); // } //}; myRefreshIcon.setPaintPassiveIcon(false); myRefreshAndInfoPanel.setLayout(new BorderLayout()); myRefreshAndInfoPanel.setOpaque(false); myRefreshAndInfoPanel.add(myRefreshIcon, BorderLayout.WEST); myRefreshAndInfoPanel.add(myInfoPanel, BorderLayout.CENTER); myProgressIcon = new AsyncProcessIcon("Background process"); myProgressIcon.setOpaque(false); myProgressIcon.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { handle(e); } @Override public void mouseReleased(MouseEvent e) { handle(e); } }); myProgressIcon.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); myProgressIcon.setBorder(StatusBarWidget.WidgetBorder.INSTANCE); myProgressIcon.setToolTipText(ActionsBundle.message("action.ShowProcessWindow.double.click")); myUpdateQueue = new MergingUpdateQueue("Progress indicator", 50, true, MergingUpdateQueue.ANY_COMPONENT); myPopup = new ProcessPopup(this); setRefreshVisible(false); restoreEmptyStatus(); } private void handle(MouseEvent e) { if (UIUtil.isActionClick(e, MouseEvent.MOUSE_PRESSED)) { if (!myPopup.isShowing()) { openProcessPopup(true); } else { hideProcessPopup(); } } else if (e.isPopupTrigger()) { ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("BackgroundTasks"); ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group).getComponent().show(e.getComponent(), e.getX(), e.getY()); } } @Override @NotNull public String ID() { return "InfoAndProgress"; } @Override public WidgetPresentation getPresentation(@NotNull PlatformType type) { return null; } @Override public void install(@NotNull StatusBar statusBar) { } @Override public void dispose() { setRefreshVisible(false); InlineProgressIndicator[] indicators = getCurrentInlineIndicators().toArray(new InlineProgressIndicator[0]); for (InlineProgressIndicator indicator : indicators) { removeProgress(indicator); } myInline2Original.clear(); myOriginal2Inlines.clear(); } @Override public JComponent getComponent() { return this; } @NotNull public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() { synchronized (myOriginals) { if (myOriginals.isEmpty()) return Collections.emptyList(); List<Pair<TaskInfo, ProgressIndicator>> result = new ArrayList<Pair<TaskInfo, ProgressIndicator>>(myOriginals.size()); for (int i = 0; i < myOriginals.size(); i++) { result.add(Pair.<TaskInfo, ProgressIndicator>create(myInfos.get(i), myOriginals.get(i))); } return Collections.unmodifiableList(result); } } public void addProgress(@NotNull ProgressIndicatorEx original, @NotNull TaskInfo info) { synchronized (myOriginals) { final boolean veryFirst = !hasProgressIndicators(); myOriginals.add(original); myInfos.add(info); final InlineProgressIndicator expanded = createInlineDelegate(info, original, false); final InlineProgressIndicator compact = createInlineDelegate(info, original, true); myPopup.addIndicator(expanded); myProgressIcon.resume(); if (veryFirst && !myPopup.isShowing()) { buildInInlineIndicator(compact); } else { buildInProcessCount(); if (myInfos.size() > 1 && Registry.is("ide.windowSystem.autoShowProcessPopup")) { openProcessPopup(false); } } runQuery(); } } private boolean hasProgressIndicators() { synchronized (myOriginals) { return !myOriginals.isEmpty(); } } private void removeProgress(@NotNull InlineProgressIndicator progress) { synchronized (myOriginals) { if (!myInline2Original.containsKey(progress)) return; final boolean last = myOriginals.size() == 1; final boolean beforeLast = myOriginals.size() == 2; myPopup.removeIndicator(progress); final ProgressIndicatorEx original = removeFromMaps(progress); if (myOriginals.contains(original)) { Disposer.dispose(progress); return; } if (last) { restoreEmptyStatus(); if (myShouldClosePopupAndOnProcessFinish) { hideProcessPopup(); } } else { if (myPopup.isShowing() || myOriginals.size() > 1) { buildInProcessCount(); } else if (beforeLast) { buildInInlineIndicator(createInlineDelegate(myInfos.get(0), myOriginals.get(0), true)); } else { restoreEmptyStatus(); } } runQuery(); } Disposer.dispose(progress); } private ProgressIndicatorEx removeFromMaps(@NotNull InlineProgressIndicator progress) { final ProgressIndicatorEx original = myInline2Original.get(progress); myInline2Original.remove(progress); myOriginal2Inlines.remove(original, progress); if (myOriginal2Inlines.get(original) == null) { final int originalIndex = myOriginals.indexOf(original); myOriginals.remove(originalIndex); myInfos.remove(originalIndex); } return original; } private void openProcessPopup(boolean requestFocus) { synchronized (myOriginals) { if (myPopup.isShowing()) return; if (hasProgressIndicators()) { myShouldClosePopupAndOnProcessFinish = true; buildInProcessCount(); } else { myShouldClosePopupAndOnProcessFinish = false; restoreEmptyStatus(); } myPopup.show(requestFocus); } } void hideProcessPopup() { synchronized (myOriginals) { if (!myPopup.isShowing()) return; if (myOriginals.size() == 1) { buildInInlineIndicator(createInlineDelegate(myInfos.get(0), myOriginals.get(0), true)); } else if (!hasProgressIndicators()) { restoreEmptyStatus(); } else { buildInProcessCount(); } myPopup.hide(); } } private void buildInProcessCount() { removeAll(); setLayout(new BorderLayout()); final JPanel progressCountPanel = new JPanel(new BorderLayout(0, 0)); progressCountPanel.setOpaque(false); String processWord = myOriginals.size() == 1 ? " process" : " processes"; final LinkLabel label = new LinkLabel(myOriginals.size() + processWord + " running...", null, new LinkListener() { @Override public void linkSelected(final LinkLabel aSource, final Object aLinkData) { triggerPopupShowing(); } }); if (SystemInfo.isMac) label.setFont(JBUI.Fonts.label(11)); label.setOpaque(false); final Wrapper labelComp = new Wrapper(label); labelComp.setOpaque(false); progressCountPanel.add(labelComp, BorderLayout.CENTER); //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); progressCountPanel.add(myProgressIcon, BorderLayout.WEST); add(myRefreshAndInfoPanel, BorderLayout.CENTER); progressCountPanel.setBorder(JBUI.Borders.empty(0, 0, 0, 4)); add(progressCountPanel, BorderLayout.EAST); revalidate(); repaint(); } private void buildInInlineIndicator(@NotNull final InlineProgressIndicator inline) { removeAll(); setLayout(new InlineLayout()); add(myRefreshAndInfoPanel); final JPanel inlinePanel = new JPanel(new BorderLayout()); inline.getComponent().setBorder(JBUI.Borders.empty(1, 0, 0, 2)); final JComponent inlineComponent = inline.getComponent(); inlineComponent.setOpaque(false); inlinePanel.add(inlineComponent, BorderLayout.CENTER); //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); inlinePanel.add(myProgressIcon, BorderLayout.WEST); inline.updateProgressNow(); inlinePanel.setOpaque(false); add(inlinePanel); myRefreshAndInfoPanel.revalidate(); myRefreshAndInfoPanel.repaint(); UISettings uiSettings = UISettings.getInstance(); if (uiSettings.PRESENTATION_MODE || !uiSettings.SHOW_STATUS_BAR && Registry.is("ide.show.progress.without.status.bar")) { final JRootPane pane = myInfoPanel.getRootPane(); assert pane != null; final PresentationModeProgressPanel panel = new PresentationModeProgressPanel(inline); final MyInlineProgressIndicator delegate = new MyInlineProgressIndicator(true, inline.getInfo(), inline) { @Override protected void updateProgress() { super.updateProgress(); panel.update(); } }; Disposer.register(inline, delegate); final Component anchor = getAnchor(pane); JBPopupFactory.getInstance().createBalloonBuilder(panel.getProgressPanel()) .setFadeoutTime(0) .setFillColor(Gray.TRANSPARENT) .setShowCallout(false) .setBorderColor(Gray.TRANSPARENT) .setBorderInsets(JBUI.emptyInsets()) .setAnimationCycle(0) .setCloseButtonEnabled(false) .setHideOnClickOutside(false) .setDisposable(inline) .setHideOnFrameResize(false) .setHideOnKeyOutside(false) .setBlockClicksThroughBalloon(true) .setHideOnAction(false) .createBalloon().show(new PositionTracker<Balloon>(anchor) { @Override public RelativePoint recalculateLocation(Balloon object) { Component c = getAnchor(pane); return new RelativePoint(c, new Point(c.getWidth() - 150, c.getHeight() - 45)); } }, Balloon.Position.above); } } @NotNull private static Component getAnchor(@NotNull JRootPane pane) { Component tabWrapper = UIUtil.findComponentOfType(pane, TabbedPaneWrapper.TabWrapper.class); if (tabWrapper != null) return tabWrapper; Component splitters = UIUtil.findComponentOfType(pane, EditorsSplitters.class); if (splitters != null) return splitters; FileEditorManagerEx ex = FileEditorManagerEx.getInstanceEx(ProjectUtil.guessCurrentProject(pane)); return ex == null ? pane : ex.getSplitters(); } public Couple<String> setText(@Nullable final String text, @Nullable final String requestor) { if (StringUtil.isEmpty(text) && !Comparing.equal(requestor, myCurrentRequestor) && !EventLog.LOG_REQUESTOR.equals(requestor)) { return Couple.of(myInfoPanel.getText(), myCurrentRequestor); } boolean logMode = myInfoPanel.updateText(EventLog.LOG_REQUESTOR.equals(requestor) ? "" : text); myCurrentRequestor = logMode ? EventLog.LOG_REQUESTOR : requestor; return Couple.of(text, requestor); } public void setRefreshVisible(final boolean visible) { UIUtil.invokeLaterIfNeeded(new Runnable() { @Override public void run() { myRefreshAlarm.cancelAllRequests(); myRefreshAlarm.addRequest(new Runnable() { @Override public void run() { if (visible) { myRefreshIcon.resume(); } else { myRefreshIcon.suspend(); } myRefreshIcon.revalidate(); myRefreshIcon.repaint(); } }, visible ? 100 : 300); } }); } public void setRefreshToolTipText(final String tooltip) { myRefreshIcon.setToolTipText(tooltip); } public BalloonHandler notifyByBalloon(MessageType type, String htmlBody, @Nullable Icon icon, @Nullable HyperlinkListener listener) { final Balloon balloon = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder( htmlBody.replace("\n", "<br>"), icon != null ? icon : type.getDefaultIcon(), type.getPopupBackground(), listener).createBalloon(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Component comp = InfoAndProgressPanel.this; if (comp.isShowing()) { int offset = comp.getHeight() / 2; Point point = new Point(comp.getWidth() - offset, comp.getHeight() - offset); balloon.show(new RelativePoint(comp, point), Balloon.Position.above); } else { final JRootPane rootPane = SwingUtilities.getRootPane(comp); if (rootPane != null && rootPane.isShowing()) { final Container contentPane = rootPane.getContentPane(); final Rectangle bounds = contentPane.getBounds(); final Point target = UIUtil.getCenterPoint(bounds, JBUI.size(1, 1)); target.y = bounds.height - 3; balloon.show(new RelativePoint(contentPane, target), Balloon.Position.above); } } } }); return new BalloonHandler() { @Override public void hide() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { balloon.hide(); } }); } }; } private static class InlineLayout extends AbstractLayoutManager { private int myProgressWidth; @Override public Dimension preferredLayoutSize(final Container parent) { Dimension result = new Dimension(); for (int i = 0; i < parent.getComponentCount(); i++) { final Dimension prefSize = parent.getComponent(i).getPreferredSize(); result.width += prefSize.width; result.height = Math.max(prefSize.height, result.height); } return result; } @Override public void layoutContainer(final Container parent) { assert parent.getComponentCount() == 2; // 1. info; 2. progress Component infoPanel = parent.getComponent(0); Component progressPanel = parent.getComponent(1); int progressPrefWidth = progressPanel.getPreferredSize().width; final Dimension size = parent.getSize(); int maxProgressWidth = (int) (size.width * 0.8); int minProgressWidth = (int) (size.width * 0.5); if (progressPrefWidth > myProgressWidth) { myProgressWidth = progressPrefWidth; } if (myProgressWidth > maxProgressWidth) { myProgressWidth = maxProgressWidth; } if (myProgressWidth < minProgressWidth) { myProgressWidth = minProgressWidth; } infoPanel.setBounds(0, 0, size.width - myProgressWidth, size.height); progressPanel.setBounds(size.width - myProgressWidth, 0, myProgressWidth, size.height); } } @NotNull private InlineProgressIndicator createInlineDelegate(@NotNull TaskInfo info, @NotNull ProgressIndicatorEx original, final boolean compact) { final Collection<InlineProgressIndicator> inlines = myOriginal2Inlines.get(original); if (inlines != null) { for (InlineProgressIndicator eachInline : inlines) { if (eachInline.isCompact() == compact) return eachInline; } } final InlineProgressIndicator inline = new MyInlineProgressIndicator(compact, info, original); myInline2Original.put(inline, original); myOriginal2Inlines.put(original, inline); if (compact) { inline.getComponent().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { handle(e); } @Override public void mouseReleased(MouseEvent e) { handle(e); } }); } return inline; } private void triggerPopupShowing() { if (myPopup.isShowing()) { hideProcessPopup(); } else { openProcessPopup(true); } } private void restoreEmptyStatus() { removeAll(); setLayout(new BorderLayout()); add(myRefreshAndInfoPanel, BorderLayout.CENTER); myProgressIcon.suspend(); Container iconParent = myProgressIcon.getParent(); if (iconParent != null) { iconParent.remove(myProgressIcon); // to prevent leaks to this removed parent via progress icon } myRefreshAndInfoPanel.revalidate(); myRefreshAndInfoPanel.repaint(); } //private String formatTime(long t) { // if (t < 1000) return "< 1 sec"; // if (t < 60 * 1000) return (t / 1000) + " sec"; // return "~" + (int)Math.ceil(t / (60 * 1000f)) + " min"; //} public boolean isProcessWindowOpen() { return myPopup.isShowing(); } public void setProcessWindowOpen(final boolean open) { if (open) { openProcessPopup(true); } else { hideProcessPopup(); } } private class MyInlineProgressIndicator extends InlineProgressIndicator { private ProgressIndicatorEx myOriginal; public MyInlineProgressIndicator(final boolean compact, @NotNull TaskInfo task, @NotNull ProgressIndicatorEx original) { super(compact, task); myOriginal = original; original.addStateDelegate(this); addStateDelegate(new AbstractProgressIndicatorExBase(){ @Override public void cancel() { super.cancel(); updateProgress(); } }); } @Override public void stop() { super.stop(); updateProgress(); } @Override protected boolean isFinished() { TaskInfo info = getInfo(); return info == null || isFinished(info); } @Override public void finish(@NotNull final TaskInfo task) { super.finish(task); queueRunningUpdate(new Runnable() { @Override public void run() { removeProgress(MyInlineProgressIndicator.this); } }); } @Override public void dispose() { super.dispose(); myOriginal = null; } @Override protected void cancelRequest() { myOriginal.cancel(); } @Override protected void queueProgressUpdate(final Runnable update) { myUpdateQueue.queue(new Update(MyInlineProgressIndicator.this, false, 1) { @Override public void run() { update.run(); } }); } @Override protected void queueRunningUpdate(final Runnable update) { myUpdateQueue.queue(new Update(new Object(), false, 0) { @Override public void run() { ApplicationManager.getApplication().invokeLater(update); } }); } } private void runQuery() { if (getRootPane() == null) return; Set<InlineProgressIndicator> indicators = getCurrentInlineIndicators(); if (indicators.isEmpty()) return; for (InlineProgressIndicator each : indicators) { each.updateProgress(); } myQueryAlarm.cancelAllRequests(); myQueryAlarm.addRequest(new Runnable() { @Override public void run() { runQuery(); } }, 2000); } @NotNull private Set<InlineProgressIndicator> getCurrentInlineIndicators() { synchronized (myOriginals) { return myInline2Original.keySet(); } } }
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java
/* * Copyright 2000-2015 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.openapi.wm.impl.status; import com.intellij.ide.ui.UISettings; import com.intellij.idea.ActionsBundle; import com.intellij.notification.EventLog; import com.intellij.openapi.actionSystem.ActionGroup; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileEditor.impl.EditorsSplitters; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.TaskInfo; import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.ui.MessageType; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.BalloonHandler; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.CustomStatusBarWidget; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.ui.Gray; import com.intellij.ui.TabbedPaneWrapper; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.labels.LinkLabel; import com.intellij.ui.components.labels.LinkListener; import com.intellij.ui.components.panels.Wrapper; import com.intellij.util.Alarm; import com.intellij.util.ui.*; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.*; import java.util.List; public class InfoAndProgressPanel extends JPanel implements CustomStatusBarWidget { private final ProcessPopup myPopup; private final StatusPanel myInfoPanel = new StatusPanel(); private final JPanel myRefreshAndInfoPanel = new JPanel(); private final AnimatedIcon myProgressIcon; private final ArrayList<ProgressIndicatorEx> myOriginals = new ArrayList<ProgressIndicatorEx>(); private final ArrayList<TaskInfo> myInfos = new ArrayList<TaskInfo>(); private final Map<InlineProgressIndicator, ProgressIndicatorEx> myInline2Original = new HashMap<InlineProgressIndicator, ProgressIndicatorEx>(); private final MultiValuesMap<ProgressIndicatorEx, InlineProgressIndicator> myOriginal2Inlines = new MultiValuesMap<ProgressIndicatorEx, InlineProgressIndicator>(); private final MergingUpdateQueue myUpdateQueue; private final Alarm myQueryAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private boolean myShouldClosePopupAndOnProcessFinish; private final Alarm myRefreshAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private final AnimatedIcon myRefreshIcon; private String myCurrentRequestor; public InfoAndProgressPanel() { setOpaque(false); myRefreshIcon = new RefreshFileSystemIcon(); // new AsyncProcessIcon("Refreshing filesystem") { // protected Icon getPassiveIcon() { // return myEmptyRefreshIcon; // } // // @Override // public Dimension getPreferredSize() { // if (!isRunning()) return new Dimension(0, 0); // return super.getPreferredSize(); // } // // @Override // public void paint(Graphics g) { // g.translate(0, -1); // super.paint(g); // g.translate(0, 1); // } //}; myRefreshIcon.setPaintPassiveIcon(false); myRefreshAndInfoPanel.setLayout(new BorderLayout()); myRefreshAndInfoPanel.setOpaque(false); myRefreshAndInfoPanel.add(myRefreshIcon, BorderLayout.WEST); myRefreshAndInfoPanel.add(myInfoPanel, BorderLayout.CENTER); myProgressIcon = new AsyncProcessIcon("Background process"); myProgressIcon.setOpaque(false); myProgressIcon.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { handle(e); } @Override public void mouseReleased(MouseEvent e) { handle(e); } }); myProgressIcon.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); myProgressIcon.setBorder(StatusBarWidget.WidgetBorder.INSTANCE); myProgressIcon.setToolTipText(ActionsBundle.message("action.ShowProcessWindow.double.click")); myUpdateQueue = new MergingUpdateQueue("Progress indicator", 50, true, MergingUpdateQueue.ANY_COMPONENT); myPopup = new ProcessPopup(this); setRefreshVisible(false); restoreEmptyStatus(); } private void handle(MouseEvent e) { if (UIUtil.isActionClick(e, MouseEvent.MOUSE_PRESSED)) { if (!myPopup.isShowing()) { openProcessPopup(true); } else { hideProcessPopup(); } } else if (e.isPopupTrigger()) { ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction("BackgroundTasks"); ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group).getComponent().show(e.getComponent(), e.getX(), e.getY()); } } @Override @NotNull public String ID() { return "InfoAndProgress"; } @Override public WidgetPresentation getPresentation(@NotNull PlatformType type) { return null; } @Override public void install(@NotNull StatusBar statusBar) { } @Override public void dispose() { setRefreshVisible(false); InlineProgressIndicator[] indicators = getCurrentInlineIndicators().toArray(new InlineProgressIndicator[0]); for (InlineProgressIndicator indicator : indicators) { removeProgress(indicator); } myInline2Original.clear(); myOriginal2Inlines.clear(); } @Override public JComponent getComponent() { return this; } @NotNull public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() { synchronized (myOriginals) { if (myOriginals.isEmpty()) return Collections.emptyList(); List<Pair<TaskInfo, ProgressIndicator>> result = new ArrayList<Pair<TaskInfo, ProgressIndicator>>(myOriginals.size()); for (int i = 0; i < myOriginals.size(); i++) { result.add(Pair.<TaskInfo, ProgressIndicator>create(myInfos.get(i), myOriginals.get(i))); } return Collections.unmodifiableList(result); } } public void addProgress(@NotNull ProgressIndicatorEx original, @NotNull TaskInfo info) { synchronized (myOriginals) { final boolean veryFirst = !hasProgressIndicators(); myOriginals.add(original); myInfos.add(info); final InlineProgressIndicator expanded = createInlineDelegate(info, original, false); final InlineProgressIndicator compact = createInlineDelegate(info, original, true); myPopup.addIndicator(expanded); myProgressIcon.resume(); if (veryFirst && !myPopup.isShowing()) { buildInInlineIndicator(compact); } else { buildInProcessCount(); if (myInfos.size() > 1 && Registry.is("ide.windowSystem.autoShowProcessPopup")) { openProcessPopup(false); } } runQuery(); } } private boolean hasProgressIndicators() { synchronized (myOriginals) { return !myOriginals.isEmpty(); } } private void removeProgress(@NotNull InlineProgressIndicator progress) { synchronized (myOriginals) { if (!myInline2Original.containsKey(progress)) return; final boolean last = myOriginals.size() == 1; final boolean beforeLast = myOriginals.size() == 2; myPopup.removeIndicator(progress); final ProgressIndicatorEx original = removeFromMaps(progress); if (myOriginals.contains(original)) return; if (last) { restoreEmptyStatus(); if (myShouldClosePopupAndOnProcessFinish) { hideProcessPopup(); } } else { if (myPopup.isShowing() || myOriginals.size() > 1) { buildInProcessCount(); } else if (beforeLast) { buildInInlineIndicator(createInlineDelegate(myInfos.get(0), myOriginals.get(0), true)); } else { restoreEmptyStatus(); } } runQuery(); } Disposer.dispose(progress); } private ProgressIndicatorEx removeFromMaps(@NotNull InlineProgressIndicator progress) { final ProgressIndicatorEx original = myInline2Original.get(progress); myInline2Original.remove(progress); myOriginal2Inlines.remove(original, progress); if (myOriginal2Inlines.get(original) == null) { final int originalIndex = myOriginals.indexOf(original); myOriginals.remove(originalIndex); myInfos.remove(originalIndex); } return original; } private void openProcessPopup(boolean requestFocus) { synchronized (myOriginals) { if (myPopup.isShowing()) return; if (hasProgressIndicators()) { myShouldClosePopupAndOnProcessFinish = true; buildInProcessCount(); } else { myShouldClosePopupAndOnProcessFinish = false; restoreEmptyStatus(); } myPopup.show(requestFocus); } } void hideProcessPopup() { synchronized (myOriginals) { if (!myPopup.isShowing()) return; if (myOriginals.size() == 1) { buildInInlineIndicator(createInlineDelegate(myInfos.get(0), myOriginals.get(0), true)); } else if (!hasProgressIndicators()) { restoreEmptyStatus(); } else { buildInProcessCount(); } myPopup.hide(); } } private void buildInProcessCount() { removeAll(); setLayout(new BorderLayout()); final JPanel progressCountPanel = new JPanel(new BorderLayout(0, 0)); progressCountPanel.setOpaque(false); String processWord = myOriginals.size() == 1 ? " process" : " processes"; final LinkLabel label = new LinkLabel(myOriginals.size() + processWord + " running...", null, new LinkListener() { @Override public void linkSelected(final LinkLabel aSource, final Object aLinkData) { triggerPopupShowing(); } }); if (SystemInfo.isMac) label.setFont(JBUI.Fonts.label(11)); label.setOpaque(false); final Wrapper labelComp = new Wrapper(label); labelComp.setOpaque(false); progressCountPanel.add(labelComp, BorderLayout.CENTER); //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); progressCountPanel.add(myProgressIcon, BorderLayout.WEST); add(myRefreshAndInfoPanel, BorderLayout.CENTER); progressCountPanel.setBorder(JBUI.Borders.empty(0, 0, 0, 4)); add(progressCountPanel, BorderLayout.EAST); revalidate(); repaint(); } private void buildInInlineIndicator(@NotNull final InlineProgressIndicator inline) { removeAll(); setLayout(new InlineLayout()); add(myRefreshAndInfoPanel); final JPanel inlinePanel = new JPanel(new BorderLayout()); inline.getComponent().setBorder(JBUI.Borders.empty(1, 0, 0, 2)); final JComponent inlineComponent = inline.getComponent(); inlineComponent.setOpaque(false); inlinePanel.add(inlineComponent, BorderLayout.CENTER); //myProgressIcon.setBorder(new IdeStatusBarImpl.MacStatusBarWidgetBorder()); inlinePanel.add(myProgressIcon, BorderLayout.WEST); inline.updateProgressNow(); inlinePanel.setOpaque(false); add(inlinePanel); myRefreshAndInfoPanel.revalidate(); myRefreshAndInfoPanel.repaint(); UISettings uiSettings = UISettings.getInstance(); if (uiSettings.PRESENTATION_MODE || !uiSettings.SHOW_STATUS_BAR && Registry.is("ide.show.progress.without.status.bar")) { final JRootPane pane = myInfoPanel.getRootPane(); assert pane != null; final PresentationModeProgressPanel panel = new PresentationModeProgressPanel(inline); final MyInlineProgressIndicator delegate = new MyInlineProgressIndicator(true, inline.getInfo(), inline) { @Override protected void updateProgress() { super.updateProgress(); panel.update(); } }; Disposer.register(inline, delegate); final Component anchor = getAnchor(pane); JBPopupFactory.getInstance().createBalloonBuilder(panel.getProgressPanel()) .setFadeoutTime(0) .setFillColor(Gray.TRANSPARENT) .setShowCallout(false) .setBorderColor(Gray.TRANSPARENT) .setBorderInsets(JBUI.emptyInsets()) .setAnimationCycle(0) .setCloseButtonEnabled(false) .setHideOnClickOutside(false) .setDisposable(inline) .setHideOnFrameResize(false) .setHideOnKeyOutside(false) .setBlockClicksThroughBalloon(true) .setHideOnAction(false) .createBalloon().show(new PositionTracker<Balloon>(anchor) { @Override public RelativePoint recalculateLocation(Balloon object) { Component c = getAnchor(pane); return new RelativePoint(c, new Point(c.getWidth() - 150, c.getHeight() - 45)); } }, Balloon.Position.above); } } @NotNull private static Component getAnchor(@NotNull JRootPane pane) { Component tabWrapper = UIUtil.findComponentOfType(pane, TabbedPaneWrapper.TabWrapper.class); if (tabWrapper != null) return tabWrapper; Component splitters = UIUtil.findComponentOfType(pane, EditorsSplitters.class); if (splitters != null) return splitters; FileEditorManagerEx ex = FileEditorManagerEx.getInstanceEx(ProjectUtil.guessCurrentProject(pane)); return ex == null ? pane : ex.getSplitters(); } public Couple<String> setText(@Nullable final String text, @Nullable final String requestor) { if (StringUtil.isEmpty(text) && !Comparing.equal(requestor, myCurrentRequestor) && !EventLog.LOG_REQUESTOR.equals(requestor)) { return Couple.of(myInfoPanel.getText(), myCurrentRequestor); } boolean logMode = myInfoPanel.updateText(EventLog.LOG_REQUESTOR.equals(requestor) ? "" : text); myCurrentRequestor = logMode ? EventLog.LOG_REQUESTOR : requestor; return Couple.of(text, requestor); } public void setRefreshVisible(final boolean visible) { UIUtil.invokeLaterIfNeeded(new Runnable() { @Override public void run() { myRefreshAlarm.cancelAllRequests(); myRefreshAlarm.addRequest(new Runnable() { @Override public void run() { if (visible) { myRefreshIcon.resume(); } else { myRefreshIcon.suspend(); } myRefreshIcon.revalidate(); myRefreshIcon.repaint(); } }, visible ? 100 : 300); } }); } public void setRefreshToolTipText(final String tooltip) { myRefreshIcon.setToolTipText(tooltip); } public BalloonHandler notifyByBalloon(MessageType type, String htmlBody, @Nullable Icon icon, @Nullable HyperlinkListener listener) { final Balloon balloon = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder( htmlBody.replace("\n", "<br>"), icon != null ? icon : type.getDefaultIcon(), type.getPopupBackground(), listener).createBalloon(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Component comp = InfoAndProgressPanel.this; if (comp.isShowing()) { int offset = comp.getHeight() / 2; Point point = new Point(comp.getWidth() - offset, comp.getHeight() - offset); balloon.show(new RelativePoint(comp, point), Balloon.Position.above); } else { final JRootPane rootPane = SwingUtilities.getRootPane(comp); if (rootPane != null && rootPane.isShowing()) { final Container contentPane = rootPane.getContentPane(); final Rectangle bounds = contentPane.getBounds(); final Point target = UIUtil.getCenterPoint(bounds, JBUI.size(1, 1)); target.y = bounds.height - 3; balloon.show(new RelativePoint(contentPane, target), Balloon.Position.above); } } } }); return new BalloonHandler() { @Override public void hide() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { balloon.hide(); } }); } }; } private static class InlineLayout extends AbstractLayoutManager { private int myProgressWidth; @Override public Dimension preferredLayoutSize(final Container parent) { Dimension result = new Dimension(); for (int i = 0; i < parent.getComponentCount(); i++) { final Dimension prefSize = parent.getComponent(i).getPreferredSize(); result.width += prefSize.width; result.height = Math.max(prefSize.height, result.height); } return result; } @Override public void layoutContainer(final Container parent) { assert parent.getComponentCount() == 2; // 1. info; 2. progress Component infoPanel = parent.getComponent(0); Component progressPanel = parent.getComponent(1); int progressPrefWidth = progressPanel.getPreferredSize().width; final Dimension size = parent.getSize(); int maxProgressWidth = (int) (size.width * 0.8); int minProgressWidth = (int) (size.width * 0.5); if (progressPrefWidth > myProgressWidth) { myProgressWidth = progressPrefWidth; } if (myProgressWidth > maxProgressWidth) { myProgressWidth = maxProgressWidth; } if (myProgressWidth < minProgressWidth) { myProgressWidth = minProgressWidth; } infoPanel.setBounds(0, 0, size.width - myProgressWidth, size.height); progressPanel.setBounds(size.width - myProgressWidth, 0, myProgressWidth, size.height); } } @NotNull private InlineProgressIndicator createInlineDelegate(@NotNull TaskInfo info, @NotNull ProgressIndicatorEx original, final boolean compact) { final Collection<InlineProgressIndicator> inlines = myOriginal2Inlines.get(original); if (inlines != null) { for (InlineProgressIndicator eachInline : inlines) { if (eachInline.isCompact() == compact) return eachInline; } } final InlineProgressIndicator inline = new MyInlineProgressIndicator(compact, info, original); myInline2Original.put(inline, original); myOriginal2Inlines.put(original, inline); if (compact) { inline.getComponent().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { handle(e); } @Override public void mouseReleased(MouseEvent e) { handle(e); } }); } return inline; } private void triggerPopupShowing() { if (myPopup.isShowing()) { hideProcessPopup(); } else { openProcessPopup(true); } } private void restoreEmptyStatus() { removeAll(); setLayout(new BorderLayout()); add(myRefreshAndInfoPanel, BorderLayout.CENTER); myProgressIcon.suspend(); Container iconParent = myProgressIcon.getParent(); if (iconParent != null) { iconParent.remove(myProgressIcon); // to prevent leaks to this removed parent via progress icon } myRefreshAndInfoPanel.revalidate(); myRefreshAndInfoPanel.repaint(); } //private String formatTime(long t) { // if (t < 1000) return "< 1 sec"; // if (t < 60 * 1000) return (t / 1000) + " sec"; // return "~" + (int)Math.ceil(t / (60 * 1000f)) + " min"; //} public boolean isProcessWindowOpen() { return myPopup.isShowing(); } public void setProcessWindowOpen(final boolean open) { if (open) { openProcessPopup(true); } else { hideProcessPopup(); } } private class MyInlineProgressIndicator extends InlineProgressIndicator { private ProgressIndicatorEx myOriginal; public MyInlineProgressIndicator(final boolean compact, @NotNull TaskInfo task, @NotNull ProgressIndicatorEx original) { super(compact, task); myOriginal = original; original.addStateDelegate(this); addStateDelegate(new AbstractProgressIndicatorExBase(){ @Override public void cancel() { super.cancel(); updateProgress(); } }); } @Override public void stop() { super.stop(); updateProgress(); } @Override protected boolean isFinished() { TaskInfo info = getInfo(); return info == null || isFinished(info); } @Override public void finish(@NotNull final TaskInfo task) { super.finish(task); queueRunningUpdate(new Runnable() { @Override public void run() { removeProgress(MyInlineProgressIndicator.this); } }); } @Override public void dispose() { super.dispose(); myOriginal = null; } @Override protected void cancelRequest() { myOriginal.cancel(); } @Override protected void queueProgressUpdate(final Runnable update) { myUpdateQueue.queue(new Update(MyInlineProgressIndicator.this, false, 1) { @Override public void run() { update.run(); } }); } @Override protected void queueRunningUpdate(final Runnable update) { myUpdateQueue.queue(new Update(new Object(), false, 0) { @Override public void run() { ApplicationManager.getApplication().invokeLater(update); } }); } } private void runQuery() { if (getRootPane() == null) return; Set<InlineProgressIndicator> indicators = getCurrentInlineIndicators(); if (indicators.isEmpty()) return; for (InlineProgressIndicator each : indicators) { each.updateProgress(); } myQueryAlarm.cancelAllRequests(); myQueryAlarm.addRequest(new Runnable() { @Override public void run() { runQuery(); } }, 2000); } @NotNull private Set<InlineProgressIndicator> getCurrentInlineIndicators() { synchronized (myOriginals) { return myInline2Original.keySet(); } } }
fix status bar progress leaks
platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java
fix status bar progress leaks
Java
apache-2.0
ac96bb49b9fab173ea9d38d1b760274e3cd9cd98
0
drankye/directory-server,apache/directory-server,drankye/directory-server,darranl/directory-server,lucastheisen/apache-directory-server,apache/directory-server,darranl/directory-server,lucastheisen/apache-directory-server
/* * 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.directory.server.ldap.handlers; import java.util.concurrent.TimeUnit; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.entry.ClonedServerEntry; import org.apache.directory.server.core.entry.ServerEntryUtils; import org.apache.directory.server.core.entry.ServerStringValue; import org.apache.directory.server.core.event.EventType; import org.apache.directory.server.core.event.NotificationCriteria; import org.apache.directory.server.core.filtering.EntryFilteringCursor; import org.apache.directory.server.core.partition.PartitionNexus; import org.apache.directory.server.ldap.LdapSession; import org.apache.directory.shared.ldap.codec.util.LdapURLEncodingException; import org.apache.directory.shared.ldap.constants.SchemaConstants; import org.apache.directory.shared.ldap.entry.EntryAttribute; import org.apache.directory.shared.ldap.entry.Value; import org.apache.directory.shared.ldap.exception.OperationAbandonedException; import org.apache.directory.shared.ldap.filter.EqualityNode; import org.apache.directory.shared.ldap.filter.OrNode; import org.apache.directory.shared.ldap.filter.PresenceNode; import org.apache.directory.shared.ldap.message.LdapResult; import org.apache.directory.shared.ldap.message.ManageDsaITControl; import org.apache.directory.shared.ldap.message.PersistentSearchControl; import org.apache.directory.shared.ldap.message.ReferralImpl; import org.apache.directory.shared.ldap.message.Response; import org.apache.directory.shared.ldap.message.ResultCodeEnum; import org.apache.directory.shared.ldap.filter.SearchScope; import org.apache.directory.shared.ldap.message.SearchRequest; import org.apache.directory.shared.ldap.message.SearchResponseDone; import org.apache.directory.shared.ldap.message.SearchResponseEntry; import org.apache.directory.shared.ldap.message.SearchResponseEntryImpl; import org.apache.directory.shared.ldap.message.SearchResponseReference; import org.apache.directory.shared.ldap.message.SearchResponseReferenceImpl; import org.apache.directory.shared.ldap.name.LdapDN; import org.apache.directory.shared.ldap.schema.AttributeType; import org.apache.directory.shared.ldap.util.LdapURL; import org.apache.mina.common.IoService; import org.apache.mina.common.TrafficMask; import org.apache.mina.common.WriteFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.directory.server.ldap.LdapServer.NO_SIZE_LIMIT; import static org.apache.directory.server.ldap.LdapServer.NO_TIME_LIMIT; import javax.naming.NamingException; /** * A handler for processing search requests. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev: 664302 $ */ public class SearchHandler extends ReferralAwareRequestHandler<SearchRequest> { private static final Logger LOG = LoggerFactory.getLogger( SearchHandler.class ); /** Speedup for logs */ private static final boolean IS_DEBUG = LOG.isDebugEnabled(); /** cached to save redundant lookups into registries */ private AttributeType objectClassAttributeType; /** * Constructs a new filter EqualityNode asserting that a candidate * objectClass is a referral. * * @param session the {@link LdapSession} to construct the node for * @return the {@link EqualityNode} (objectClass=referral) non-normalized * @throws Exception in the highly unlikely event of schema related failures */ private EqualityNode<String> newIsReferralEqualityNode( LdapSession session ) throws Exception { if ( objectClassAttributeType == null ) { objectClassAttributeType = session.getCoreSession().getDirectoryService().getRegistries() .getAttributeTypeRegistry().lookup( SchemaConstants.OBJECT_CLASS_AT ); } EqualityNode<String> ocIsReferral = new EqualityNode<String>( SchemaConstants.OBJECT_CLASS_AT, new ServerStringValue( objectClassAttributeType, SchemaConstants.REFERRAL_OC ) ); return ocIsReferral; } /** * Handles search requests containing the persistent search control but * delegates to doSimpleSearch() if the changesOnly parameter of the * control is set to false. * * @param session the LdapSession for which this search is conducted * @param req the search request containing the persistent search control * @param psearchControl the persistent search control extracted * @throws Exception if failures are encountered while searching */ private void handlePersistentSearch( LdapSession session, SearchRequest req, PersistentSearchControl psearchControl ) throws Exception { /* * We want the search to complete first before we start listening to * events when the control does NOT specify changes ONLY mode. */ if ( ! psearchControl.isChangesOnly() ) { SearchResponseDone done = doSimpleSearch( session, req ); // ok if normal search beforehand failed somehow quickly abandon psearch if ( done.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS ) { session.getIoSession().write( done ); return; } } if ( req.isAbandoned() ) { return; } // now we process entries forever as they change PersistentSearchListener handler = new PersistentSearchListener( session, req ); // compose notification criteria and add the listener to the event // service using that notification criteria to determine which events // are to be delivered to the persistent search issuing client NotificationCriteria criteria = new NotificationCriteria(); criteria.setAliasDerefMode( req.getDerefAliases() ); criteria.setBase( req.getBase() ); criteria.setFilter( req.getFilter() ); criteria.setScope( req.getScope() ); criteria.setEventMask( EventType.getEventTypes( psearchControl.getChangeTypes() ) ); getLdapServer().getDirectoryService().getEventService().addListener( handler, criteria ); req.addAbandonListener( new SearchAbandonListener( ldapServer, handler ) ); return; } /** * Handles search requests on the RootDSE. * * @param session the LdapSession for which this search is conducted * @param req the search request on the RootDSE * @throws Exception if failures are encountered while searching */ private void handleRootDseSearch( LdapSession session, SearchRequest req ) throws Exception { EntryFilteringCursor cursor = null; try { cursor = session.getCoreSession().search( req ); // Position the cursor at the beginning cursor.beforeFirst(); boolean hasRootDSE = false; while ( cursor.next() ) { if ( hasRootDSE ) { // This is an error ! We should never find more than one rootDSE ! LOG.error( "Got back more than one entry for search on RootDSE which means " + "Cursor is not functioning properly!" ); } else { hasRootDSE = true; ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); } } // write the SearchResultDone message session.getIoSession().write( req.getResultResponse() ); } finally { // Close the cursor now. if ( cursor != null ) { try { cursor.close(); } catch ( NamingException e ) { LOG.error( "failed on list.close()", e ); } } } } /** * Based on the server maximum time limits configured for search and the * requested time limits this method determines if at all to replace the * default ClosureMonitor of the result set Cursor with one that closes * the Cursor when either server mandated or request mandated time limits * are reached. * * @param req the {@link SearchRequest} issued * @param session the {@link LdapSession} on which search was requested * @param cursor the {@link EntryFilteringCursor} over the search results */ private void setTimeLimitsOnCursor( SearchRequest req, LdapSession session, final EntryFilteringCursor cursor ) { // Don't bother setting time limits for administrators if ( session.getCoreSession().isAnAdministrator() && req.getTimeLimit() == NO_TIME_LIMIT ) { return; } /* * Non administrator based searches are limited by time if the server * has been configured with unlimited time and the request specifies * unlimited search time */ if ( ldapServer.getMaxTimeLimit() == NO_TIME_LIMIT && req.getTimeLimit() == NO_TIME_LIMIT ) { return; } /* * If the non-administrator user specifies unlimited time but the server * is configured to limit the search time then we limit by the max time * allowed by the configuration */ if ( req.getTimeLimit() == 0 ) { cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) ); return; } /* * If the non-administrative user specifies a time limit equal to or * less than the maximum limit configured in the server then we * constrain search by the amount specified in the request */ if ( ldapServer.getMaxTimeLimit() >= req.getTimeLimit() ) { cursor.setClosureMonitor( new SearchTimeLimitingMonitor( req.getTimeLimit(), TimeUnit.SECONDS ) ); return; } /* * Here the non-administrative user's requested time limit is greater * than what the server's configured maximum limit allows so we limit * the search to the configured limit */ cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) ); } private int getSearchSizeLimits( SearchRequest req, LdapSession session ) { LOG.debug( "req size limit = {}, configured size limit = {}", req.getSizeLimit(), ldapServer.getMaxSizeLimit() ); // Don't bother setting size limits for administrators that don't ask for it if ( session.getCoreSession().isAnAdministrator() && req.getSizeLimit() == NO_SIZE_LIMIT ) { return NO_SIZE_LIMIT; } // Don't bother setting size limits for administrators that don't ask for it if ( session.getCoreSession().isAnAdministrator() ) { return req.getSizeLimit(); } /* * Non administrator based searches are limited by size if the server * has been configured with unlimited size and the request specifies * unlimited search size */ if ( ldapServer.getMaxSizeLimit() == NO_SIZE_LIMIT && req.getSizeLimit() == NO_SIZE_LIMIT ) { return NO_SIZE_LIMIT; } /* * If the non-administrator user specifies unlimited size but the server * is configured to limit the search size then we limit by the max size * allowed by the configuration */ if ( req.getSizeLimit() == 0 ) { return ldapServer.getMaxSizeLimit(); } if ( ldapServer.getMaxSizeLimit() == NO_SIZE_LIMIT ) { return req.getSizeLimit(); } /* * If the non-administrative user specifies a size limit equal to or * less than the maximum limit configured in the server then we * constrain search by the amount specified in the request */ if ( ldapServer.getMaxSizeLimit() >= req.getSizeLimit() ) { return req.getSizeLimit(); } /* * Here the non-administrative user's requested size limit is greater * than what the server's configured maximum limit allows so we limit * the search to the configured limit */ return ldapServer.getMaxSizeLimit(); } /** * Conducts a simple search across the result set returning each entry * back except for the search response done. This is calculated but not * returned so the persistent search mechanism can leverage this method * along with standard search. * * @param session the LDAP session object for this request * @param req the search request * @return the result done * @throws Exception if there are failures while processing the request */ private SearchResponseDone doSimpleSearch( LdapSession session, SearchRequest req ) throws Exception { /* * Iterate through all search results building and sending back responses * for each search result returned. */ EntryFilteringCursor cursor = null; try { LdapResult ldapResult = req.getResultResponse().getLdapResult(); cursor = session.getCoreSession().search( req ); req.addAbandonListener( new SearchAbandonListener( ldapServer, cursor ) ); setTimeLimitsOnCursor( req, session, cursor ); final int sizeLimit = getSearchSizeLimits( req, session ); LOG.debug( "using {} for size limit", sizeLimit ); // Position the cursor at the beginning cursor.beforeFirst(); if ( sizeLimit == NO_SIZE_LIMIT ) { while ( cursor.next() ) { if ( session.getIoSession().isClosing() ) { break; } ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); } } else { int count = 0; while ( cursor.next() ) { if ( session.getIoSession().isClosing() ) { break; } if ( count < sizeLimit ) { ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); count++; } else { // DO NOT WRITE THE RESPONSE - JUST RETURN IT ldapResult.setResultCode( ResultCodeEnum.SIZE_LIMIT_EXCEEDED ); return ( SearchResponseDone ) req.getResultResponse(); } } } // DO NOT WRITE THE RESPONSE - JUST RETURN IT ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); return ( SearchResponseDone ) req.getResultResponse(); } finally { if ( cursor != null ) { try { cursor.close(); } catch ( NamingException e ) { LOG.error( "failed on list.close()", e ); } } } } /** * Generates a response for an entry retrieved from the server core based * on the nature of the request with respect to referral handling. This * method will either generate a SearchResponseEntry or a * SearchResponseReference depending on if the entry is a referral or if * the ManageDSAITControl has been enabled. * * @param req the search request * @param entry the entry to be handled * @return the response for the entry * @throws Exception if there are problems in generating the response */ private Response generateResponse( LdapSession session, SearchRequest req, ClonedServerEntry entry ) throws Exception { EntryAttribute ref = entry.getOriginalEntry().get( SchemaConstants.REF_AT ); boolean hasManageDsaItControl = req.getControls().containsKey( ManageDsaITControl.CONTROL_OID ); if ( ref != null && ! hasManageDsaItControl ) { SearchResponseReference respRef; respRef = new SearchResponseReferenceImpl( req.getMessageId() ); respRef.setReferral( new ReferralImpl() ); for ( Value<?> val : ref ) { String url = ( String ) val.get(); if ( ! url.startsWith( "ldap" ) ) { respRef.getReferral().addLdapUrl( url ); } LdapURL ldapUrl = new LdapURL(); ldapUrl.setForceScopeRendering( true ); try { ldapUrl.parse( url.toCharArray() ); } catch ( LdapURLEncodingException e ) { LOG.error( "Bad URL ({}) for ref in {}. Reference will be ignored.", url, entry ); } switch( req.getScope() ) { case SUBTREE: ldapUrl.setScope( SearchScope.SUBTREE.getJndiScope() ); break; case ONELEVEL: // one level here is object level on remote server ldapUrl.setScope( SearchScope.OBJECT.getJndiScope() ); break; default: throw new IllegalStateException( "Unexpected base scope." ); } respRef.getReferral().addLdapUrl( ldapUrl.toString() ); } return respRef; } else { SearchResponseEntry respEntry; respEntry = new SearchResponseEntryImpl( req.getMessageId() ); respEntry.setAttributes( ServerEntryUtils.toAttributesImpl( entry ) ); respEntry.setObjectName( entry.getDn() ); return respEntry; } } /** * Alters the filter expression based on the presence of the * ManageDsaIT control. If the control is not present, the search * filter will be altered to become a disjunction with two terms. * The first term is the original filter. The second term is a * (objectClass=referral) assertion. When OR'd together these will * make sure we get all referrals so we can process continuations * properly without having the filter remove them from the result * set. * * NOTE: original filter is first since most entries are not referrals * so it has a higher probability on average of accepting and shorting * evaluation before having to waste cycles trying to evaluate if the * entry is a referral. * * @param session the session to use to construct the filter (schema access) * @param req the request to get the original filter from * @throws Exception if there are schema access problems */ public void modifyFilter( LdapSession session, SearchRequest req ) throws Exception { if ( req.hasControl( ManageDsaITControl.CONTROL_OID ) ) { return; } /* * Do not add the OR'd (objectClass=referral) expression if the user * searches for the subSchemaSubEntry as the SchemaIntercepter can't * handle an OR'd filter. */ if ( isSubSchemaSubEntrySearch( session, req ) ) { return; } /* * Most of the time the search filter is just (objectClass=*) and if * this is the case then there's no reason at all to OR this with an * (objectClass=referral). If we detect this case then we leave it * as is to represent the OR condition: * * (| (objectClass=referral)(objectClass=*)) == (objectClass=*) */ if ( req.getFilter() instanceof PresenceNode ) { PresenceNode presenceNode = ( PresenceNode ) req.getFilter(); AttributeType at = session.getCoreSession().getDirectoryService() .getRegistries().getAttributeTypeRegistry().lookup( presenceNode.getAttribute() ); if ( at.getOid().equals( SchemaConstants.OBJECT_CLASS_AT_OID ) ) { return; } } // using varags to add two expressions to an OR node req.setFilter( new OrNode( req.getFilter(), newIsReferralEqualityNode( session ) ) ); } /** * Main message handing method for search requests. This will be called * even if the ManageDsaIT control is present because the super class does * not know that the search operation has more to do after finding the * base. The call to this means that finding the base can ignore * referrals. * * @param session the associated session * @param req the received SearchRequest */ public void handleIgnoringReferrals( LdapSession session, LdapDN reqTargetDn, ClonedServerEntry entry, SearchRequest req ) { if ( IS_DEBUG ) { LOG.debug( "Message received: {}", req.toString() ); } // add the search request to the registry of outstanding requests for this session session.registerOutstandingRequest( req ); try { // modify the filter to affect continuation support modifyFilter( session, req ); // =============================================================== // Handle search in rootDSE differently. // =============================================================== if ( isRootDSESearch( req ) ) { handleRootDseSearch( session, req ); return; } // =============================================================== // Handle psearch differently // =============================================================== PersistentSearchControl psearchControl = ( PersistentSearchControl ) req.getControls().get( PersistentSearchControl.CONTROL_OID ); if ( psearchControl != null ) { handlePersistentSearch( session, req, psearchControl ); // do not unregister the outstanding request unlike below return; } // =============================================================== // Handle regular search requests from here down // =============================================================== SearchResponseDone done = doSimpleSearch( session, req ); session.getIoSession().write( done ); session.unregisterOutstandingRequest( req ); } catch ( Exception e ) { /* * From RFC 2251 Section 4.11: * * In the event that a server receives an Abandon Request on a Search * operation in the midst of transmitting responses to the Search, that * server MUST cease transmitting entry responses to the abandoned * request immediately, and MUST NOT send the SearchResultDone. Of * course, the server MUST ensure that only properly encoded LDAPMessage * PDUs are transmitted. * * SO DON'T SEND BACK ANYTHING!!!!! */ if ( e instanceof OperationAbandonedException ) { return; } handleException( session, req, e ); } } /** * Determines if a search request is on the RootDSE of the server. * * It is a RootDSE search if : * - the base DN is empty * - and the scope is BASE OBJECT * - and the filter is (ObjectClass = *) * * (RFC 4511, 5.1, par. 1 & 2) * * @param req the request issued * @return true if the search is on the RootDSE false otherwise */ private static boolean isRootDSESearch( SearchRequest req ) { boolean isBaseIsRoot = req.getBase().isEmpty(); boolean isBaseScope = req.getScope() == SearchScope.OBJECT; boolean isRootDSEFilter = false; if ( req.getFilter() instanceof PresenceNode ) { String attribute = ( ( PresenceNode ) req.getFilter() ).getAttribute(); isRootDSEFilter = attribute.equalsIgnoreCase( SchemaConstants.OBJECT_CLASS_AT ) || attribute.equals( SchemaConstants.OBJECT_CLASS_AT_OID ); } return isBaseIsRoot && isBaseScope && isRootDSEFilter; } /** * <p> * Determines if a search request is a subSchemaSubEntry search. * </p> * <p> * It is a schema search if: * - the base DN is the DN of the subSchemaSubEntry of the root DSE * - and the scope is BASE OBJECT * - and the filter is (objectClass=subschema) * (RFC 4512, 4.4,) * </p> * <p> * However in this method we only check the first condition to avoid * performance issues. * </p> * * @param session the LDAP session * @param req the request issued * * @return true if the search is on the subSchemaSubEntry, false otherwise * * @throws Exception the exception */ private static boolean isSubSchemaSubEntrySearch( LdapSession session, SearchRequest req ) throws Exception { LdapDN base = req.getBase(); String baseNormForm = ( base.isNormalized() ? base.getNormName() : base.toNormName() ); DirectoryService ds = session.getCoreSession().getDirectoryService(); PartitionNexus nexus = ds.getPartitionNexus(); Value<?> subschemaSubentry = nexus.getRootDSE( null ).get( SchemaConstants.SUBSCHEMA_SUBENTRY_AT ).get(); LdapDN subschemaSubentryDn = new LdapDN( ( String ) ( subschemaSubentry.get() ) ); subschemaSubentryDn.normalize( ds.getRegistries().getAttributeTypeRegistry().getNormalizerMapping() ); String subschemaSubentryDnNorm = subschemaSubentryDn.getNormName(); return subschemaSubentryDnNorm.equals( baseNormForm ); } }
protocol-ldap/src/main/java/org/apache/directory/server/ldap/handlers/SearchHandler.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.directory.server.ldap.handlers; import java.util.concurrent.TimeUnit; import org.apache.directory.server.core.DirectoryService; import org.apache.directory.server.core.entry.ClonedServerEntry; import org.apache.directory.server.core.entry.ServerEntryUtils; import org.apache.directory.server.core.entry.ServerStringValue; import org.apache.directory.server.core.event.EventType; import org.apache.directory.server.core.event.NotificationCriteria; import org.apache.directory.server.core.filtering.EntryFilteringCursor; import org.apache.directory.server.core.partition.PartitionNexus; import org.apache.directory.server.ldap.LdapSession; import org.apache.directory.shared.ldap.codec.util.LdapURLEncodingException; import org.apache.directory.shared.ldap.constants.SchemaConstants; import org.apache.directory.shared.ldap.entry.EntryAttribute; import org.apache.directory.shared.ldap.entry.Value; import org.apache.directory.shared.ldap.exception.OperationAbandonedException; import org.apache.directory.shared.ldap.filter.EqualityNode; import org.apache.directory.shared.ldap.filter.OrNode; import org.apache.directory.shared.ldap.filter.PresenceNode; import org.apache.directory.shared.ldap.message.LdapResult; import org.apache.directory.shared.ldap.message.ManageDsaITControl; import org.apache.directory.shared.ldap.message.PersistentSearchControl; import org.apache.directory.shared.ldap.message.ReferralImpl; import org.apache.directory.shared.ldap.message.Response; import org.apache.directory.shared.ldap.message.ResultCodeEnum; import org.apache.directory.shared.ldap.filter.SearchScope; import org.apache.directory.shared.ldap.message.SearchRequest; import org.apache.directory.shared.ldap.message.SearchResponseDone; import org.apache.directory.shared.ldap.message.SearchResponseEntry; import org.apache.directory.shared.ldap.message.SearchResponseEntryImpl; import org.apache.directory.shared.ldap.message.SearchResponseReference; import org.apache.directory.shared.ldap.message.SearchResponseReferenceImpl; import org.apache.directory.shared.ldap.name.LdapDN; import org.apache.directory.shared.ldap.schema.AttributeType; import org.apache.directory.shared.ldap.util.LdapURL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.directory.server.ldap.LdapServer.NO_SIZE_LIMIT; import static org.apache.directory.server.ldap.LdapServer.NO_TIME_LIMIT; import javax.naming.NamingException; /** * A handler for processing search requests. * * @author <a href="mailto:[email protected]">Apache Directory Project</a> * @version $Rev: 664302 $ */ public class SearchHandler extends ReferralAwareRequestHandler<SearchRequest> { private static final Logger LOG = LoggerFactory.getLogger( SearchHandler.class ); /** Speedup for logs */ private static final boolean IS_DEBUG = LOG.isDebugEnabled(); /** cached to save redundant lookups into registries */ private AttributeType objectClassAttributeType; /** * Constructs a new filter EqualityNode asserting that a candidate * objectClass is a referral. * * @param session the {@link LdapSession} to construct the node for * @return the {@link EqualityNode} (objectClass=referral) non-normalized * @throws Exception in the highly unlikely event of schema related failures */ private EqualityNode<String> newIsReferralEqualityNode( LdapSession session ) throws Exception { if ( objectClassAttributeType == null ) { objectClassAttributeType = session.getCoreSession().getDirectoryService().getRegistries() .getAttributeTypeRegistry().lookup( SchemaConstants.OBJECT_CLASS_AT ); } EqualityNode<String> ocIsReferral = new EqualityNode<String>( SchemaConstants.OBJECT_CLASS_AT, new ServerStringValue( objectClassAttributeType, SchemaConstants.REFERRAL_OC ) ); return ocIsReferral; } /** * Handles search requests containing the persistent search control but * delegates to doSimpleSearch() if the changesOnly parameter of the * control is set to false. * * @param session the LdapSession for which this search is conducted * @param req the search request containing the persistent search control * @param psearchControl the persistent search control extracted * @throws Exception if failures are encountered while searching */ private void handlePersistentSearch( LdapSession session, SearchRequest req, PersistentSearchControl psearchControl ) throws Exception { /* * We want the search to complete first before we start listening to * events when the control does NOT specify changes ONLY mode. */ if ( ! psearchControl.isChangesOnly() ) { SearchResponseDone done = doSimpleSearch( session, req ); // ok if normal search beforehand failed somehow quickly abandon psearch if ( done.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS ) { session.getIoSession().write( done ); return; } } if ( req.isAbandoned() ) { return; } // now we process entries forever as they change PersistentSearchListener handler = new PersistentSearchListener( session, req ); // compose notification criteria and add the listener to the event // service using that notification criteria to determine which events // are to be delivered to the persistent search issuing client NotificationCriteria criteria = new NotificationCriteria(); criteria.setAliasDerefMode( req.getDerefAliases() ); criteria.setBase( req.getBase() ); criteria.setFilter( req.getFilter() ); criteria.setScope( req.getScope() ); criteria.setEventMask( EventType.getEventTypes( psearchControl.getChangeTypes() ) ); getLdapServer().getDirectoryService().getEventService().addListener( handler, criteria ); req.addAbandonListener( new SearchAbandonListener( ldapServer, handler ) ); return; } /** * Handles search requests on the RootDSE. * * @param session the LdapSession for which this search is conducted * @param req the search request on the RootDSE * @throws Exception if failures are encountered while searching */ private void handleRootDseSearch( LdapSession session, SearchRequest req ) throws Exception { EntryFilteringCursor cursor = null; try { cursor = session.getCoreSession().search( req ); // Position the cursor at the beginning cursor.beforeFirst(); boolean hasRootDSE = false; while ( cursor.next() ) { if ( hasRootDSE ) { // This is an error ! We should never find more than one rootDSE ! LOG.error( "Got back more than one entry for search on RootDSE which means " + "Cursor is not functioning properly!" ); } else { hasRootDSE = true; ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); } } // write the SearchResultDone message session.getIoSession().write( req.getResultResponse() ); } finally { // Close the cursor now. if ( cursor != null ) { try { cursor.close(); } catch ( NamingException e ) { LOG.error( "failed on list.close()", e ); } } } } /** * Based on the server maximum time limits configured for search and the * requested time limits this method determines if at all to replace the * default ClosureMonitor of the result set Cursor with one that closes * the Cursor when either server mandated or request mandated time limits * are reached. * * @param req the {@link SearchRequest} issued * @param session the {@link LdapSession} on which search was requested * @param cursor the {@link EntryFilteringCursor} over the search results */ private void setTimeLimitsOnCursor( SearchRequest req, LdapSession session, final EntryFilteringCursor cursor ) { // Don't bother setting time limits for administrators if ( session.getCoreSession().isAnAdministrator() && req.getTimeLimit() == NO_TIME_LIMIT ) { return; } /* * Non administrator based searches are limited by time if the server * has been configured with unlimited time and the request specifies * unlimited search time */ if ( ldapServer.getMaxTimeLimit() == NO_TIME_LIMIT && req.getTimeLimit() == NO_TIME_LIMIT ) { return; } /* * If the non-administrator user specifies unlimited time but the server * is configured to limit the search time then we limit by the max time * allowed by the configuration */ if ( req.getTimeLimit() == 0 ) { cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) ); return; } /* * If the non-administrative user specifies a time limit equal to or * less than the maximum limit configured in the server then we * constrain search by the amount specified in the request */ if ( ldapServer.getMaxTimeLimit() >= req.getTimeLimit() ) { cursor.setClosureMonitor( new SearchTimeLimitingMonitor( req.getTimeLimit(), TimeUnit.SECONDS ) ); return; } /* * Here the non-administrative user's requested time limit is greater * than what the server's configured maximum limit allows so we limit * the search to the configured limit */ cursor.setClosureMonitor( new SearchTimeLimitingMonitor( ldapServer.getMaxTimeLimit(), TimeUnit.SECONDS ) ); } private int getSearchSizeLimits( SearchRequest req, LdapSession session ) { LOG.debug( "req size limit = {}, configured size limit = {}", req.getSizeLimit(), ldapServer.getMaxSizeLimit() ); // Don't bother setting size limits for administrators that don't ask for it if ( session.getCoreSession().isAnAdministrator() && req.getSizeLimit() == NO_SIZE_LIMIT ) { return NO_SIZE_LIMIT; } // Don't bother setting size limits for administrators that don't ask for it if ( session.getCoreSession().isAnAdministrator() ) { return req.getSizeLimit(); } /* * Non administrator based searches are limited by size if the server * has been configured with unlimited size and the request specifies * unlimited search size */ if ( ldapServer.getMaxSizeLimit() == NO_SIZE_LIMIT && req.getSizeLimit() == NO_SIZE_LIMIT ) { return NO_SIZE_LIMIT; } /* * If the non-administrator user specifies unlimited size but the server * is configured to limit the search size then we limit by the max size * allowed by the configuration */ if ( req.getSizeLimit() == 0 ) { return ldapServer.getMaxSizeLimit(); } if ( ldapServer.getMaxSizeLimit() == NO_SIZE_LIMIT ) { return req.getSizeLimit(); } /* * If the non-administrative user specifies a size limit equal to or * less than the maximum limit configured in the server then we * constrain search by the amount specified in the request */ if ( ldapServer.getMaxSizeLimit() >= req.getSizeLimit() ) { return req.getSizeLimit(); } /* * Here the non-administrative user's requested size limit is greater * than what the server's configured maximum limit allows so we limit * the search to the configured limit */ return ldapServer.getMaxSizeLimit(); } /** * Conducts a simple search across the result set returning each entry * back except for the search response done. This is calculated but not * returned so the persistent search mechanism can leverage this method * along with standard search. * * @param session the LDAP session object for this request * @param req the search request * @return the result done * @throws Exception if there are failures while processing the request */ private SearchResponseDone doSimpleSearch( LdapSession session, SearchRequest req ) throws Exception { /* * Iterate through all search results building and sending back responses * for each search result returned. */ EntryFilteringCursor cursor = null; try { LdapResult ldapResult = req.getResultResponse().getLdapResult(); cursor = session.getCoreSession().search( req ); req.addAbandonListener( new SearchAbandonListener( ldapServer, cursor ) ); setTimeLimitsOnCursor( req, session, cursor ); final int sizeLimit = getSearchSizeLimits( req, session ); LOG.debug( "using {} for size limit", sizeLimit ); // Position the cursor at the beginning cursor.beforeFirst(); if ( sizeLimit == NO_SIZE_LIMIT ) { while ( cursor.next() ) { ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); } } else { int count = 0; while ( cursor.next() ) { if ( count < sizeLimit ) { ClonedServerEntry entry = cursor.get(); session.getIoSession().write( generateResponse( session, req, entry ) ); count++; } else { // DO NOT WRITE THE RESPONSE - JUST RETURN IT ldapResult.setResultCode( ResultCodeEnum.SIZE_LIMIT_EXCEEDED ); return ( SearchResponseDone ) req.getResultResponse(); } } } // DO NOT WRITE THE RESPONSE - JUST RETURN IT ldapResult.setResultCode( ResultCodeEnum.SUCCESS ); return ( SearchResponseDone ) req.getResultResponse(); } finally { if ( cursor != null ) { try { cursor.close(); } catch ( NamingException e ) { LOG.error( "failed on list.close()", e ); } } } } /** * Generates a response for an entry retrieved from the server core based * on the nature of the request with respect to referral handling. This * method will either generate a SearchResponseEntry or a * SearchResponseReference depending on if the entry is a referral or if * the ManageDSAITControl has been enabled. * * @param req the search request * @param entry the entry to be handled * @return the response for the entry * @throws Exception if there are problems in generating the response */ private Response generateResponse( LdapSession session, SearchRequest req, ClonedServerEntry entry ) throws Exception { EntryAttribute ref = entry.getOriginalEntry().get( SchemaConstants.REF_AT ); boolean hasManageDsaItControl = req.getControls().containsKey( ManageDsaITControl.CONTROL_OID ); if ( ref != null && ! hasManageDsaItControl ) { SearchResponseReference respRef; respRef = new SearchResponseReferenceImpl( req.getMessageId() ); respRef.setReferral( new ReferralImpl() ); for ( Value<?> val : ref ) { String url = ( String ) val.get(); if ( ! url.startsWith( "ldap" ) ) { respRef.getReferral().addLdapUrl( url ); } LdapURL ldapUrl = new LdapURL(); ldapUrl.setForceScopeRendering( true ); try { ldapUrl.parse( url.toCharArray() ); } catch ( LdapURLEncodingException e ) { LOG.error( "Bad URL ({}) for ref in {}. Reference will be ignored.", url, entry ); } switch( req.getScope() ) { case SUBTREE: ldapUrl.setScope( SearchScope.SUBTREE.getJndiScope() ); break; case ONELEVEL: // one level here is object level on remote server ldapUrl.setScope( SearchScope.OBJECT.getJndiScope() ); break; default: throw new IllegalStateException( "Unexpected base scope." ); } respRef.getReferral().addLdapUrl( ldapUrl.toString() ); } return respRef; } else { SearchResponseEntry respEntry; respEntry = new SearchResponseEntryImpl( req.getMessageId() ); respEntry.setAttributes( ServerEntryUtils.toAttributesImpl( entry ) ); respEntry.setObjectName( entry.getDn() ); return respEntry; } } /** * Alters the filter expression based on the presence of the * ManageDsaIT control. If the control is not present, the search * filter will be altered to become a disjunction with two terms. * The first term is the original filter. The second term is a * (objectClass=referral) assertion. When OR'd together these will * make sure we get all referrals so we can process continuations * properly without having the filter remove them from the result * set. * * NOTE: original filter is first since most entries are not referrals * so it has a higher probability on average of accepting and shorting * evaluation before having to waste cycles trying to evaluate if the * entry is a referral. * * @param session the session to use to construct the filter (schema access) * @param req the request to get the original filter from * @throws Exception if there are schema access problems */ public void modifyFilter( LdapSession session, SearchRequest req ) throws Exception { if ( req.hasControl( ManageDsaITControl.CONTROL_OID ) ) { return; } /* * Do not add the OR'd (objectClass=referral) expression if the user * searches for the subSchemaSubEntry as the SchemaIntercepter can't * handle an OR'd filter. */ if ( isSubSchemaSubEntrySearch( session, req ) ) { return; } /* * Most of the time the search filter is just (objectClass=*) and if * this is the case then there's no reason at all to OR this with an * (objectClass=referral). If we detect this case then we leave it * as is to represent the OR condition: * * (| (objectClass=referral)(objectClass=*)) == (objectClass=*) */ if ( req.getFilter() instanceof PresenceNode ) { PresenceNode presenceNode = ( PresenceNode ) req.getFilter(); AttributeType at = session.getCoreSession().getDirectoryService() .getRegistries().getAttributeTypeRegistry().lookup( presenceNode.getAttribute() ); if ( at.getOid().equals( SchemaConstants.OBJECT_CLASS_AT_OID ) ) { return; } } // using varags to add two expressions to an OR node req.setFilter( new OrNode( req.getFilter(), newIsReferralEqualityNode( session ) ) ); } /** * Main message handing method for search requests. This will be called * even if the ManageDsaIT control is present because the super class does * not know that the search operation has more to do after finding the * base. The call to this means that finding the base can ignore * referrals. * * @param session the associated session * @param req the received SearchRequest */ public void handleIgnoringReferrals( LdapSession session, LdapDN reqTargetDn, ClonedServerEntry entry, SearchRequest req ) { if ( IS_DEBUG ) { LOG.debug( "Message received: {}", req.toString() ); } // add the search request to the registry of outstanding requests for this session session.registerOutstandingRequest( req ); try { // modify the filter to affect continuation support modifyFilter( session, req ); // =============================================================== // Handle search in rootDSE differently. // =============================================================== if ( isRootDSESearch( req ) ) { handleRootDseSearch( session, req ); return; } // =============================================================== // Handle psearch differently // =============================================================== PersistentSearchControl psearchControl = ( PersistentSearchControl ) req.getControls().get( PersistentSearchControl.CONTROL_OID ); if ( psearchControl != null ) { handlePersistentSearch( session, req, psearchControl ); // do not unregister the outstanding request unlike below return; } // =============================================================== // Handle regular search requests from here down // =============================================================== SearchResponseDone done = doSimpleSearch( session, req ); session.getIoSession().write( done ); session.unregisterOutstandingRequest( req ); } catch ( Exception e ) { /* * From RFC 2251 Section 4.11: * * In the event that a server receives an Abandon Request on a Search * operation in the midst of transmitting responses to the Search, that * server MUST cease transmitting entry responses to the abandoned * request immediately, and MUST NOT send the SearchResultDone. Of * course, the server MUST ensure that only properly encoded LDAPMessage * PDUs are transmitted. * * SO DON'T SEND BACK ANYTHING!!!!! */ if ( e instanceof OperationAbandonedException ) { return; } handleException( session, req, e ); } } /** * Determines if a search request is on the RootDSE of the server. * * It is a RootDSE search if : * - the base DN is empty * - and the scope is BASE OBJECT * - and the filter is (ObjectClass = *) * * (RFC 4511, 5.1, par. 1 & 2) * * @param req the request issued * @return true if the search is on the RootDSE false otherwise */ private static boolean isRootDSESearch( SearchRequest req ) { boolean isBaseIsRoot = req.getBase().isEmpty(); boolean isBaseScope = req.getScope() == SearchScope.OBJECT; boolean isRootDSEFilter = false; if ( req.getFilter() instanceof PresenceNode ) { String attribute = ( ( PresenceNode ) req.getFilter() ).getAttribute(); isRootDSEFilter = attribute.equalsIgnoreCase( SchemaConstants.OBJECT_CLASS_AT ) || attribute.equals( SchemaConstants.OBJECT_CLASS_AT_OID ); } return isBaseIsRoot && isBaseScope && isRootDSEFilter; } /** * <p> * Determines if a search request is a subSchemaSubEntry search. * </p> * <p> * It is a schema search if: * - the base DN is the DN of the subSchemaSubEntry of the root DSE * - and the scope is BASE OBJECT * - and the filter is (objectClass=subschema) * (RFC 4512, 4.4,) * </p> * <p> * However in this method we only check the first condition to avoid * performance issues. * </p> * * @param session the LDAP session * @param req the request issued * * @return true if the search is on the subSchemaSubEntry, false otherwise * * @throws Exception the exception */ private static boolean isSubSchemaSubEntrySearch( LdapSession session, SearchRequest req ) throws Exception { LdapDN base = req.getBase(); String baseNormForm = ( base.isNormalized() ? base.getNormName() : base.toNormName() ); DirectoryService ds = session.getCoreSession().getDirectoryService(); PartitionNexus nexus = ds.getPartitionNexus(); Value<?> subschemaSubentry = nexus.getRootDSE( null ).get( SchemaConstants.SUBSCHEMA_SUBENTRY_AT ).get(); LdapDN subschemaSubentryDn = new LdapDN( ( String ) ( subschemaSubentry.get() ) ); subschemaSubentryDn.normalize( ds.getRegistries().getAttributeTypeRegistry().getNormalizerMapping() ); String subschemaSubentryDnNorm = subschemaSubentryDn.getNormName(); return subschemaSubentryDnNorm.equals( baseNormForm ); } }
improving responsiveness of search to client death git-svn-id: 90776817adfbd895fc5cfa90f675377e0a62e745@688603 13f79535-47bb-0310-9956-ffa450edef68
protocol-ldap/src/main/java/org/apache/directory/server/ldap/handlers/SearchHandler.java
improving responsiveness of search to client death
Java
apache-2.0
43c9e3f506e4de1b9ca5c5bd4fbecaec204d1d9d
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
/** * */ package org.commcare.android.util; import java.text.Normalizer; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.os.Build; import android.support.v4.util.LruCache; import android.util.Pair; /** * @author ctsims * */ public class StringUtils { //TODO: Bro you can't just cache every fucking string ever. static LruCache<String, String> normalizationCache; static Pattern diacritics; //TODO: Really not sure about this size. Also, the LRU probably isn't really the best model here //since we'd _like_ for these caches to get cleaned up at _some_ point. static final private int cacheSize = 100 * 1024; /** * @param input A non-null string * @return a canonical version of the passed in string that is lower cased and has removed diacritical marks * like accents. */ @SuppressLint("NewApi") public synchronized static String normalize(String input) { if(normalizationCache == null) { normalizationCache = new LruCache<String, String>(cacheSize); diacritics = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); } String normalized = normalizationCache.get(input); if(normalized != null) { return normalizationCache.get(input);} //If we're above gingerbread we'll normalize this in NFD form //which helps a lot. Otherwise we won't be able to clear up some of those //issues, but we can at least still eliminate diacritics. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { normalized = Normalizer.normalize(input, Normalizer.Form.NFD); } else{ //TODO: I doubt it's worth it, but in theory we could run //some other normalization for the minority of pre-API9 //devices. normalized = input; } normalizationCache.put(input, normalized); return normalized; } /** * Computes the Levenshtein Distance between two strings. * * This code is sourced and unmodified from wikibooks under * the Creative Commons attribution share-alike 3.0 license and * by be re-used under the terms of that license. * * http://creativecommons.org/licenses/by-sa/3.0/ * * TODO: re-implement for efficiency/licensing possibly. * * @param s0 * @param s1 * * @return */ public static int LevenshteinDistance (String s0, String s1) { int len0 = s0.length()+1; int len1 = s1.length()+1; // the array of distances int[] cost = new int[len0]; int[] newcost = new int[len0]; // initial cost of skipping prefix in String s0 for(int i=0;i<len0;i++) cost[i]=i; // dynamicaly computing the array of distances // transformation cost for each letter in s1 for(int j=1;j<len1;j++) { // initial cost of skipping prefix in String s1 newcost[0]=j-1; // transformation cost for each letter in s0 for(int i=1;i<len0;i++) { // matching current letters in both strings int match = (s0.charAt(i-1)==s1.charAt(j-1))?0:1; // computing cost for each transformation int cost_replace = cost[i-1]+match; int cost_insert = cost[i]+1; int cost_delete = newcost[i-1]+1; // keep minimum cost newcost[i] = Math.min(Math.min(cost_insert, cost_delete),cost_replace ); } // swap cost/newcost arrays int[] swap=cost; cost=newcost; newcost=swap; } // the distance is the cost for transforming all letters in both strings return cost[len0-1]; } /** * Identifies whether two strings are close enough that they are likely to be * intended to be the same string. Fuzzy matching is only performed on strings that are * longer than a certain size. * * @param a * @param b * @return A pair with two values. First value represents a match: true if the two strings * meet CommCare's fuzzy match definition, false otherwise. Second value is the actual string * distance that was matched, in order to be able to rank or otherwise interpret results. */ public static Pair<Boolean, Integer> fuzzyMatch(String a, String b) { //tweakable parameter: Minimum length before edit distance //starts being used (this is probably not necessary, and //basically only makes sure that "at" doesn't match "or" or similar if(b.length() > 3) { int distance = StringUtils.LevenshteinDistance(a, b); //tweakable parameter: edit distance past string length disparity if(distance <= 2) { return Pair.create(true, distance); } } return Pair.create(false, -1); } }
app/src/org/commcare/android/util/StringUtils.java
/** * */ package org.commcare.android.util; import java.text.Normalizer; import java.util.regex.Pattern; import android.annotation.SuppressLint; import android.os.Build; import android.support.v4.util.LruCache; import android.util.Pair; /** * @author ctsims * */ public class StringUtils { //TODO: Bro you can't just cache every fucking string ever. static LruCache<String, String> normalizationCache; static Pattern diacritics; //TODO: Really not sure about this size. Also, the LRU probably isn't really the best model here //since we'd _like_ for these caches to get cleaned up at _some_ point. static final private int cacheSize = 100 * 1024; /** * @param input A non-null string * @return a canonical version of the passed in string that is lower cased and has removed diacritical marks * like accents. */ @SuppressLint("NewApi") public synchronized static String normalize(String input) { if(normalizationCache == null) { normalizationCache = new LruCache<String, String>(cacheSize); diacritics = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); } String normalized = normalizationCache.get(input); if(normalized != null) { return normalizationCache.get(input);} //If we're above gingerbread we'll normalize this in NFD form //which helps a lot. Otherwise we won't be able to clear up some of those //issues, but we can at least still eliminate diacritics. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { input = Normalizer.normalize(input, Normalizer.Form.NFD); } else{ //TODO: I doubt it's worth it, but in theory we could run //some other normalization for the minority of pre-API9 //devices. } normalizationCache.put(input, normalized); return normalized; } /** * Computes the Levenshtein Distance between two strings. * * This code is sourced and unmodified from wikibooks under * the Creative Commons attribution share-alike 3.0 license and * by be re-used under the terms of that license. * * http://creativecommons.org/licenses/by-sa/3.0/ * * TODO: re-implement for efficiency/licensing possibly. * * @param s0 * @param s1 * * @return */ public static int LevenshteinDistance (String s0, String s1) { int len0 = s0.length()+1; int len1 = s1.length()+1; // the array of distances int[] cost = new int[len0]; int[] newcost = new int[len0]; // initial cost of skipping prefix in String s0 for(int i=0;i<len0;i++) cost[i]=i; // dynamicaly computing the array of distances // transformation cost for each letter in s1 for(int j=1;j<len1;j++) { // initial cost of skipping prefix in String s1 newcost[0]=j-1; // transformation cost for each letter in s0 for(int i=1;i<len0;i++) { // matching current letters in both strings int match = (s0.charAt(i-1)==s1.charAt(j-1))?0:1; // computing cost for each transformation int cost_replace = cost[i-1]+match; int cost_insert = cost[i]+1; int cost_delete = newcost[i-1]+1; // keep minimum cost newcost[i] = Math.min(Math.min(cost_insert, cost_delete),cost_replace ); } // swap cost/newcost arrays int[] swap=cost; cost=newcost; newcost=swap; } // the distance is the cost for transforming all letters in both strings return cost[len0-1]; } /** * Identifies whether two strings are close enough that they are likely to be * intended to be the same string. Fuzzy matching is only performed on strings that are * longer than a certain size. * * @param a * @param b * @return A pair with two values. First value represents a match: true if the two strings * meet CommCare's fuzzy match definition, false otherwise. Second value is the actual string * distance that was matched, in order to be able to rank or otherwise interpret results. */ public static Pair<Boolean, Integer> fuzzyMatch(String a, String b) { //tweakable parameter: Minimum length before edit distance //starts being used (this is probably not necessary, and //basically only makes sure that "at" doesn't match "or" or similar if(b.length() > 3) { int distance = StringUtils.LevenshteinDistance(a, b); //tweakable parameter: edit distance past string length disparity if(distance <= 2) { return Pair.create(true, distance); } } return Pair.create(false, -1); } }
Fix NullPointerException
app/src/org/commcare/android/util/StringUtils.java
Fix NullPointerException
Java
apache-2.0
1bb744cc9e7b2fffc3cdae9266ff0ddba6b59b49
0
OpenHFT/Chronicle-Bytes
/* * Copyright (c) 2016-2022 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.bytes; import net.openhft.chronicle.bytes.internal.BytesInternal; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.io.IORuntimeException; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.util.Arrays; import java.util.Locale; import java.util.Random; import static java.nio.charset.StandardCharsets.US_ASCII; import static net.openhft.chronicle.bytes.BytesInternalTest.Nested.LENGTH; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; public class BytesInternalTest extends BytesTestCommon { @Test public void testParseUTF_SB1() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); byte[] bytes2 = new byte[128]; Arrays.fill(bytes2, (byte) '?'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8(bytes, sb, true, 128); assertEquals(128, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); BytesInternal.parseUtf8(bytes, sb, false, 128); assertEquals(128, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testParseUTF8_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8(bytes, sb, true, length); assertEquals(length, sb.length()); String actual = sb.toString(); sb = null; // free some memory. assertEquals(new String(bytes2, US_ASCII), actual); bytes.releaseLast(); } @Test public void parseLongEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLong()); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseLongNonEmpty() { for (String s : "0, 0, 0..,0-, 0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLong()); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseLongDecimalEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLongDecimal()); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseLongDecimalNonEmpty() { for (String s : "0, 0, .0,0-,0x, .0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLongDecimal()); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, Double.compare(-0.0, from.parseDouble())); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleEmptyZero() { for (String s : "0, 0, .0,0-,0x, .0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, Double.compare(0.0, from.parseDouble())); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleScientificNegative() { parseDoubleScientific("6.1E-4", 6.1E-4, 5 /*0.00061 needs dp 5*/); } @Test public void parseDoubleScientificNegative1() { parseDoubleScientific("6.123E-4", 6.123E-4, 7 /* 0.0006123 needs dp 7 */); } @Test public void parseDoubleScientificPositive1() { parseDoubleScientific("6.12345E4", 6.12345E4, 1 /* 6.12345 x 10^4 = 61234.5 needs 1 */); } private void parseDoubleScientific(final String strDouble, final double expected, final int expectedDp) { final Bytes<?> from = Bytes.from(strDouble); try { assertEquals(expected, from.parseDouble(), 0.0); assertEquals(expectedDp, from.lastDecimalPlaces()); } finally { from.releaseLast(); } } @Test public void testParseUTF81_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf81(bytes, sb, true, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); BytesInternal.parseUtf81(bytes, sb, false, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testParseUTF_SB1_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8_SB1(bytes, sb, true, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); /* BytesInternal.parseUtf8_SB1(bytes, sb, false, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); */ bytes.releaseLast(); } @Test public void testParse8bit_LongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testAllParseDouble() { assumeFalse(GuardedNativeBytes.areNewGuarded()); for (String s : "0.,1.,9.".split(",")) { // todo FIX for i == 7 && d == 8 for (int d = 0; d < 8; d++) { s += '0'; for (int i = 1; i < 10; i += 2) { String si = s + i; Bytes<?> from = Bytes.from(si); assertEquals(si, Double.parseDouble(si), from.parseDouble(), 0.0); from.releaseLast(); } } } } @Test public void testWriteUtf8LongString() throws IORuntimeException, BufferUnderflowException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.writeUtf8(bytes, test); sb.setLength(0); assertTrue(BytesInternal.compareUtf8(bytes, 0, test)); bytes.releaseLast(); } @Test public void testAppendUtf8LongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.appendUtf8(bytes, test, 0, length); sb.setLength(0); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(test, sb.toString()); bytes.releaseLast(); } @Test public void testAppend8bitLongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.append8bit(0, bytes, test, 0, length); sb.setLength(0); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(test, sb.toString()); bytes.releaseLast(); } @Test public void testParseDouble() { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull Object[][] tests = { {"0e0 ", 0.0}, {"-1E-3 ", -1E-3}, {"12E3 ", 12E3}, {"-1.1E-3 ", -1.1E-3}, {"-1.1E3 ", -1.1E3}, {"-1.16823E70 ", -1.16823E70}, {"1.17045E70 ", 1.17045E70}, {"6.85202", 6.85202} }; for (Object[] objects : tests) { @NotNull String text = (String) objects[0]; double expected = (Double) objects[1]; Bytes<?> from = Bytes.from(text); assertEquals(expected, from.parseDouble(), 0.0); assertTrue(from.lastNumberHadDigits()); from.releaseLast(); } } @Test public void testCopyAfterSkip() { final Bytes<byte[]> src = Bytes.from("hello again"); src.readSkip(7); assertEquals(src.copy().toString(), src.toString()); } @Test public void testCopyToArrayAfterSkip() { final Bytes<byte[]> src = Bytes.from("hello again"); src.readSkip(7); final byte[] buffer = new byte[100]; final int copiedLen = src.copyTo(buffer); assertEquals(new String(buffer, 0, copiedLen), src.toString()); } private int checkParse(int different, String s) { double d = Double.parseDouble(s); Bytes<?> from = Bytes.from(s); double d2 = from.parseDouble(); from.releaseLast(); if (d != d2) { // System.out.println(d + " != " + d2); ++different; } return different; } @Test public void bytesParseDouble_Issue85_SeededRandom() { assumeFalse(GuardedNativeBytes.areNewGuarded()); Random random = new Random(1); int different = 0; int max = 10_000; for (int i = 0; i < max; i++) { double num = random.nextDouble(); String s = String.format(Locale.UK, "%.9f", num); different = checkParse(different, s); } Assert.assertEquals("Different " + (100.0 * different) / max + "%", 0, different); } @Test @Ignore(/* peformance test */) public void testNoneDirectWritePerformance() { final int size = 64; Bytes<?> a = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> b = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> c = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> d = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> e = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> f = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> g = Bytes.allocateElasticOnHeap(size + 8); int retry = 1; for (int t = 0; t <= 4; t++) { long time1 = 0, time2 = 0, time3 = 0; long time4 = 0, time5 = 0, time6 = 0; final int runs = t == 0 ? 1_000 : 5_000; int count = 0; for (int i = 0; i < runs; i++) { for (int o = 0; o <= 8; o++) for (int s = 0; s <= size - o; s++) { long start1 = 0, end1 = 0, start2 = 0, end2 = 0, start3 = 0, end3 = 0; long start4 = 0, end4 = 0, start5 = 0, end5 = 0, start6 = 0, end6 = 0; for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); b.clear().writeSkip(t); start1 = System.nanoTime(); BytesInternal.writeFully(a, o, s, b); end1 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); c.clear().writeSkip(t); start2 = System.nanoTime(); simpleWriteFully1(a, o, s, c); end2 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); d.clear().writeSkip(t); start3 = System.nanoTime(); oldWriteFully(a, o, s, d); end3 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); d.clear().writeSkip(t); start4 = System.nanoTime(); simpleWriteFully2(a, o, s, d); end4 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); e.clear().writeSkip(t); start5 = System.nanoTime(); simpleWriteFully3(a, o, s, e); end5 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); g.clear().writeSkip(t); start6 = System.nanoTime(); simpleWriteFully4(a, o, s, g); end6 = System.nanoTime(); } time1 += end1 - start1; time2 += end2 - start2; time3 += end3 - start3; time4 += end4 - start4; time5 += end5 - start5; time6 += end6 - start6; count++; } } time1 /= count; time2 /= count; time3 /= count; time4 /= count; time5 /= count; time6 /= count; System.out.println("time1 " + time1 + ", time2 " + time2 + ", time3: " + time3); System.out.println("time4 " + time4 + ", time5 " + time5 + ", time6: " + time6); // This is a performance test so just assert it ran assertTrue(time1 > 0); assertTrue(time2 > 0); assertTrue(time3 > 0); assertTrue(time4 > 0); assertTrue(time5 > 0); assertTrue(time6 > 0); Thread.yield(); } } static class Nested { public static final int LENGTH; static { long maxMemory = Runtime.getRuntime().maxMemory(); int maxLength = OS.isLinux() ? 1 << 30 : 1 << 28; LENGTH = (int) Math.min(maxMemory / 32, maxLength); if (LENGTH < maxLength) System.out.println("Not enough memory to run big test, was " + (LENGTH >> 20) + " MB."); } } public static void simpleWriteFully1(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully2(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully3(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { int i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully4(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { int i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void oldWriteFully(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 3; i += 4) sdo.rawWriteInt(bytes.readInt(offset + i)); for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } }
src/test/java/net/openhft/chronicle/bytes/BytesInternalTest.java
/* * Copyright (c) 2016-2022 chronicle.software * * https://chronicle.software * * 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.openhft.chronicle.bytes; import net.openhft.chronicle.bytes.internal.BytesInternal; import net.openhft.chronicle.core.OS; import net.openhft.chronicle.core.io.IORuntimeException; import org.jetbrains.annotations.NotNull; import org.junit.Assert; import org.junit.Test; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import java.util.Arrays; import java.util.Locale; import java.util.Random; import static java.nio.charset.StandardCharsets.US_ASCII; import static net.openhft.chronicle.bytes.BytesInternalTest.Nested.LENGTH; import static org.junit.Assert.*; import static org.junit.Assume.assumeFalse; public class BytesInternalTest extends BytesTestCommon { @Test public void testParseUTF_SB1() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); byte[] bytes2 = new byte[128]; Arrays.fill(bytes2, (byte) '?'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8(bytes, sb, true, 128); assertEquals(128, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); BytesInternal.parseUtf8(bytes, sb, false, 128); assertEquals(128, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testParseUTF8_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8(bytes, sb, true, length); assertEquals(length, sb.length()); String actual = sb.toString(); sb = null; // free some memory. assertEquals(new String(bytes2, US_ASCII), actual); bytes.releaseLast(); } @Test public void parseLongEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLong()); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseLongNonEmpty() { for (String s : "0, 0, 0..,0-, 0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLong()); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseLongDecimalEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLongDecimal()); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseLongDecimalNonEmpty() { for (String s : "0, 0, .0,0-,0x, .0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, from.parseLongDecimal()); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleEmpty() { for (String s : ", , .,-,x, .e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, Double.compare(-0.0, from.parseDouble())); assertFalse(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleEmptyZero() { for (String s : "0, 0, .0,0-,0x, .0e".split(",")) { final Bytes<byte[]> from = Bytes.from(s); assertEquals(s, 0, Double.compare(0.0, from.parseDouble())); assertTrue(s, from.lastNumberHadDigits()); } } @Test public void parseDoubleScientificNegative() { parseDoubleScientific("6.1E-4", 6.1E-4, 5 /*0.00061 needs dp 5*/); } @Test public void parseDoubleScientificNegative1() { parseDoubleScientific("6.123E-4", 6.123E-4, 7 /* 0.0006123 needs dp 7 */); } @Test public void parseDoubleScientificPositive1() { parseDoubleScientific("6.12345E4", 6.12345E4, 1 /* 6.12345 x 10^4 = 61234.5 needs 1 */); } private void parseDoubleScientific(final String strDouble, final double expected, final int expectedDp) { final Bytes<?> from = Bytes.from(strDouble); try { assertEquals(expected, from.parseDouble(), 0.0); assertEquals(expectedDp, from.lastDecimalPlaces()); } finally { from.releaseLast(); } } @Test public void testParseUTF81_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf81(bytes, sb, true, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); BytesInternal.parseUtf81(bytes, sb, false, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testParseUTF_SB1_LongString() throws UTFDataFormatRuntimeException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parseUtf8_SB1(bytes, sb, true, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.readPosition(0); sb.setLength(0); /* BytesInternal.parseUtf8_SB1(bytes, sb, false, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); */ bytes.releaseLast(); } @Test public void testParse8bit_LongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; byte[] bytes2 = new byte[length]; Arrays.fill(bytes2, (byte) '!'); bytes.write(bytes2); @NotNull StringBuilder sb = new StringBuilder(); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(length, sb.length()); assertEquals(new String(bytes2, US_ASCII), sb.toString()); bytes.releaseLast(); } @Test public void testAllParseDouble() { assumeFalse(GuardedNativeBytes.areNewGuarded()); for (String s : "0.,1.,9.".split(",")) { // todo FIX for i == 7 && d == 8 for (int d = 0; d < 8; d++) { s += '0'; for (int i = 1; i < 10; i += 2) { String si = s + i; Bytes<?> from = Bytes.from(si); assertEquals(si, Double.parseDouble(si), from.parseDouble(), 0.0); from.releaseLast(); } } } } @Test public void testWriteUtf8LongString() throws IORuntimeException, BufferUnderflowException { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.writeUtf8(bytes, test); sb.setLength(0); assertTrue(BytesInternal.compareUtf8(bytes, 0, test)); bytes.releaseLast(); } @Test public void testAppendUtf8LongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.appendUtf8(bytes, test, 0, length); sb.setLength(0); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(test, sb.toString()); bytes.releaseLast(); } @Test public void testAppend8bitLongString() throws Exception { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull VanillaBytes bytes = Bytes.allocateElasticDirect(); int length = LENGTH; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) sb.append('!'); String test = sb.toString(); BytesInternal.append8bit(0, bytes, test, 0, length); sb.setLength(0); BytesInternal.parse8bit(0, bytes, sb, length); assertEquals(test, sb.toString()); bytes.releaseLast(); } @Test public void testParseDouble() { assumeFalse(GuardedNativeBytes.areNewGuarded()); @NotNull Object[][] tests = { {"0e0 ", 0.0}, {"-1E-3 ", -1E-3}, {"12E3 ", 12E3}, {"-1.1E-3 ", -1.1E-3}, {"-1.1E3 ", -1.1E3}, {"-1.16823E70 ", -1.16823E70}, {"1.17045E70 ", 1.17045E70}, {"6.85202", 6.85202} }; for (Object[] objects : tests) { @NotNull String text = (String) objects[0]; double expected = (Double) objects[1]; Bytes<?> from = Bytes.from(text); assertEquals(expected, from.parseDouble(), 0.0); assertTrue(from.lastNumberHadDigits()); from.releaseLast(); } } @Test public void testCopyAfterSkip() { final Bytes<byte[]> src = Bytes.from("hello again"); src.readSkip(7); assertEquals(src.copy().toString(), src.toString()); } @Test public void testCopyToArrayAfterSkip() { final Bytes<byte[]> src = Bytes.from("hello again"); src.readSkip(7); final byte[] buffer = new byte[100]; final int copiedLen = src.copyTo(buffer); assertEquals(new String(buffer, 0, copiedLen), src.toString()); } private int checkParse(int different, String s) { double d = Double.parseDouble(s); Bytes<?> from = Bytes.from(s); double d2 = from.parseDouble(); from.releaseLast(); if (d != d2) { // System.out.println(d + " != " + d2); ++different; } return different; } @Test public void bytesParseDouble_Issue85_SeededRandom() { assumeFalse(GuardedNativeBytes.areNewGuarded()); Random random = new Random(1); int different = 0; int max = 10_000; for (int i = 0; i < max; i++) { double num = random.nextDouble(); String s = String.format(Locale.UK, "%.9f", num); different = checkParse(different, s); } Assert.assertEquals("Different " + (100.0 * different) / max + "%", 0, different); } static class Nested { public static final int LENGTH; static { long maxMemory = Runtime.getRuntime().maxMemory(); int maxLength = OS.isLinux() ? 1 << 30 : 1 << 28; LENGTH = (int) Math.min(maxMemory / 16, maxLength); if (LENGTH < maxLength) System.out.println("Not enough memory to run big test, was " + (LENGTH >> 20) + " MB."); } } @Test public void testNoneDirectWritePerformance() { final int size = 64; Bytes<?> a = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> b = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> c = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> d = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> e = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> f = Bytes.allocateElasticOnHeap(size + 8); Bytes<?> g = Bytes.allocateElasticOnHeap(size + 8); int retry = 1; for (int t = 0; t <= 4; t++) { long time1 = 0, time2 = 0, time3 = 0; long time4 = 0, time5 = 0, time6 = 0; final int runs = t == 0 ? 1_000 : 5_000; int count = 0; for (int i = 0; i < runs; i++) { for (int o = 0; o <= 8; o++) for (int s = 0; s <= size - o; s++) { long start1 = 0, end1 = 0, start2 = 0, end2 = 0, start3 = 0, end3 = 0; long start4 = 0, end4 = 0, start5 = 0, end5 = 0, start6 = 0, end6 = 0; for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); b.clear().writeSkip(t); start1 = System.nanoTime(); BytesInternal.writeFully(a, o, s, b); end1 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); c.clear().writeSkip(t); start2 = System.nanoTime(); simpleWriteFully1(a, o, s, c); end2 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); d.clear().writeSkip(t); start3 = System.nanoTime(); oldWriteFully(a, o, s, d); end3 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); d.clear().writeSkip(t); start4 = System.nanoTime(); simpleWriteFully2(a, o, s, d); end4 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); e.clear().writeSkip(t); start5 = System.nanoTime(); simpleWriteFully3(a, o, s, e); end5 = System.nanoTime(); } for (int r = 0; r < retry; r++) { a.clear().writeSkip(size); g.clear().writeSkip(t); start6 = System.nanoTime(); simpleWriteFully4(a, o, s, g); end6 = System.nanoTime(); } time1 += end1 - start1; time2 += end2 - start2; time3 += end3 - start3; time4 += end4 - start4; time5 += end5 - start5; time6 += end6 - start6; count++; } } time1 /= count; time2 /= count; time3 /= count; time4 /= count; time5 /= count; time6 /= count; System.out.println("time1 " + time1 + ", time2 " + time2 + ", time3: " + time3); System.out.println("time4 " + time4 + ", time5 " + time5 + ", time6: " + time6); // This is a performance test so just assert it ran assertTrue(time1 > 0); assertTrue(time2 > 0); assertTrue(time3 > 0); assertTrue(time4 > 0); assertTrue(time5 > 0); assertTrue(time6 > 0); Thread.yield(); } } public static void simpleWriteFully1(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully2(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully3(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { int i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void simpleWriteFully4(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { int i = 0; for (; i < length - 7; i += 8) sdo.rawWriteLong(bytes.readLong(offset + i)); if (i < length - 3) { sdo.rawWriteInt(bytes.readInt(offset + i)); i += 4; } for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } public static void oldWriteFully(@NotNull RandomDataInput bytes, long offset, long length, @NotNull StreamingDataOutput sdo) throws BufferUnderflowException, BufferOverflowException, IllegalStateException { long i = 0; for (; i < length - 3; i += 4) sdo.rawWriteInt(bytes.readInt(offset + i)); for (; i < length; i++) sdo.rawWriteByte(bytes.readByte(offset + i)); } }
Speed up test
src/test/java/net/openhft/chronicle/bytes/BytesInternalTest.java
Speed up test
Java
apache-2.0
05521e0dbcaca00aaac2c51bac2a8f9457b39cbf
0
Hippoom/scaleworks-analytics-eco,Hippoom/scaleworks-analytics-eco
package elk.spike; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.UUID; import static java.lang.String.format; import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; @Slf4j @RestController @SpringBootApplication public class Application { @RequestMapping("/hello") protected String hello() { prepareGreeting(); return "hello"; } private void prepareGreeting() { log.info("Saying hello"); throw new RuntimeException("Oops"); } @ExceptionHandler(Throwable.class) protected ResponseEntity wrapThrown(Throwable thrown) { ErrorRepresentation representation = new ErrorRepresentation(thrown); log.error(format("error_id[%s]:%s", representation.errorId, thrown.getMessage()), thrown); return new ResponseEntity<Object>(representation, INTERNAL_SERVER_ERROR); } @Getter static class ErrorRepresentation { private String errorId; private String message; public ErrorRepresentation(Throwable thrown) { this.errorId = UUID.randomUUID().toString(); this.message = thrown.getMessage(); } } @Resource private ObjectMapper objectMapper; @PostConstruct protected void configObjectMapper() { objectMapper.setPropertyNamingStrategy( PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
src/main/java/elk/spike/Application.java
package elk.spike; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Exception handler for unexpected throwables
src/main/java/elk/spike/Application.java
Exception handler for unexpected throwables
Java
apache-2.0
057479c587d22af433c5fe8bad69e633e8d53924
0
flapdoodle-oss/de.flapdoodle.embed.mongo,flapdoodle-oss/de.flapdoodle.embed.mongo
/** * Copyright (C) 2011 * Michael Mosmann <[email protected]> * Martin Jรถhren <[email protected]> * * with contributions from * konstantin-ba@github,Archimedes Trajano (trajano@github) * * 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 de.flapdoodle.embed.mongo.distribution; import java.util.EnumSet; /** * MongoDB Version enum */ public enum Version implements IFeatureAwareVersion { @Deprecated V1_6_5("1.6.5"), @Deprecated V1_7_6("1.7.6"), @Deprecated V1_8_0_rc0("1.8.0-rc0"), @Deprecated V1_8_0("1.8.0"), @Deprecated V1_8_1("1.8.1"), @Deprecated V1_8_2_rc0("1.8.2-rc0"), @Deprecated V1_8_2("1.8.2"), @Deprecated V1_8_4("1.8.4"), @Deprecated V1_8_5("1.8.5"), @Deprecated V1_9_0("1.9.0"), @Deprecated V2_0_1("2.0.1"), @Deprecated V2_0_4("2.0.4"), @Deprecated V2_0_5("2.0.5"), @Deprecated V2_0_6("2.0.6"), @Deprecated V2_0_7_RC1("2.0.7-rc1"), @Deprecated V2_0_7("2.0.7"), @Deprecated V2_0_8_RC0("2.0.8-rc0"), @Deprecated V2_0_9("2.0.9"), @Deprecated V2_1_0("2.1.0"), @Deprecated V2_1_1("2.1.1"), @Deprecated V2_1_2("2.1.2"), @Deprecated V2_2_0_RC0("2.2.0-rc0"), @Deprecated V2_2_0("2.2.0"), @Deprecated V2_2_1("2.2.1"), @Deprecated V2_2_3("2.2.3"), @Deprecated V2_2_4("2.2.4"), @Deprecated V2_2_5("2.2.5"), @Deprecated V2_2_6("2.2.6"), @Deprecated V2_2_7("2.2.7"), @Deprecated V2_3_0("2.3.0"), @Deprecated V2_4_0_RC3("2.4.0-rc3"), @Deprecated V2_4_0("2.4.0",Feature.SYNC_DELAY), @Deprecated V2_4_1("2.4.1",Feature.SYNC_DELAY), @Deprecated V2_4_2("2.4.2",Feature.SYNC_DELAY), @Deprecated V2_4_3("2.4.3",Feature.SYNC_DELAY), @Deprecated V2_4_5("2.4.5",Feature.SYNC_DELAY), @Deprecated V2_4_6("2.4.6",Feature.SYNC_DELAY), @Deprecated V2_4_7("2.4.7",Feature.SYNC_DELAY), @Deprecated V2_4_8("2.4.8",Feature.SYNC_DELAY), @Deprecated V2_4_9("2.4.9",Feature.SYNC_DELAY), @Deprecated V2_4_10("2.4.10",Feature.SYNC_DELAY), @Deprecated V2_5_0("2.5.0",Feature.SYNC_DELAY), @Deprecated V2_5_1("2.5.1",Feature.SYNC_DELAY), @Deprecated V2_5_3("2.5.3",Feature.SYNC_DELAY), @Deprecated V2_5_4("2.5.4",Feature.SYNC_DELAY), /** * 2.6 series production releases -------------- */ @Deprecated V2_6_0("2.6.0",Feature.SYNC_DELAY), /** * Latest 2.6 production release */ V2_6_1("2.6.1",Feature.SYNC_DELAY), /** * Latest 2.7 series development release */ V2_7_0("2.7.0",Feature.SYNC_DELAY), ; private final String specificVersion; private EnumSet<Feature> features; Version(String vName,Feature...features) { this.specificVersion = vName; this.features = Feature.asSet(features); } @Override public String asInDownloadPath() { return specificVersion; } @Override public boolean enabled(Feature feature) { return features.contains(feature); } @Override public String toString() { return "Version{" + specificVersion + '}'; } public static enum Main implements IFeatureAwareVersion { @Deprecated V1_8(V1_8_5), @Deprecated V2_0(V2_0_9), @Deprecated V2_1(V2_1_2), @Deprecated V2_2(V2_2_7), @Deprecated V2_3(V2_3_0), @Deprecated V2_4(V2_4_10), @Deprecated V2_5(V2_5_4), /** * Latest production release */ V2_6(V2_6_1), /** * Latest development release */ V2_7(V2_7_0), PRODUCTION(V2_6), DEVELOPMENT(V2_7), ; private final IFeatureAwareVersion _latest; Main(IFeatureAwareVersion latest) { _latest = latest; } @Override public String asInDownloadPath() { return _latest.asInDownloadPath(); } @Override public boolean enabled(Feature feature) { return _latest.enabled(feature); } } }
src/main/java/de/flapdoodle/embed/mongo/distribution/Version.java
/** * Copyright (C) 2011 * Michael Mosmann <[email protected]> * Martin Jรถhren <[email protected]> * * with contributions from * konstantin-ba@github,Archimedes Trajano (trajano@github) * * 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 de.flapdoodle.embed.mongo.distribution; import java.util.EnumSet; import de.flapdoodle.embed.process.distribution.IVersion; /** * MongoDB Version enum */ public enum Version implements IFeatureAwareVersion { @Deprecated V1_6_5("1.6.5"), @Deprecated V1_7_6("1.7.6"), @Deprecated V1_8_0_rc0("1.8.0-rc0"), @Deprecated V1_8_0("1.8.0"), @Deprecated V1_8_1("1.8.1"), @Deprecated V1_8_2_rc0("1.8.2-rc0"), @Deprecated V1_8_2("1.8.2"), @Deprecated V1_8_4("1.8.4"), @Deprecated V1_8_5("1.8.5"), @Deprecated V1_9_0("1.9.0"), @Deprecated V2_0_1("2.0.1"), @Deprecated V2_0_4("2.0.4"), @Deprecated V2_0_5("2.0.5"), @Deprecated V2_0_6("2.0.6"), @Deprecated V2_0_7_RC1("2.0.7-rc1"), @Deprecated V2_0_7("2.0.7"), @Deprecated V2_0_8_RC0("2.0.8-rc0"), @Deprecated V2_0_9("2.0.9"), @Deprecated V2_1_0("2.1.0"), @Deprecated V2_1_1("2.1.1"), V2_1_2("2.1.2"), @Deprecated V2_2_0_RC0("2.2.0-rc0"), @Deprecated V2_2_0("2.2.0"), @Deprecated V2_2_1("2.2.1"), @Deprecated V2_2_3("2.2.3"), @Deprecated V2_2_4("2.2.4"), @Deprecated V2_2_5("2.2.5"), @Deprecated V2_2_6("2.2.6"), /** * last production release */ V2_2_7("2.2.7"), @Deprecated V2_3_0("2.3.0"), @Deprecated V2_4_0_RC3("2.4.0-rc3"), @Deprecated V2_4_0("2.4.0",Feature.SYNC_DELAY), @Deprecated V2_4_1("2.4.1",Feature.SYNC_DELAY), @Deprecated V2_4_2("2.4.2",Feature.SYNC_DELAY), @Deprecated V2_4_3("2.4.3",Feature.SYNC_DELAY), @Deprecated V2_4_5("2.4.5",Feature.SYNC_DELAY), @Deprecated V2_4_6("2.4.6",Feature.SYNC_DELAY), @Deprecated V2_4_7("2.4.7",Feature.SYNC_DELAY), @Deprecated V2_4_8("2.4.8",Feature.SYNC_DELAY), /** * new production release */ V2_4_9("2.4.9",Feature.SYNC_DELAY), V2_4_10("2.4.10",Feature.SYNC_DELAY), @Deprecated V2_5_0("2.5.0",Feature.SYNC_DELAY), @Deprecated V2_5_1("2.5.1",Feature.SYNC_DELAY), @Deprecated V2_5_3("2.5.3",Feature.SYNC_DELAY), /** * new developement release */ V2_5_4("2.5.4",Feature.SYNC_DELAY), /** * soon new production release */ V2_6_0("2.6.0",Feature.SYNC_DELAY), ; private final String specificVersion; private EnumSet<Feature> features; Version(String vName,Feature...features) { this.specificVersion = vName; this.features = Feature.asSet(features); } @Override public String asInDownloadPath() { return specificVersion; } @Override public boolean enabled(Feature feature) { return features.contains(feature); } @Override public String toString() { return "Version{" + specificVersion + '}'; } public static enum Main implements IFeatureAwareVersion { @Deprecated V1_8(V1_8_5), @Deprecated V2_0(V2_0_9), @Deprecated V2_1(V2_1_2), /** * last production release */ V2_2(V2_2_7), @Deprecated V2_3(V2_3_0), /** * current production release */ V2_4(V2_4_10), /** * development release */ V2_5(V2_5_4), /** * soon new production release */ V2_6(V2_6_0), PRODUCTION(V2_4), DEVELOPMENT(V2_6), ; private final IFeatureAwareVersion _latest; Main(IFeatureAwareVersion latest) { _latest = latest; } @Override public String asInDownloadPath() { return _latest.asInDownloadPath(); } @Override public boolean enabled(Feature feature) { return _latest.enabled(feature); } } }
Updated and cleaned up versions: 2.6.1 is the latest production release, with 2.7.0 as the latest development release. Deprecated all other versions.
src/main/java/de/flapdoodle/embed/mongo/distribution/Version.java
Updated and cleaned up versions: 2.6.1 is the latest production release, with 2.7.0 as the latest development release. Deprecated all other versions.
Java
apache-2.0
9c635e113ae8a09ba21c83ed9314fa666ffe686e
0
ArcadiaConsulting/appstorestats
/** * Copyright 2013 Arcadia Consulting C.B. * * 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 es.arcadiaconsulting.appstoresstats.ios.io; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import es.arcadiaconsulting.appstoresstats.ios.model.Constants; import es.arcadiaconsulting.appstoresstats.ios.model.UnitData; public class DateHelper { private static final Logger logger = LoggerFactory .getLogger(DateHelper.class); public static Date buildDateFromUTCString(String utc){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try { return formatter.parse(utc); } catch (ParseException e) { logger.error("incorrect Date",e ); return null; } } public static List<UnitData> getFullUnitData(Date deploymentDate, Date queryDate, String sku,/** String propertiesFile,*/ String user, String password, String vendorId) throws DateHelperException { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT); List<UnitData> unitDataList = new Vector<UnitData>(); // iterator for compare dates GregorianCalendar dateIterator = new GregorianCalendar(); dateIterator.setTime(queryDate); GregorianCalendar deploymentDateCalendar = new GregorianCalendar(); deploymentDateCalendar.setTime(deploymentDate); // get last day checkable, must be 1 days before if today is the initial day Date currentday= new Date(System.currentTimeMillis()); GregorianCalendar currentDayCalendar = new GregorianCalendar(); currentDayCalendar.setTime(currentday); if( (currentDayCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==dateIterator.get(Calendar.DAY_OF_YEAR))){ dateIterator.add(Calendar.DATE, -1); } //check dates if(deploymentDateCalendar.get(Calendar.YEAR)>dateIterator.get(Calendar.YEAR) || (deploymentDateCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && deploymentDateCalendar.get(Calendar.DAY_OF_YEAR)>dateIterator.get(Calendar.DAY_OF_YEAR))){ logger.error("Incorrect Dates, First date must be 2 days previous to final date "+sku); throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date "+sku); } // if iterator is less or equal to deployment date we cant check units if (dateIterator.before(deploymentDateCalendar)) { logger.error("Incorrect date "+sku); throw new DateHelperException( "We cant get Results. There are not sales too. Wait some days"); } //getting years query int deploymentyear = deploymentDateCalendar.get(Calendar.YEAR); int dateIteratorYear = dateIterator.get(Calendar.YEAR); GregorianCalendar yearIterator = deploymentDateCalendar; while(deploymentyear < dateIteratorYear){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(yearIterator.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units "+sku); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); deploymentyear = deploymentyear+1; yearIterator.add(Calendar.YEAR, 1); deploymentDateCalendar = (GregorianCalendar)yearIterator.clone(); deploymentDateCalendar.set(Calendar.DAY_OF_YEAR,1); //if query is on first day of year return response if(dateIterator.get(Calendar.MONTH)==1&&dateIterator.get(Calendar.DAY_OF_MONTH)==1) return cleanUnitDataList(unitDataList); } //iterate for months (iterate to month) GregorianCalendar monthIterator = (GregorianCalendar)dateIterator.clone(); if(monthIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)){ //si es el mismo mes la consulta hacemos la consulta dia a dia GregorianCalendar dayIterator = deploymentDateCalendar; while(dayIterator.get(Calendar.DAY_OF_YEAR)<=dateIterator.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(dayIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Error Getting day units day: " + dayIterator.getTime()+": "+sku); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); dayIterator.add(Calendar.DATE, 1); } }else{ while(monthIterator.get(Calendar.MONTH)-1>-1){ monthIterator.add(Calendar.MONTH, -1); List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(monthIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Error Getting month units for app: "+sku); //throw new DateHelperException( // "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); //if query is first day of month return unit data // if(dateIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.getActualMaximum(Calendar.DAY_OF_MONTH)) // return unitDataList; } //iterate for weeks //first do petiton for day to sunday GregorianCalendar weekIterator = new GregorianCalendar(dateIterator.get(Calendar.YEAR),dateIterator.get(Calendar.MONTH),1); //si cae en 1 el lunes y la fecha de consulta es superior al 7 que sera domingo se hara la consulta unicamente con la semana if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY && dateIterator.get(Calendar.DAY_OF_MONTH)>=7){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Error Getting week units for app: "+sku); //throw new DateHelperException( // "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(dateIterator.get(Calendar.DAY_OF_MONTH)==7) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DATE, 7); }else{ //si no coincide con la primera semana llegamos al domingo de la primera semana dia a dia do{ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Error Getting week units for app "+sku); //throw new DateHelperException( // "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); //si es el mismo dia que el ultimo dia consultable se retorna if(weekIterator.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR)&& weekIterator.get(Calendar.MONTH)==dateIterator.get(Calendar.MONTH)&& weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DATE, 1); }while(weekIterator.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY); } //hacemos la consulta de semanas mientras el dia del iterador mas 6 sea menor o igual que la fecha de la query //la consulta debe hacerse por domingos asi que hay que sumar los seis dias while(weekIterator.get(Calendar.DAY_OF_MONTH)+7<=dateIterator.get(Calendar.DAY_OF_MONTH)){ if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.MONDAY){ weekIterator.add(Calendar.DAY_OF_MONTH, 6); }else{ weekIterator.add(Calendar.DAY_OF_MONTH, 7); } List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Problem getting week sales for app: "+sku); //throw new DateHelperException("Problem getting week sales. Please see log for more information"); //hacemos por ultimo la consulta hasta llegar al dia de la consulta ya que no se ha encontrado estadisticas de alguna semana aun while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){ dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("there are not day sales; " + sdf.format(weekIterator.getTime())+" "+sku); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); weekIterator.add(Calendar.DATE, 1); if(weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); } }else{ unitDataList.addAll(dayUnitData); if(weekIterator.get(Calendar.DAY_OF_MONTH)+7==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DAY_OF_MONTH, 1); } } //hacemos por ultimo la consulta hasta llegar al dia de la consulta while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("there are not day sales; " + sdf.format(weekIterator.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); weekIterator.add(Calendar.DATE, 1); } } return cleanUnitDataList(unitDataList); /** Redo to init for years // getting day units until sunday or deployment day or first sunday // without 1 week passed while ((Calendar.SUNDAY != dateIterator.get(Calendar.DAY_OF_WEEK) || (Calendar.SUNDAY == dateIterator .get(Calendar.DAY_OF_WEEK) && isFirstSunday( deploymentDateCalendar, dateIterator)))) { List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( propertiesFile, user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(dateIterator), sku); if (dayUnitData == null) { logger.error("Error Getting day units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); dateIterator.add(Calendar.DATE, -1); // if dateIterator is the same that deployment day return item if(dateIterator.get(Calendar.YEAR)==deploymentDateCalendar.get(Calendar.YEAR)&&dateIterator.get(Calendar.DAY_OF_MONTH)==deploymentDateCalendar.get(Calendar.DAY_OF_MONTH)&&dateIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)) return unitDataList; } //init week iteration //if is first week is less than 7 (if is 7 we can do one week petition) we must do a petition for day to arrive to first month day if(dateIterator.get(Calendar.DAY_OF_WEEK)<7){ } while(){ } */ } private static boolean isFirstSunday(Calendar deploymentDate, Calendar sunday) { int dayOfWeek = deploymentDate.get(Calendar.DAY_OF_WEEK); Calendar dateIterator = deploymentDate; dateIterator.add(Calendar.DATE, 8 - dayOfWeek); if (dateIterator.get(Calendar.DAY_OF_WEEK_IN_MONTH) == sunday .get(Calendar.DAY_OF_WEEK_IN_MONTH)) return true; return false; } private static List<UnitData> cleanUnitDataList(List<UnitData> unitDataListIn){ List<UnitData> cleanedUnitDataList = new Vector<UnitData>(); for (Iterator iterator = unitDataListIn.iterator(); iterator .hasNext();) { UnitData unitData = (UnitData) iterator.next(); boolean countryIsAdded = false; for (Iterator iterator2 = cleanedUnitDataList.iterator(); iterator2 .hasNext();) { UnitData unitDataCleaned = (UnitData) iterator2.next(); if(unitData.getCountryCode().equals(unitDataCleaned.getCountryCode())){ countryIsAdded = true; break; } } if(!countryIsAdded){ UnitData newUnitData = new UnitData(unitData.countryCode, getAllCountryDataUnits(unitDataListIn,unitData.countryCode)); cleanedUnitDataList.add(newUnitData); } } return cleanedUnitDataList; } private static int getAllCountryDataUnits(List<UnitData> unitData, String country ){ int units=0; for (Iterator iterator = unitData.iterator(); iterator.hasNext();) { UnitData unitData2 = (UnitData) iterator.next(); if(unitData2.getCountryCode().equals(country)) units = units + unitData2.getUnits(); } return units; } // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo public static final int USE_CASE_0 = 0; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo public static final int USE_CASE_1 = 1; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo public static final int USE_CASE_2 = 2; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo public static final int USE_CASE_3 = 3; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes public static final int USE_CASE_4 = 4; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes public static final int USE_CASE_5 = 5; // consulta fecha inicio y fin menos de un mes public static final int USE_CASE_6=6; // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes public static final int USE_CASE_7 = 7; // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes public static final int USE_CASE_8 = 8; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes public static final int USE_CASE_9 = 9; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo public static final int USE_CASE_10 = 10; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo public static final int USE_CASE_11 = 11; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes public static final int USE_CASE_12 = 12; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes public static final int USE_CASE_13 = 13; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo public static final int USE_CASE_14 = 14; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo public static final int USE_CASE_15 = 15; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes public static final int USE_CASE_16 = 16; // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo public static final int USE_CASE_17 = 17; // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses public static final int USE_CASE_18 = 18; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses public static final int USE_CASE_19 = 19; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo public static final int USE_CASE_20 = 20; // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes public static final int USE_CASE_21 = 21; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo public static final int USE_CASE_22 = 22; public static int getDateUseCase(Date firstDate, Date secondDate){ GregorianCalendar firstDateCalendar = new GregorianCalendar(); firstDateCalendar.setTime(firstDate); GregorianCalendar secondDateCalendar = new GregorianCalendar(); secondDateCalendar.setTime(secondDate); Date currentDate = new Date(System.currentTimeMillis()); GregorianCalendar currentDateCalendar = new GregorianCalendar(); currentDateCalendar.setTime(currentDate); GregorianCalendar oneMonth = (GregorianCalendar)currentDateCalendar.clone(); oneMonth.add(Calendar.MONTH, -1); //GregorianCalendar threeMonth = (GregorianCalendar)currentDateCalendar.clone(); //threeMonth.add(Calendar.MONTH, -3); GregorianCalendar sixMonth = (GregorianCalendar)currentDateCalendar.clone(); sixMonth.add(Calendar.MONTH, -6); GregorianCalendar oneYear = (GregorianCalendar) currentDateCalendar.clone(); oneYear.add(Calendar.YEAR, -1); // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_0; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_1; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_2; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_3; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.after(oneMonth)) return USE_CASE_4; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.after(oneMonth)) return USE_CASE_5; // consulta fecha inicio y fin menos de un mes if(firstDateCalendar.after(oneMonth)&&secondDateCalendar.after(oneMonth)) return USE_CASE_6; // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_7; // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_8; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_9; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_10; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_11; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.after(oneMonth)) return USE_CASE_12; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_13; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_14; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_15; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.after(oneMonth)) return USE_CASE_16; // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.getMaximum(Calendar.DAY_OF_YEAR)) return USE_CASE_17; // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneYear)) return USE_CASE_18; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(sixMonth)&&secondDateCalendar.after(oneYear)) return USE_CASE_19; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)== Calendar.SUNDAY) return USE_CASE_20; // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes if(firstDateCalendar.before(oneYear)&&secondDateCalendar.after(oneMonth)) return USE_CASE_21; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!= Calendar.SUNDAY) return USE_CASE_22; return -1000; } public static List<UnitData> getUnitDataByDate(Date firstDate, Date secondDate, String sku, String user, String password, String vendorId) throws DateHelperException { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT); List<UnitData> unitDataList = new Vector<UnitData>(); GregorianCalendar firstDateCalendar = new GregorianCalendar(); firstDateCalendar.setTime(firstDate); GregorianCalendar secondDateCalendar = new GregorianCalendar(); secondDateCalendar.setTime(secondDate); //if seconddate is current delete one day // get last day checkable, must be 1 days before if today is the initial day Date currentday= new Date(System.currentTimeMillis()); GregorianCalendar currentDayCalendar = new GregorianCalendar(); currentDayCalendar.setTime(currentday); if( (currentDayCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.get(Calendar.DAY_OF_YEAR))){ secondDateCalendar.add(Calendar.DATE, -1); } //check dates if(firstDateCalendar.get(Calendar.YEAR)>secondDateCalendar.get(Calendar.YEAR) || (firstDateCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && firstDateCalendar.get(Calendar.DAY_OF_YEAR)>secondDateCalendar.get(Calendar.DAY_OF_YEAR))){ logger.error("Incorrect Dates, First date must be 2 days previous to final date"); throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date"); } // if iterator is less or equal to deployment date we cant check units if (secondDateCalendar.before(firstDateCalendar)) { logger.error("Incorrect date"); throw new DateHelperException( "We cant get Results. Incorrect dates. Wait some days"); } //checkUseCase int usecase = getDateUseCase(firstDateCalendar.getTime(),secondDateCalendar.getTime()); GregorianCalendar iteratorFirst = null; GregorianCalendar iteratorSecond = null; switch (usecase) { // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo case USE_CASE_0: // iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo case USE_CASE_1: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorSecond = (GregorianCalendar)secondDateCalendar.clone(); while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorSecond.add(Calendar.DATE, 1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=iteratorSecond.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo case USE_CASE_2: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo case USE_CASE_3: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorSecond = (GregorianCalendar)secondDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorSecond.add(Calendar.DATE, 1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes case USE_CASE_4: iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ return cleanUnitDataList(unitDataList); }else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ iteratorFirst.add(Calendar.DATE, 7); break; } iteratorFirst.add(Calendar.DATE, 7); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.DATE, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes case USE_CASE_5: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ return cleanUnitDataList(unitDataList); }else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ iteratorFirst.add(Calendar.DATE, 7); break; } iteratorFirst.add(Calendar.DATE, 7); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.DATE, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio y fin menos de un mes case USE_CASE_6: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes case USE_CASE_7: iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes case USE_CASE_8: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorFirst.set(Calendar.DAY_OF_MONTH, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes case USE_CASE_9: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo case USE_CASE_10: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo case USE_CASE_11: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes case USE_CASE_12: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes case USE_CASE_13: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo case USE_CASE_14: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo case USE_CASE_15: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes case USE_CASE_16: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorFirst.set(Calendar.DAY_OF_MONTH, 1); return getFullUnitData(iteratorFirst.getTime(), secondDate, sku, user, password, vendorId); // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo case USE_CASE_17: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses case USE_CASE_18: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses case USE_CASE_19: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo case USE_CASE_20: iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes case USE_CASE_21: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo case USE_CASE_22: iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); default: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); } return cleanUnitDataList(unitDataList); } }
appstoresstats-ios/src/main/java/es/arcadiaconsulting/appstoresstats/ios/io/DateHelper.java
/** * Copyright 2013 Arcadia Consulting C.B. * * 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 es.arcadiaconsulting.appstoresstats.ios.io; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import es.arcadiaconsulting.appstoresstats.ios.model.Constants; import es.arcadiaconsulting.appstoresstats.ios.model.UnitData; public class DateHelper { private static final Logger logger = LoggerFactory .getLogger(DateHelper.class); public static Date buildDateFromUTCString(String utc){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); try { return formatter.parse(utc); } catch (ParseException e) { logger.error("incorrect Date",e ); return null; } } public static List<UnitData> getFullUnitData(Date deploymentDate, Date queryDate, String sku,/** String propertiesFile,*/ String user, String password, String vendorId) throws DateHelperException { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT); List<UnitData> unitDataList = new Vector<UnitData>(); // iterator for compare dates GregorianCalendar dateIterator = new GregorianCalendar(); dateIterator.setTime(queryDate); GregorianCalendar deploymentDateCalendar = new GregorianCalendar(); deploymentDateCalendar.setTime(deploymentDate); // get last day checkable, must be 1 days before if today is the initial day Date currentday= new Date(System.currentTimeMillis()); GregorianCalendar currentDayCalendar = new GregorianCalendar(); currentDayCalendar.setTime(currentday); if( (currentDayCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==dateIterator.get(Calendar.DAY_OF_YEAR))){ dateIterator.add(Calendar.DATE, -1); } //check dates if(deploymentDateCalendar.get(Calendar.YEAR)>dateIterator.get(Calendar.YEAR) || (deploymentDateCalendar.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR) && deploymentDateCalendar.get(Calendar.DAY_OF_YEAR)>dateIterator.get(Calendar.DAY_OF_YEAR))){ logger.error("Incorrect Dates, First date must be 2 days previous to final date "+sku); throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date "+sku); } // if iterator is less or equal to deployment date we cant check units if (dateIterator.before(deploymentDateCalendar)) { logger.error("Incorrect date "+sku); throw new DateHelperException( "We cant get Results. There are not sales too. Wait some days"); } //getting years query int deploymentyear = deploymentDateCalendar.get(Calendar.YEAR); int dateIteratorYear = dateIterator.get(Calendar.YEAR); GregorianCalendar yearIterator = deploymentDateCalendar; while(deploymentyear < dateIteratorYear){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(yearIterator.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units "+sku); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); deploymentyear = deploymentyear+1; yearIterator.add(Calendar.YEAR, 1); //if query is on first day of year return response if(dateIterator.get(Calendar.MONTH)==1&&dateIterator.get(Calendar.DAY_OF_MONTH)==1) return cleanUnitDataList(unitDataList); } //iterate for months (iterate to month) GregorianCalendar monthIterator = (GregorianCalendar)dateIterator.clone(); if(monthIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)){ //si es el mismo mes la consulta hacemos la consulta dia a dia GregorianCalendar dayIterator = deploymentDateCalendar; while(dayIterator.get(Calendar.DAY_OF_YEAR)<=dateIterator.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(dayIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Error Getting day units day: " + dayIterator.getTime()+": "+sku); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); dayIterator.add(Calendar.DATE, 1); } }else{ while(monthIterator.get(Calendar.MONTH)-1>-1){ monthIterator.add(Calendar.MONTH, -1); List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(monthIterator.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units for app: "+sku); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); //if query is first day of month return unit data // if(dateIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.getActualMaximum(Calendar.DAY_OF_MONTH)) // return unitDataList; } //iterate for weeks //first do petiton for day to sunday GregorianCalendar weekIterator = new GregorianCalendar(dateIterator.get(Calendar.YEAR),dateIterator.get(Calendar.MONTH),1); //si cae en 1 el lunes y la fecha de consulta es superior al 7 que sera domingo se hara la consulta unicamente con la semana if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY && dateIterator.get(Calendar.DAY_OF_MONTH)>=7){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units for app: "+sku); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(dateIterator.get(Calendar.DAY_OF_MONTH)==7) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DATE, 7); }else{ //si no coincide con la primera semana llegamos al domingo de la primera semana dia a dia do{ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units for app "+sku); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); //si es el mismo dia que el ultimo dia consultable se retorna if(weekIterator.get(Calendar.YEAR)==dateIterator.get(Calendar.YEAR)&& weekIterator.get(Calendar.MONTH)==dateIterator.get(Calendar.MONTH)&& weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DATE, 1); }while(weekIterator.get(Calendar.DAY_OF_WEEK)!=Calendar.MONDAY); } //hacemos la consulta de semanas mientras el dia del iterador mas 6 sea menor o igual que la fecha de la query //la consulta debe hacerse por domingos asi que hay que sumar los seis dias while(weekIterator.get(Calendar.DAY_OF_MONTH)+7<=dateIterator.get(Calendar.DAY_OF_MONTH)){ if(weekIterator.get(Calendar.DAY_OF_WEEK)==Calendar.MONDAY){ weekIterator.add(Calendar.DAY_OF_MONTH, 6); }else{ weekIterator.add(Calendar.DAY_OF_MONTH, 7); } List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("Problem getting week sales for app: "+sku); //throw new DateHelperException("Problem getting week sales. Please see log for more information"); //hacemos por ultimo la consulta hasta llegar al dia de la consulta ya que no se ha encontrado estadisticas de alguna semana aun while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){ dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("there are not day sales; " + sdf.format(weekIterator.getTime())+" "+sku); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); weekIterator.add(Calendar.DATE, 1); if(weekIterator.get(Calendar.DAY_OF_MONTH)==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); } }else{ unitDataList.addAll(dayUnitData); if(weekIterator.get(Calendar.DAY_OF_MONTH)+7==dateIterator.get(Calendar.DAY_OF_MONTH)) return cleanUnitDataList(unitDataList); weekIterator.add(Calendar.DAY_OF_MONTH, 1); } } //hacemos por ultimo la consulta hasta llegar al dia de la consulta while(weekIterator.get(Calendar.DAY_OF_MONTH)<=dateIterator.get(Calendar.DAY_OF_MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(weekIterator.getTime()), sku); if (dayUnitData == null) { logger.info("there are not day sales; " + sdf.format(weekIterator.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); weekIterator.add(Calendar.DATE, 1); } } return cleanUnitDataList(unitDataList); /** Redo to init for years // getting day units until sunday or deployment day or first sunday // without 1 week passed while ((Calendar.SUNDAY != dateIterator.get(Calendar.DAY_OF_WEEK) || (Calendar.SUNDAY == dateIterator .get(Calendar.DAY_OF_WEEK) && isFirstSunday( deploymentDateCalendar, dateIterator)))) { List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( propertiesFile, user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(dateIterator), sku); if (dayUnitData == null) { logger.error("Error Getting day units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); dateIterator.add(Calendar.DATE, -1); // if dateIterator is the same that deployment day return item if(dateIterator.get(Calendar.YEAR)==deploymentDateCalendar.get(Calendar.YEAR)&&dateIterator.get(Calendar.DAY_OF_MONTH)==deploymentDateCalendar.get(Calendar.DAY_OF_MONTH)&&dateIterator.get(Calendar.MONTH)==deploymentDateCalendar.get(Calendar.MONTH)) return unitDataList; } //init week iteration //if is first week is less than 7 (if is 7 we can do one week petition) we must do a petition for day to arrive to first month day if(dateIterator.get(Calendar.DAY_OF_WEEK)<7){ } while(){ } */ } private static boolean isFirstSunday(Calendar deploymentDate, Calendar sunday) { int dayOfWeek = deploymentDate.get(Calendar.DAY_OF_WEEK); Calendar dateIterator = deploymentDate; dateIterator.add(Calendar.DATE, 8 - dayOfWeek); if (dateIterator.get(Calendar.DAY_OF_WEEK_IN_MONTH) == sunday .get(Calendar.DAY_OF_WEEK_IN_MONTH)) return true; return false; } private static List<UnitData> cleanUnitDataList(List<UnitData> unitDataListIn){ List<UnitData> cleanedUnitDataList = new Vector<UnitData>(); for (Iterator iterator = unitDataListIn.iterator(); iterator .hasNext();) { UnitData unitData = (UnitData) iterator.next(); boolean countryIsAdded = false; for (Iterator iterator2 = cleanedUnitDataList.iterator(); iterator2 .hasNext();) { UnitData unitDataCleaned = (UnitData) iterator2.next(); if(unitData.getCountryCode().equals(unitDataCleaned.getCountryCode())){ countryIsAdded = true; break; } } if(!countryIsAdded){ UnitData newUnitData = new UnitData(unitData.countryCode, getAllCountryDataUnits(unitDataListIn,unitData.countryCode)); cleanedUnitDataList.add(newUnitData); } } return cleanedUnitDataList; } private static int getAllCountryDataUnits(List<UnitData> unitData, String country ){ int units=0; for (Iterator iterator = unitData.iterator(); iterator.hasNext();) { UnitData unitData2 = (UnitData) iterator.next(); if(unitData2.getCountryCode().equals(country)) units = units + unitData2.getUnits(); } return units; } // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo public static final int USE_CASE_0 = 0; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo public static final int USE_CASE_1 = 1; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo public static final int USE_CASE_2 = 2; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo public static final int USE_CASE_3 = 3; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes public static final int USE_CASE_4 = 4; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes public static final int USE_CASE_5 = 5; // consulta fecha inicio y fin menos de un mes public static final int USE_CASE_6=6; // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes public static final int USE_CASE_7 = 7; // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes public static final int USE_CASE_8 = 8; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes public static final int USE_CASE_9 = 9; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo public static final int USE_CASE_10 = 10; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo public static final int USE_CASE_11 = 11; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes public static final int USE_CASE_12 = 12; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes public static final int USE_CASE_13 = 13; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo public static final int USE_CASE_14 = 14; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo public static final int USE_CASE_15 = 15; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes public static final int USE_CASE_16 = 16; // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo public static final int USE_CASE_17 = 17; // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses public static final int USE_CASE_18 = 18; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses public static final int USE_CASE_19 = 19; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo public static final int USE_CASE_20 = 20; // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes public static final int USE_CASE_21 = 21; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo public static final int USE_CASE_22 = 22; public static int getDateUseCase(Date firstDate, Date secondDate){ GregorianCalendar firstDateCalendar = new GregorianCalendar(); firstDateCalendar.setTime(firstDate); GregorianCalendar secondDateCalendar = new GregorianCalendar(); secondDateCalendar.setTime(secondDate); Date currentDate = new Date(System.currentTimeMillis()); GregorianCalendar currentDateCalendar = new GregorianCalendar(); currentDateCalendar.setTime(currentDate); GregorianCalendar oneMonth = (GregorianCalendar)currentDateCalendar.clone(); oneMonth.add(Calendar.MONTH, -1); //GregorianCalendar threeMonth = (GregorianCalendar)currentDateCalendar.clone(); //threeMonth.add(Calendar.MONTH, -3); GregorianCalendar sixMonth = (GregorianCalendar)currentDateCalendar.clone(); sixMonth.add(Calendar.MONTH, -6); GregorianCalendar oneYear = (GregorianCalendar) currentDateCalendar.clone(); oneYear.add(Calendar.YEAR, -1); // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_0; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_1; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_2; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_3; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY &&secondDateCalendar.after(oneMonth)) return USE_CASE_4; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes if(firstDateCalendar.before(oneMonth)&&(firstDateCalendar.after(sixMonth))&&firstDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY &&secondDateCalendar.after(oneMonth)) return USE_CASE_5; // consulta fecha inicio y fin menos de un mes if(firstDateCalendar.after(oneMonth)&&secondDateCalendar.after(oneMonth)) return USE_CASE_6; // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_7; // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)==secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_8; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_9; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_10; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_11; // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)==1 &&secondDateCalendar.after(oneMonth)) return USE_CASE_12; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(sixMonth)&&(secondDateCalendar.after(oneYear))&&secondDateCalendar.get(Calendar.DAY_OF_MONTH)!=secondDateCalendar.getMaximum(Calendar.DAY_OF_MONTH)) return USE_CASE_13; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) return USE_CASE_14; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.before(oneMonth)&&(secondDateCalendar.after(sixMonth))&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) return USE_CASE_15; // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes if(firstDateCalendar.before(sixMonth)&&(firstDateCalendar.after(oneYear))&&firstDateCalendar.get(Calendar.DAY_OF_MONTH)!=1 &&secondDateCalendar.after(oneMonth)) return USE_CASE_16; // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.getMaximum(Calendar.DAY_OF_YEAR)) return USE_CASE_17; // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneYear)) return USE_CASE_18; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(sixMonth)&&secondDateCalendar.after(oneYear)) return USE_CASE_19; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)== Calendar.SUNDAY) return USE_CASE_20; // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes if(firstDateCalendar.before(oneYear)&&secondDateCalendar.after(oneMonth)) return USE_CASE_21; // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo if(firstDateCalendar.before(oneYear)&&secondDateCalendar.before(oneMonth)&&secondDateCalendar.after(sixMonth)&&secondDateCalendar.get(Calendar.DAY_OF_WEEK)!= Calendar.SUNDAY) return USE_CASE_22; return -1000; } public static List<UnitData> getUnitDataByDate(Date firstDate, Date secondDate, String sku, String user, String password, String vendorId) throws DateHelperException { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_FORMAT); List<UnitData> unitDataList = new Vector<UnitData>(); GregorianCalendar firstDateCalendar = new GregorianCalendar(); firstDateCalendar.setTime(firstDate); GregorianCalendar secondDateCalendar = new GregorianCalendar(); secondDateCalendar.setTime(secondDate); //if seconddate is current delete one day // get last day checkable, must be 1 days before if today is the initial day Date currentday= new Date(System.currentTimeMillis()); GregorianCalendar currentDayCalendar = new GregorianCalendar(); currentDayCalendar.setTime(currentday); if( (currentDayCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && currentDayCalendar.get(Calendar.DAY_OF_YEAR)==secondDateCalendar.get(Calendar.DAY_OF_YEAR))){ secondDateCalendar.add(Calendar.DATE, -1); } //check dates if(firstDateCalendar.get(Calendar.YEAR)>secondDateCalendar.get(Calendar.YEAR) || (firstDateCalendar.get(Calendar.YEAR)==secondDateCalendar.get(Calendar.YEAR) && firstDateCalendar.get(Calendar.DAY_OF_YEAR)>secondDateCalendar.get(Calendar.DAY_OF_YEAR))){ logger.error("Incorrect Dates, First date must be 2 days previous to final date"); throw new DateHelperException("Incorrect Dates, First date must be 2 days previous to final date"); } // if iterator is less or equal to deployment date we cant check units if (secondDateCalendar.before(firstDateCalendar)) { logger.error("Incorrect date"); throw new DateHelperException( "We cant get Results. Incorrect dates. Wait some days"); } //checkUseCase int usecase = getDateUseCase(firstDateCalendar.getTime(),secondDateCalendar.getTime()); GregorianCalendar iteratorFirst = null; GregorianCalendar iteratorSecond = null; switch (usecase) { // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses domingo case USE_CASE_0: // iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin entre 1 y 6 meses no domingo case USE_CASE_1: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorSecond = (GregorianCalendar)secondDateCalendar.clone(); while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorSecond.add(Calendar.DATE, 1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=iteratorSecond.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses domingo case USE_CASE_2: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin entre 1 y 6 meses no domingo case USE_CASE_3: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorSecond = (GregorianCalendar)secondDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorSecond.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorSecond.add(Calendar.DATE, 1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==iteratorSecond.get(Calendar.DAY_OF_YEAR)) return cleanUnitDataList(unitDataList); iteratorFirst.add(Calendar.DATE, 7); } break; // consulta fecha inicio entre 1 y 6 meses lunes, fecha fin menos de un mes case USE_CASE_4: iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ return cleanUnitDataList(unitDataList); }else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ iteratorFirst.add(Calendar.DATE, 7); break; } iteratorFirst.add(Calendar.DATE, 7); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.DATE, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 1 y 6 meses no lunes, fecha fin menos de un mes case USE_CASE_5: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY){ iteratorFirst.add(Calendar.DATE, -1); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_WEEDLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting week units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+7==secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ return cleanUnitDataList(unitDataList); }else if(iteratorFirst.get(Calendar.DAY_OF_YEAR)+12<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ iteratorFirst.add(Calendar.DATE, 7); break; } iteratorFirst.add(Calendar.DATE, 7); } while(iteratorFirst.get(Calendar.DAY_OF_YEAR)<=secondDateCalendar.get(Calendar.DAY_OF_YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_DAILY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("there are not day sales; " + sdf.format(iteratorFirst.getTime())); return cleanUnitDataList(unitDataList); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.DATE, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio y fin menos de un mes case USE_CASE_6: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio entre 6 y 12 meses dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes case USE_CASE_7: iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno, y fecha de fin entre 6 y 12 meses ultimo dia del mes case USE_CASE_8: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorFirst.set(Calendar.DAY_OF_MONTH, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes case USE_CASE_9: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses domingo case USE_CASE_10: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin entre 1 y 6 meses no domingo case USE_CASE_11: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses dia uno y fecha de fin menos de un mes case USE_CASE_12: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 6 y 12 meses no ultimo dia del mes case USE_CASE_13: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses domingo case USE_CASE_14: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin entre 1 y 6 meses no domingo case USE_CASE_15: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio entre 6 y 12 meses no dia uno y fecha de fin menos de un mes case USE_CASE_16: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar)firstDateCalendar.clone(); iteratorFirst.set(Calendar.DAY_OF_MONTH, 1); return getFullUnitData(iteratorFirst.getTime(), secondDate, sku, user, password, vendorId); // consulta fecha inicio mas de un aรฑo, fecha fin ultimo dia del aรฑo case USE_CASE_17: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin anterior a seis meses case USE_CASE_18: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 6 y 12 meses case USE_CASE_19: logger.warn("We can get sales with this dates, we get the aproximated possible sale"); iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses domingo case USE_CASE_20: iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); // consulta fecha inicio mas de un aรฑo, fecha fin menos de un mes case USE_CASE_21: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); // consulta fecha inicio mas de un aรฑo, fecha fin no ultimo dia del mes entre 1 y 6 meses no domingo case USE_CASE_22: iteratorFirst = (GregorianCalendar) firstDateCalendar.clone(); while(iteratorFirst.get(Calendar.YEAR)!=secondDateCalendar.get(Calendar.YEAR)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_YEARLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting year units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.YEAR, 1); } iteratorFirst.set(Calendar.DAY_OF_YEAR, 1); while(iteratorFirst.get(Calendar.MONTH)<=secondDateCalendar.get(Calendar.MONTH)){ List<UnitData> dayUnitData = Autoingestion.getUnitsByDate( /**propertiesFile,*/ user, password, vendorId, Constants.REPORT_TYPE_SALES, Constants.DATE_TYPE_MONTHLY, Constants.REPORT_SUBTYPE_SUMMARY_NAME, sdf.format(iteratorFirst.getTime()), sku); if (dayUnitData == null) { logger.error("Error Getting month units"); throw new DateHelperException( "Problem getting day sales. Please see log for more information"); } unitDataList.addAll(dayUnitData); iteratorFirst.add(Calendar.MONTH, 1); } return cleanUnitDataList(unitDataList); default: return getFullUnitData(firstDate, secondDate, sku, user, password, vendorId); } return cleanUnitDataList(unitDataList); } }
change date helper to get all stats searching all dates
appstoresstats-ios/src/main/java/es/arcadiaconsulting/appstoresstats/ios/io/DateHelper.java
change date helper to get all stats searching all dates
Java
apache-2.0
0901c5c703a56fe75f57214e492938b3d9ecf37f
0
KernelHaven/KernelHaven,KernelHaven/KernelHaven
/* * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering * * 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 * * https://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.ssehub.kernel_haven.util.io.csv; import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import net.ssehub.kernel_haven.util.io.ITableReader; import net.ssehub.kernel_haven.util.null_checks.NonNull; import net.ssehub.kernel_haven.util.null_checks.Nullable; /** * A reader for reading CSV files. This reader expects fields to be escaped as defined in * <a href="https://tools.ietf.org/html/rfc4180">RFC4180</a>. The behavior for malformed escapes is based on * the behavior observed in LibreOffice Calc. Examples of malformed escapes and how they are handled: * <ul> * <li>A single " appearing in the middle of an unescaped field: The single " is interpreted as a normal content * character</li> * <li>A double "" appearing in the middle of an unescaped field: The double "" are interpreted as normal content * characters.</li> * <li>A " appearing at the end of an unescaped field: The " is interpreted as a normal content character.</li> * <li>A " appearing at the start of a field, but not at the end: The field is not considered to not have ended. * All characters, until a " at the end position of a field is encountered, are intepreted as normal content * characters (including all line breaks, separator characters and "; double "" are still escaped to a single * ")-. For example <code>value 1;"value 2; value 3</code> has 2 fields: "value 1" and "value 2; value3"</li> * </ul> * This reader violates RFC4180 in that it considers any of the following sequences to be line-breaks: \r, \n, \r\n. * Additionally, this reader assumes that the default field separator is a semicolon (;) character. * * @author Adam */ public class CsvReader implements ITableReader { private @NonNull Reader in; private char separator; private Integer peeked; private boolean isEnd; private int currentLineNumber; /** * Creates a new {@link CsvReader} for the given input stream. Uses {@link CsvWriter#DEFAULT_SEPARATOR}. * * @param in The input stream to read the CSV data from. */ public CsvReader(@NonNull InputStream in) { this(in, CsvWriter.DEFAULT_SEPARATOR); } /** * Creates a new {@link CsvReader} for the given input stream. * * @param in The input stream to read the CSV data from. * @param separator The separator character to use. */ public CsvReader(@NonNull InputStream in, char separator) { this (new InputStreamReader(in, StandardCharsets.UTF_8), separator); } /** * Creates a new {@link CsvReader} for the given reader. Uses {@link CsvWriter#DEFAULT_SEPARATOR}. * * @param in The reader to read the CSV data from. */ public CsvReader(@NonNull Reader in) { this(in, CsvWriter.DEFAULT_SEPARATOR); } /** * Creates a new {@link CsvReader} for the given reader. * * @param in The reader to read the CSV data from. * @param separator The separator character to use. */ public CsvReader(@NonNull Reader in, char separator) { this.in = in; this.separator = separator; } @Override public void close() throws IOException { in.close(); } /** * Reads the next element from the stream. This method must be used, so that {@link #peek()} correctly functions. * If the end of stream is detected, this method sets {@link #isEnd} to true. * * @return The read character. -1 if end of stream is reached. * * @throws IOException If reading the stream fails. */ private int read() throws IOException { int result; if (peeked != null) { result = peeked; peeked = null; } else { result = in.read(); } if (result == -1) { isEnd = true; } return result; } /** * Peeks at the next character. The next {@link #read()} call will return the same character. {@link #read()} must * be called at least once before calling {@link #peek()} again. * * @return The next character that will be read. -1 if next character will be end of stream. * * @throws IOException If reading the stream fails. * @throws IllegalStateException If {@link #peek()} is called twice, without {@link #read()} in between. */ private int peek() throws IOException { if (peeked != null) { throw new IllegalStateException("Cannot peek while already storing peeked character"); } peeked = in.read(); return peeked; } /** * Removes the escaping " from a given field. The same string is returned, if field is not escaped. Double "" * are escaped to only one ". * * @param field The field to un-escape. * @return The un-escaped field. */ private @NonNull String unescape(@NonNull String field) { String result; if (field.isEmpty() || field.charAt(0) != '"') { result = field; } else { StringBuilder escaped = new StringBuilder(); for (int i = 1; i < field.length(); i++) { char c = field.charAt(i); if (c == '"' && i == field.length() - 1) { // trailing " means escaped sequence ended break; } else if (c == '"' && field.charAt(i + 1) == '"') { // double "" mean insert one " // move i to next character, so that only one " is added i++; } escaped.append(c); } result = notNull(escaped.toString()); } return result; } /** * Reads and parses a single line of CSV data. Splits at separator character. Considers (and un-escapes) * escaped values. * * @return The fields found in the CSV. * * @throws IOException If reading the stream fails. */ // CHECKSTYLE:OFF // TODO: this method is too long. private @NonNull String @Nullable [] readLine() throws IOException { // CHECKSTYLE:ON List<@NonNull String> parts = new LinkedList<>(); // whether we are currently inside an escape sequence // an escaped sequence starts with a " and ends with a " // the start " must be the first character of the field // the end " must be the last character of a field boolean inEscaped = false; // only relevant if inEscaped = true // whether the last read character was a " // used to detect the edge case that an escaped " is in front of a delimiter (e.g. ""; ) boolean wasQuote = false; // whether the last character was \r // only used to detect \r\n in escaped text boolean wasCarriageReturn = false; // contains characters of the current field // new characters are added until a (unescaped) separator is found // when a (unescaped) separator is found, the contents of this contain the previous field StringBuilder currentElement = new StringBuilder(); // break; will be called once the one of line (or stream) is reached while (true) { char c = (char) read(); if (isEnd) { currentLineNumber++; // increase for last line break; } if (c != '"') { // wasQuote is only relevant to detect double quotes ("") wasQuote = false; } if ((c == '\n' && !wasCarriageReturn) || c == '\r') { currentLineNumber++; } wasCarriageReturn = (c == '\r'); if (c == separator && !inEscaped) { // we found an unescaped separator parts.add(notNull(currentElement.toString())); currentElement.setLength(0); // jump back to start, to not add the separator to the next field continue; } else if (c == '"') { if (!inEscaped && currentElement.length() == 0) { // we found a " at the beginning of a field -> the field is escaped inEscaped = true; } else if (inEscaped && !wasQuote) { // check if we are at the end of a field, by peeking at the next character int peek = peek(); if (peek == -1 || peek == separator || peek == '\n' || peek == '\r') { // we found a " at the end of a field -> escaping ended inEscaped = false; // the next iteration will read() the end of field, so we don't have to do anything } else { // we just found a " in the middle of an escaped field wasQuote = true; } } else if (inEscaped) { // we are the " after another " wasQuote = false; } } else if ((c == '\n' || c == '\r') && !inEscaped) { // check if line-break is \r\n if (c == '\r') { int next = peek(); if (next == '\n') { // if \r is followed by \n, read the \n so that it doesn't re-appear in the next iteration. read(); } } // a non-escaped end of line -> we are done with this row break; } currentElement.append(c); } @NonNull String @Nullable [] result; if (parts.isEmpty() && currentElement.length() == 0 && peek() == -1) { // ignore last line in file, if its empty // we know that we are at the last line, if we didn't find any fields // (parts.empty() && currentElement.empty()) and the next char will be the end of stream result = null; isEnd = true; currentLineNumber--; } else { // add the last field (which we didn't find a separator for, because it was ended with a \n) parts.add(notNull(currentElement.toString())); result = notNull(parts.toArray(new @NonNull String[0])); for (int i = 0; i < result.length; i++) { result[i] = unescape(result[i]); } } return result; } @Override public @NonNull String @Nullable [] readNextRow() throws IOException { @NonNull String @Nullable [] result = null; if (!isEnd) { result = readLine(); } return result; } @Override public int getLineNumber() { return currentLineNumber; } }
src/net/ssehub/kernel_haven/util/io/csv/CsvReader.java
/* * Copyright 2017-2019 University of Hildesheim, Software Systems Engineering * * 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 * * https://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.ssehub.kernel_haven.util.io.csv; import static net.ssehub.kernel_haven.util.null_checks.NullHelpers.notNull; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.util.LinkedList; import java.util.List; import net.ssehub.kernel_haven.util.io.ITableReader; import net.ssehub.kernel_haven.util.null_checks.NonNull; import net.ssehub.kernel_haven.util.null_checks.Nullable; /** * A reader for reading CSV files. This reader expects fields to be escaped as defined in * <a href="https://tools.ietf.org/html/rfc4180">RFC4180</a>. The behavior for malformed escapes is based on * the behavior observed in LibreOffice Calc. Examples of malformed escapes and how they are handled: * <ul> * <li>A single " appearing in the middle of an unescaped field: The single " is interpreted as a normal content * character</li> * <li>A double "" appearing in the middle of an unescaped field: The double "" are interpreted as normal content * characters.</li> * <li>A " appearing at the end of an unescaped field: The " is interpreted as a normal content character.</li> * <li>A " appearing at the start of a field, but not at the end: The field is not considered to not have ended. * All characters, until a " at the end position of a field is encountered, are intepreted as normal content * characters (including all line breaks, separator characters and "; double "" are still escaped to a single * ")-. For example <code>value 1;"value 2; value 3</code> has 2 fields: "value 1" and "value 2; value3"</li> * </ul> * This reader violates RFC4180 in that it considers any of the following sequences to be line-breaks: \r, \n, \r\n. * Additionally, this reader assumes that the default field separator is a semicolon (;) character. * * @author Adam */ public class CsvReader implements ITableReader { private @NonNull Reader in; private char separator; private Integer peeked; private boolean isEnd; private int currentLineNumber; /** * Creates a new {@link CsvReader} for the given input stream. Uses {@link CsvWriter#DEFAULT_SEPARATOR}. * * @param in The input stream to read the CSV data from. */ public CsvReader(@NonNull InputStream in) { this(in, CsvWriter.DEFAULT_SEPARATOR); } /** * Creates a new {@link CsvReader} for the given input stream. * * @param in The input stream to read the CSV data from. * @param separator The separator character to use. */ public CsvReader(@NonNull InputStream in, char separator) { this (new InputStreamReader(in, StandardCharsets.UTF_8), separator); } /** * Creates a new {@link CsvReader} for the given reader. Uses {@link CsvWriter#DEFAULT_SEPARATOR}. * * @param in The reader to read the CSV data from. */ public CsvReader(@NonNull Reader in) { this(in, CsvWriter.DEFAULT_SEPARATOR); } /** * Creates a new {@link CsvReader} for the given reader. * * @param in The reader to read the CSV data from. * @param separator The separator character to use. */ public CsvReader(@NonNull Reader in, char separator) { this.in = in; this.separator = separator; } @Override public void close() throws IOException { in.close(); } /** * Reads the next element from the stream. This method must be used, so that {@link #peek()} correctly functions. * If the end of stream is detected, this method sets {@link #isEnd} to true. * * @return The read character. -1 if end of stream is reached. * * @throws IOException If reading the stream fails. */ private int read() throws IOException { int result; if (peeked != null) { result = peeked; peeked = null; } else { result = in.read(); } if (result == -1) { isEnd = true; } return result; } /** * Peeks at the next character. The next {@link #read()} call will return the same character. {@link #read()} must * be called at least once before calling {@link #peek()} again. * * @return The next character that will be read. -1 if next character will be end of stream. * * @throws IOException If reading the stream fails. * @throws IllegalStateException If {@link #peek()} is called twice, without {@link #read()} in between. */ private int peek() throws IOException { if (peeked != null) { throw new IllegalStateException("Cannot peek while already storing peeked character"); } peeked = in.read(); return peeked; } /** * Removes the escaping " from a given field. The same string is returned, if field is not escaped. Double "" * are escaped to only one ". * * @param field The field to un-escape. * @return The un-escaped field. */ private @NonNull String unescape(@NonNull String field) { StringBuilder escaped = new StringBuilder(); if (field.isEmpty() || field.charAt(0) != '"') { escaped.append(field); } else { for (int i = 1; i < field.length(); i++) { char c = field.charAt(i); if (c == '"' && i == field.length() - 1) { // trailing " means escaped sequence ended break; } else if (c == '"' && field.charAt(i + 1) == '"') { // double "" mean insert one " // move i to next character, so that only one " is added i++; } escaped.append(c); } } return notNull(escaped.toString()); } /** * Reads and parses a single line of CSV data. Splits at separator character. Considers (and un-escapes) * escaped values. * * @return The fields found in the CSV. * * @throws IOException If reading the stream fails. */ // CHECKSTYLE:OFF // TODO: this method is too long. private @NonNull String @Nullable [] readLine() throws IOException { // CHECKSTYLE:ON List<@NonNull String> parts = new LinkedList<>(); // whether we are currently inside an escape sequence // an escaped sequence starts with a " and ends with a " // the start " must be the first character of the field // the end " must be the last character of a field boolean inEscaped = false; // only relevant if inEscaped = true // whether the last read character was a " // used to detect the edge case that an escaped " is in front of a delimiter (e.g. ""; ) boolean wasQuote = false; // whether the last character was \r // only used to detect \r\n in escaped text boolean wasCarriageReturn = false; // contains characters of the current field // new characters are added until a (unescaped) separator is found // when a (unescaped) separator is found, the contents of this contain the previous field StringBuilder currentElement = new StringBuilder(); // break; will be called once the one of line (or stream) is reached while (true) { char c = (char) read(); if (isEnd) { currentLineNumber++; // increase for last line break; } if (c != '"') { // wasQuote is only relevant to detect double quotes ("") wasQuote = false; } if ((c == '\n' && !wasCarriageReturn) || c == '\r') { currentLineNumber++; } wasCarriageReturn = (c == '\r'); if (c == separator && !inEscaped) { // we found an unescaped separator parts.add(notNull(currentElement.toString())); currentElement.setLength(0); // jump back to start, to not add the separator to the next field continue; } else if (c == '"') { if (!inEscaped && currentElement.length() == 0) { // we found a " at the beginning of a field -> the field is escaped inEscaped = true; } else if (inEscaped && !wasQuote) { // check if we are at the end of a field, by peeking at the next character int peek = peek(); if (peek == -1 || peek == separator || peek == '\n' || peek == '\r') { // we found a " at the end of a field -> escaping ended inEscaped = false; // the next iteration will read() the end of field, so we don't have to do anything } else { // we just found a " in the middle of an escaped field wasQuote = true; } } else if (inEscaped) { // we are the " after another " wasQuote = false; } } else if ((c == '\n' || c == '\r') && !inEscaped) { // check if line-break is \r\n if (c == '\r') { int next = peek(); if (next == '\n') { // if \r is followed by \n, read the \n so that it doesn't re-appear in the next iteration. read(); } } // a non-escaped end of line -> we are done with this row break; } currentElement.append(c); } @NonNull String @Nullable [] result; if (parts.isEmpty() && currentElement.length() == 0 && peek() == -1) { // ignore last line in file, if its empty // we know that we are at the last line, if we didn't find any fields // (parts.empty() && currentElement.empty()) and the next char will be the end of stream result = null; isEnd = true; currentLineNumber--; } else { // add the last field (which we didn't find a separator for, because it was ended with a \n) parts.add(notNull(currentElement.toString())); result = notNull(parts.toArray(new @NonNull String[0])); for (int i = 0; i < result.length; i++) { result[i] = unescape(result[i]); } } return result; } @Override public @NonNull String @Nullable [] readNextRow() throws IOException { @NonNull String @Nullable [] result = null; if (!isEnd) { result = readLine(); } return result; } @Override public int getLineNumber() { return currentLineNumber; } }
Fixes a memory leak in CsvReader Avoids creating a new StringBuffer and converting it back when the same result is returned at the unescape method
src/net/ssehub/kernel_haven/util/io/csv/CsvReader.java
Fixes a memory leak in CsvReader
Java
apache-2.0
f26c29bce9565dfb1c5ebb9c5194c568a6ae6104
0
Graylog2/gelfclient
/* * Copyright 2012-2014 TORCH GmbH * * This file is part of Graylog2. * * Graylog2 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 3 of the License, or * (at your option) any later version. * * Graylog2 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 Graylog2. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.gelfclient.transport; import org.graylog2.gelfclient.GelfMessage; /** * @author Bernd Ahlers <[email protected]> */ public interface GelfTransport { public void send(GelfMessage message); public void stop(); public void sync() throws InterruptedException; }
src/main/java/org/graylog2/gelfclient/transport/GelfTransport.java
/* * Copyright 2012-2014 TORCH GmbH * * This file is part of Graylog2. * * Graylog2 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 3 of the License, or * (at your option) any later version. * * Graylog2 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 Graylog2. If not, see <http://www.gnu.org/licenses/>. */ package org.graylog2.gelfclient.transport; import org.graylog2.gelfclient.GelfMessage; /** * @author Bernd Ahlers <[email protected]> */ public interface GelfTransport { public void send(GelfMessage message); public void stop(); }
Add sync() to the GelfTransport interface.
src/main/java/org/graylog2/gelfclient/transport/GelfTransport.java
Add sync() to the GelfTransport interface.
Java
apache-2.0
5974e24232fdd9ae94c004474dd329a6f41f5766
0
apache/openwebbeans,apache/openwebbeans,apache/openwebbeans
/* * 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.webbeans.reservation.intercept; import javax.decorator.Decorates; import javax.decorator.Decorator; import javax.enterprise.inject.Any; import org.apache.commons.logging.Log; import org.apache.webbeans.reservation.bindings.ApplicationLog; import org.apache.webbeans.reservation.bindings.DatabaseLogin; import org.apache.webbeans.reservation.controller.api.ILoginController; import org.apache.webbeans.reservation.entity.User; @Decorator public class LoginDecorator implements ILoginController { @Decorates @Any @DatabaseLogin ILoginController decorator; private @ApplicationLog Log logger; /* (non-Javadoc) * @see org.apache.webbeans.reservation.controller.LoginController#checkLogin(java.lang.String, java.lang.String) */ public User checkLogin(String userName, String password) { logger.info("Login process is started. Use tries to login with user name : " + userName ); return null; } }
samples/reservation/src/main/java/org/apache/webbeans/reservation/intercept/LoginDecorator.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.webbeans.reservation.intercept; import javax.decorator.Decorates; import javax.decorator.Decorator; import org.apache.commons.logging.Log; import org.apache.webbeans.reservation.bindings.ApplicationLog; import org.apache.webbeans.reservation.bindings.DatabaseLogin; import org.apache.webbeans.reservation.controller.api.ILoginController; import org.apache.webbeans.reservation.entity.User; @Decorator public class LoginDecorator implements ILoginController { @Decorates @DatabaseLogin ILoginController decorator; private @ApplicationLog Log logger; /* (non-Javadoc) * @see org.apache.webbeans.reservation.controller.LoginController#checkLogin(java.lang.String, java.lang.String) */ public User checkLogin(String userName, String password) { logger.info("Login process is started. Use tries to login with user name : " + userName ); return null; } }
Update for @Any git-svn-id: 959c5dc4f35e0484f067e28fe24ef05c41faf244@786292 13f79535-47bb-0310-9956-ffa450edef68
samples/reservation/src/main/java/org/apache/webbeans/reservation/intercept/LoginDecorator.java
Update for @Any
Java
apache-2.0
bb5d07b3cb3ae725b4167c4295aea1662be6a79b
0
wskplho/android-maven-plugin,kedzie/maven-android-plugin,b-cuts/android-maven-plugin,xiaojiaqiao/android-maven-plugin,xieningtao/android-maven-plugin,greek1979/maven-android-plugin,jdegroot/android-maven-plugin,mitchhentges/android-maven-plugin,CJstar/android-maven-plugin,secondsun/maven-android-plugin,xiaojiaqiao/android-maven-plugin,ashutoshbhide/android-maven-plugin,Stuey86/android-maven-plugin,xiaojiaqiao/android-maven-plugin,b-cuts/android-maven-plugin,simpligility/android-maven-plugin,Cha0sX/android-maven-plugin,kevinsawicki/maven-android-plugin,psorobka/android-maven-plugin,kedzie/maven-android-plugin,WonderCsabo/maven-android-plugin,secondsun/maven-android-plugin,Stuey86/android-maven-plugin,Cha0sX/android-maven-plugin,Cha0sX/android-maven-plugin,jdegroot/android-maven-plugin,xieningtao/android-maven-plugin,secondsun/maven-android-plugin,mitchhentges/android-maven-plugin,psorobka/android-maven-plugin,wskplho/android-maven-plugin,repanda/android-maven-plugin,hgl888/android-maven-plugin,repanda/android-maven-plugin,hgl888/android-maven-plugin,WonderCsabo/maven-android-plugin,CJstar/android-maven-plugin,ashutoshbhide/android-maven-plugin,greek1979/maven-android-plugin
/* * Copyright (C) 2009-2011 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * 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.jayway.maven.plugins.android.standalonemojos; import com.android.ddmlib.AdbCommandRejectedException; import com.android.ddmlib.IDevice; import com.android.ddmlib.ShellCommandUnresponsiveException; import com.android.ddmlib.TimeoutException; import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner; import com.android.ddmlib.testrunner.ITestRunListener; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; import com.android.ddmlib.testrunner.TestIdentifier; import com.jayway.maven.plugins.android.AbstractIntegrationtestMojo; import com.jayway.maven.plugins.android.DeviceCallback; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import static com.android.ddmlib.testrunner.ITestRunListener.TestFailure.ERROR; /** * @author [email protected] */ public abstract class AbstractInstrumentationMojo extends AbstractIntegrationtestMojo { /** * Package name of the apk we wish to instrument. If not specified, it is inferred from * <code>AndroidManifest.xml</code>. * * @optional * @parameter expression="${android.test.instrumentationPackage} */ private String instrumentationPackage; /** * Class name of test runner. If not specified, it is inferred from <code>AndroidManifest.xml</code>. * * @optional * @parameter expression="${android.test.instrumentationRunner}" */ private String instrumentationRunner; /** * Enable debug causing the test runner to wait until debugger is * connected. * @optional * @parameter default-value=false expression="${android.test.debug}" */ private boolean testDebug; /** * Enable or disable code coverage for this test run. * @optional * @parameter default-value=false expression="${android.test.coverage}" */ private boolean testCoverage; /** * Enable this flag to run a log only and not execute the tests * @optional * @parameter default-value=false expression="${android.test.logonly}" */ private boolean testLogOnly; /** * If specified only execute tests of certain size as defined by the * SmallTest, MediumTest and LargeTest annotations. Use "small", * "medium" or "large" as values. * @see com.android.ddmlib.testrunner.IRemoteAndroidTestRunner * * @optional * @parameter expression="${android.test.testsize}" */ private String testSize; /** * Create * @optional * @parameter default-value=true expression="${android.test.createreport}" */ private boolean testCreateReport; /** * @optional * @parameter default-value="surefire-reports" expressions=${android.test.reportdirectory} */ private String testReportDirectory; private boolean testClassesExists; private boolean testPackagesExists; private String testPackages; private String[] testClassesArray; protected void instrument() throws MojoExecutionException, MojoFailureException { if (instrumentationPackage == null) { instrumentationPackage = extractPackageNameFromAndroidManifest(androidManifestFile); } if (instrumentationRunner == null) { instrumentationRunner = extractInstrumentationRunnerFromAndroidManifest(androidManifestFile); } // only run Tests in specific package testPackages = buildTestPackagesString(); testPackagesExists = StringUtils.isNotBlank(testPackages); if (testClasses != null) { testClassesArray = (String[]) testClasses.toArray(); testClassesExists = testClassesArray.length > 0; } else { testClassesExists = false; } if(testClassesExists && testPackagesExists) { // if both testPackages and testClasses are specified --> ERROR throw new MojoFailureException("testPackages and testClasses are mutual exclusive. They cannot be specified at the same time. " + "Please specify either testPackages or testClasses! For details, see http://developer.android.com/guide/developing/testing/testing_otheride.html"); } doWithDevices(new DeviceCallback() { public void doWithDevice(final IDevice device) throws MojoExecutionException, MojoFailureException { List<String> commands = new ArrayList<String>(); RemoteAndroidTestRunner remoteAndroidTestRunner = new RemoteAndroidTestRunner(instrumentationPackage, instrumentationRunner, device); if(testPackagesExists) { remoteAndroidTestRunner.setTestPackageName(testPackages); getLog().info("Running tests for specified test packages: " + testPackages); } if(testClassesExists) { remoteAndroidTestRunner.setClassNames(testClassesArray); getLog().info("Running tests for specified test " + "classes/methods: " + Arrays.toString(testClassesArray)); } remoteAndroidTestRunner.setDebug(testDebug); remoteAndroidTestRunner.setCoverage(testCoverage); remoteAndroidTestRunner.setLogOnly(testLogOnly); if (StringUtils.isNotBlank(testSize)) { IRemoteAndroidTestRunner.TestSize validSize = IRemoteAndroidTestRunner.TestSize.getTestSize(testSize); remoteAndroidTestRunner.setTestSize(validSize); } getLog().info("Running instrumentation tests in " + instrumentationPackage + " on " + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ")"); try { AndroidTestRunListener testRunListener = new AndroidTestRunListener(project, device); remoteAndroidTestRunner.run(testRunListener); if (testRunListener.hasFailuresOrErrors()) { throw new MojoFailureException("Tests failed on device."); } if (testRunListener.threwException()) { throw new MojoFailureException(testRunListener.getExceptionMessages()); } } catch (TimeoutException e) { throw new MojoExecutionException("timeout", e); } catch (AdbCommandRejectedException e) { throw new MojoExecutionException("adb command rejected", e); } catch (ShellCommandUnresponsiveException e) { throw new MojoExecutionException("shell command " + "unresponsive", e); } catch (IOException e) { throw new MojoExecutionException("IO problem", e); } } }); } /** * AndroidTestRunListener produces a nice output for the log for the test * run as well as an xml file compatible with the junit xml report file * format understood by many tools. * * It will do so for each device/emulator the tests run on. */ private class AndroidTestRunListener implements ITestRunListener { /** the indent used in the log to group items that belong together visually **/ private static final String INDENT = " "; /** * Junit report schema documentation is sparse. Here are some hints * @see "http://mail-archives.apache.org/mod_mbox/ant-dev/200902.mbox/%[email protected]%3E" * @see "http://junitpdfreport.sourceforge.net/managedcontent/PdfTranslation" */ private static final String TAG_TESTSUITES = "testsuites"; private static final String TAG_TESTSUITE = "testsuite"; private static final String ATTR_TESTSUITE_ERRORS = "errors"; private static final String ATTR_TESTSUITE_FAILURES = "failures"; private static final String ATTR_TESTSUITE_HOSTNAME = "hostname"; private static final String ATTR_TESTSUITE_NAME = "name"; private static final String ATTR_TESTSUITE_TESTS = "tests"; private static final String ATTR_TESTSUITE_TIME = "time"; private static final String ATTR_TESTSUITE_TIMESTAMP = "timestamp"; private static final String TAG_PROPERTIES = "properties"; private static final String TAG_PROPERTY = "property"; private static final String ATTR_PROPERTY_NAME = "name"; private static final String ATTR_PROPERTY_VALUE = "value"; private static final String TAG_TESTCASE = "testcase"; private static final String ATTR_TESTCASE_NAME = "name"; private static final String ATTR_TESTCASE_CLASSNAME = "classname"; private static final String ATTR_TESTCASE_TIME = "time"; private static final String TAG_ERROR = "error"; private static final String TAG_FAILURE = "failure"; private static final String ATTR_MESSAGE = "message"; private static final String ATTR_TYPE = "type"; /** time format for the output of milliseconds in seconds in the xml file **/ private final NumberFormat timeFormatter = new DecimalFormat("#0.0000"); private int testCount = 0; private int testFailureCount = 0; private int testErrorCount = 0; private MavenProject project; /** the emulator or device we are running the tests on **/ private IDevice device; private long testStartTime; // junit xml report related fields private Document junitReport; private Node testSuiteNode; private Node currentTestCaseNode; // we track if we have problems and then report upstream private boolean threwException = false; private StringBuilder exceptionMessages = new StringBuilder(); public AndroidTestRunListener(MavenProject project, IDevice device) { this.project = project; this.device = device; } public void testRunStarted(String runName, int testCount) { this.testCount = testCount; getLog().info(INDENT + "Run started: " + runName + ", " + testCount + " tests:"); if (testCreateReport) { try { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; parser = fact.newDocumentBuilder(); junitReport = parser.newDocument(); Node testSuitesNode = junitReport.createElement(TAG_TESTSUITES); junitReport.appendChild(testSuitesNode); testSuiteNode = junitReport.createElement(TAG_TESTSUITE); NamedNodeMap testSuiteAttributes = testSuiteNode.getAttributes(); Attr nameAttr = junitReport.createAttribute(ATTR_TESTSUITE_NAME); nameAttr.setValue(runName); testSuiteAttributes.setNamedItem(nameAttr); Attr hostnameAttr = junitReport.createAttribute(ATTR_TESTSUITE_HOSTNAME); hostnameAttr.setValue(getDeviceIdentifier()); testSuiteAttributes.setNamedItem(hostnameAttr); Node propertiesNode = junitReport.createElement(TAG_PROPERTIES); for (Map.Entry<Object, Object> property : System.getProperties().entrySet()) { Node propertyNode = junitReport.createElement(TAG_PROPERTY); NamedNodeMap propertyAttributes = propertyNode.getAttributes(); Attr propNameAttr = junitReport.createAttribute(ATTR_PROPERTY_NAME); propNameAttr.setValue(property.getKey().toString()); propertyAttributes.setNamedItem(propNameAttr); Attr propValueAttr = junitReport.createAttribute(ATTR_PROPERTY_VALUE); propValueAttr.setValue(property.getValue().toString()); propertyAttributes.setNamedItem(propValueAttr); propertiesNode.appendChild(propertyNode); } testSuiteNode.appendChild(propertiesNode); testSuitesNode.appendChild(testSuiteNode); } catch (ParserConfigurationException e) { threwException = true; exceptionMessages.append("Failed to create document"); exceptionMessages.append(e.getMessage()); } } } public void testStarted(TestIdentifier test) { getLog().info(INDENT + INDENT +"Start: " + test.toString()); if (testCreateReport) { currentTestCaseNode = junitReport.createElement(TAG_TESTCASE); NamedNodeMap testCaseAttributes = currentTestCaseNode.getAttributes(); Attr classAttr = junitReport.createAttribute(ATTR_TESTCASE_CLASSNAME); classAttr.setValue(test.getClassName()); testCaseAttributes.setNamedItem(classAttr); Attr methodAttr = junitReport.createAttribute(ATTR_TESTCASE_NAME); methodAttr.setValue(test.getTestName()); testCaseAttributes.setNamedItem(methodAttr); } } public void testFailed(TestFailure status, TestIdentifier test, String trace) { if (status==ERROR) { ++testErrorCount; } else { ++testFailureCount; } getLog().info(INDENT + INDENT + status.name() + ":" + test.toString()); getLog().info(INDENT + INDENT + trace); if (testCreateReport) { Node errorFailureNode; NamedNodeMap errorfailureAttributes; if (status == ERROR) { errorFailureNode = junitReport.createElement(TAG_ERROR); errorfailureAttributes = errorFailureNode.getAttributes(); } else { errorFailureNode = junitReport.createElement(TAG_FAILURE); errorfailureAttributes= errorFailureNode.getAttributes(); } errorFailureNode.setTextContent(trace); Attr msgAttr = junitReport.createAttribute(ATTR_MESSAGE); msgAttr.setValue(parseForMessage(trace)); errorfailureAttributes.setNamedItem(msgAttr); Attr typeAttr = junitReport.createAttribute(ATTR_TYPE); typeAttr.setValue(parseForException(trace)); errorfailureAttributes.setNamedItem(typeAttr); currentTestCaseNode.appendChild(errorFailureNode); } } public void testEnded(TestIdentifier test, Map<String, String> testMetrics) { getLog().info( INDENT + INDENT +"End: " + test.toString()); logMetrics(testMetrics); if (testCreateReport) { testSuiteNode.appendChild(currentTestCaseNode); NamedNodeMap testCaseAttributes = currentTestCaseNode.getAttributes(); Attr timeAttr = junitReport.createAttribute(ATTR_TESTCASE_TIME); timeAttr.setValue(getTestDuration()); testCaseAttributes.setNamedItem(timeAttr); } } public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) { getLog().info(INDENT +"Run ended: " + elapsedTime + " ms"); if (hasFailuresOrErrors()) { getLog().error(INDENT + "FAILURES!!!"); } getLog().info(INDENT + "Tests run: " + testCount + ", Failures: " + testFailureCount + ", Errors: " + testErrorCount); if (testCreateReport) { NamedNodeMap testSuiteAttributes = testSuiteNode.getAttributes(); Attr testCountAttr = junitReport.createAttribute(ATTR_TESTSUITE_TESTS); testCountAttr.setValue(Integer.toString(testCount)); testSuiteAttributes.setNamedItem(testCountAttr); Attr testFailuresAttr = junitReport.createAttribute(ATTR_TESTSUITE_FAILURES); testFailuresAttr.setValue(Integer.toString(testFailureCount)); testSuiteAttributes.setNamedItem(testFailuresAttr); Attr testErrorsAttr = junitReport.createAttribute(ATTR_TESTSUITE_ERRORS); testErrorsAttr.setValue(Integer.toString(testErrorCount)); testSuiteAttributes.setNamedItem(testErrorsAttr); Attr timeAttr = junitReport.createAttribute(ATTR_TESTSUITE_TIME); timeAttr.setValue(timeFormatter.format(elapsedTime / 1000.0)); testSuiteAttributes.setNamedItem(timeAttr); Attr timeStampAttr = junitReport.createAttribute(ATTR_TESTSUITE_TIMESTAMP); timeStampAttr.setValue( new Date().toString()); testSuiteAttributes.setNamedItem(timeStampAttr); } logMetrics(runMetrics); if (testCreateReport) { writeJunitReportToFile(); } } public void testRunFailed(String errorMessage) { getLog().info(INDENT +"Run failed: " + errorMessage); } public void testRunStopped(long elapsedTime) { getLog().info(INDENT +"Run stopped:" + elapsedTime); } private String parseForMessage(String trace) { return trace.substring(trace.indexOf(":") + 2, trace.indexOf("\r\n")); } private String parseForException(String trace) { return trace.substring(0, trace.indexOf(":")); } private String getTestDuration() { long now = new Date().getTime(); double seconds = (now - testStartTime)/1000.0; return timeFormatter.format(seconds); } private void writeJunitReportToFile() { TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = null; try { xformer = xfactory.newTransformer(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } Source source = new DOMSource(junitReport); FileWriter writer = null; try { String directory = new StringBuilder() .append(project.getBuild().getDirectory()) .append("/") .append(testReportDirectory).toString(); createDirectoryIfNecessary(directory); String fileName = new StringBuilder() .append(project.getBuild().getDirectory()) .append("/") .append(testReportDirectory) .append("/TEST-") .append(getDeviceIdentifier()) .append(".xml") .toString(); File reportFile = new File(fileName); writer = new FileWriter(reportFile); Result result = new StreamResult(writer); xformer.transform(source, result); getLog().info("Report file written to " + reportFile.getAbsolutePath()); } catch (IOException e) { threwException = true; exceptionMessages.append("Failed to write test report file"); exceptionMessages.append(e.getMessage()); } catch (TransformerException e) { threwException = true; exceptionMessages.append("Failed to transform document to write to test report file"); exceptionMessages.append(e.getMessage()); } finally { IOUtils.closeQuietly(writer); } } private void logMetrics(Map<String, String> metrics) { for (Map.Entry<String, String> entry : metrics.entrySet()) { getLog().info(INDENT + INDENT + entry.getKey() + ": " + entry.getValue()); } } public boolean hasFailuresOrErrors() { return testErrorCount > 0 || testFailureCount > 0; } public boolean threwException() { return threwException; } public String getExceptionMessages() { return exceptionMessages.toString(); } private String getDeviceIdentifier() { String SEPARATOR = "_"; StringBuilder identfier = new StringBuilder() .append(device.getSerialNumber()); if (device.getAvdName() != null) { identfier.append(SEPARATOR).append(device.getAvdName()); } else { String manufacturer = StringUtils.deleteWhitespace(device.getProperty("ro.product.manufacturer")); if (StringUtils.isNotBlank(manufacturer)) { identfier.append(SEPARATOR).append(manufacturer); } String model = StringUtils.deleteWhitespace(device.getProperty("ro.product.model")); if (StringUtils.isNotBlank(model)) { identfier.append(SEPARATOR).append(model); } } return identfier.toString(); } private void createDirectoryIfNecessary(String testReportDirectory) { File directory = new File(testReportDirectory); if (!directory.isDirectory()) { directory.mkdir(); } } } }
src/main/java/com/jayway/maven/plugins/android/standalonemojos/AbstractInstrumentationMojo.java
/* * Copyright (C) 2009-2011 Jayway AB * Copyright (C) 2007-2008 JVending Masa * * 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.jayway.maven.plugins.android.standalonemojos; import com.android.ddmlib.AdbCommandRejectedException; import com.android.ddmlib.IDevice; import com.android.ddmlib.ShellCommandUnresponsiveException; import com.android.ddmlib.TimeoutException; import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner; import com.android.ddmlib.testrunner.ITestRunListener; import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; import com.android.ddmlib.testrunner.TestIdentifier; import com.jayway.maven.plugins.android.AbstractIntegrationtestMojo; import com.jayway.maven.plugins.android.DeviceCallback; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import static com.android.ddmlib.testrunner.ITestRunListener.TestFailure.ERROR; /** * @author [email protected] */ public abstract class AbstractInstrumentationMojo extends AbstractIntegrationtestMojo { /** * Package name of the apk we wish to instrument. If not specified, it is inferred from * <code>AndroidManifest.xml</code>. * * @optional * @parameter expression="${android.test.instrumentationPackage} */ private String instrumentationPackage; /** * Class name of test runner. If not specified, it is inferred from <code>AndroidManifest.xml</code>. * * @optional * @parameter expression="${android.test.instrumentationRunner}" */ private String instrumentationRunner; /** * Enable debug causing the test runner to wait until debugger is * connected. * @optional * @parameter default-value=false expression="${android.test.debug}" */ private boolean testDebug; /** * Enable or disable code coverage for this test run. * @optional * @parameter default-value=false expression="${android.test.coverage}" */ private boolean testCoverage; /** * Enable this flag to run a log only and not execute the tests * @optional * @parameter default-value=false expression="${android.test.logonly}" */ private boolean testLogOnly; /** * If specified only execute tests of certain size as defined by the * SmallTest, MediumTest and LargeTest annotations. Use "small", * "medium" or "large" as values. * @see com.android.ddmlib.testrunner.IRemoteAndroidTestRunner * * @optional * @parameter expression="${android.test.testsize}" */ private String testSize; /** * Create * @optional * @parameter default-value=true expression="${android.test.createreport}" */ private boolean testCreateReport; /** * @optional * @parameter default-value="surefire-reports" expressions=${android.test.reportdirectory} */ private String testReportDirectory; private boolean testClassesExists; private boolean testPackagesExists; private String testPackages; private String[] testClassesArray; protected void instrument() throws MojoExecutionException, MojoFailureException { if (instrumentationPackage == null) { instrumentationPackage = extractPackageNameFromAndroidManifest(androidManifestFile); } if (instrumentationRunner == null) { instrumentationRunner = extractInstrumentationRunnerFromAndroidManifest(androidManifestFile); } // only run Tests in specific package testPackages = buildTestPackagesString(); testPackagesExists = StringUtils.isNotBlank(testPackages); if (testClasses != null) { testClassesArray = (String[]) testClasses.toArray(); testClassesExists = testClassesArray.length > 0; } else { testClassesExists = false; } if(testClassesExists && testPackagesExists) { // if both testPackages and testClasses are specified --> ERROR throw new MojoFailureException("testPackages and testClasses are mutual exclusive. They cannot be specified at the same time. " + "Please specify either testPackages or testClasses! For details, see http://developer.android.com/guide/developing/testing/testing_otheride.html"); } doWithDevices(new DeviceCallback() { public void doWithDevice(final IDevice device) throws MojoExecutionException, MojoFailureException { List<String> commands = new ArrayList<String>(); RemoteAndroidTestRunner remoteAndroidTestRunner = new RemoteAndroidTestRunner(instrumentationPackage, instrumentationRunner, device); if(testPackagesExists) { remoteAndroidTestRunner.setTestPackageName(testPackages); getLog().info("Running tests for specified test packages: " + testPackages); } if(testClassesExists) { remoteAndroidTestRunner.setClassNames(testClassesArray); getLog().info("Running tests for specified test " + "classes/methods: " + Arrays.toString(testClassesArray)); } remoteAndroidTestRunner.setDebug(testDebug); remoteAndroidTestRunner.setCoverage(testCoverage); remoteAndroidTestRunner.setLogOnly(testLogOnly); if (StringUtils.isNotBlank(testSize)) { IRemoteAndroidTestRunner.TestSize validSize = IRemoteAndroidTestRunner.TestSize.getTestSize(testSize); remoteAndroidTestRunner.setTestSize(validSize); } getLog().info("Running instrumentation tests in " + instrumentationPackage + " on " + device.getSerialNumber() + " (avdName=" + device.getAvdName() + ")"); try { AndroidTestRunListener testRunListener = new AndroidTestRunListener(project, device); remoteAndroidTestRunner.run(testRunListener); if (testRunListener.hasFailuresOrErrors()) { throw new MojoFailureException("Tests failed on device."); } } catch (TimeoutException e) { throw new MojoExecutionException("timeout", e); } catch (AdbCommandRejectedException e) { throw new MojoExecutionException("adb command rejected", e); } catch (ShellCommandUnresponsiveException e) { throw new MojoExecutionException("shell command " + "unresponsive", e); } catch (IOException e) { throw new MojoExecutionException("IO problem", e); } } }); } /** * AndroidTestRunListener produces a nice output for the log for the test * run as well as an xml file compatible with the junit xml report file * format understood by many tools. * * It will do so for each device/emulator the tests run on. */ private class AndroidTestRunListener implements ITestRunListener { /** the indent used in the log to group items that belong together visually **/ private static final String INDENT = " "; /** * Junit report schema documentation is sparse. Here are some hints * @see "http://mail-archives.apache.org/mod_mbox/ant-dev/200902.mbox/%[email protected]%3E" * @see "http://junitpdfreport.sourceforge.net/managedcontent/PdfTranslation" */ private static final String TAG_TESTSUITES = "testsuites"; private static final String TAG_TESTSUITE = "testsuite"; private static final String ATTR_TESTSUITE_ERRORS = "errors"; private static final String ATTR_TESTSUITE_FAILURES = "failures"; private static final String ATTR_TESTSUITE_HOSTNAME = "hostname"; private static final String ATTR_TESTSUITE_NAME = "name"; private static final String ATTR_TESTSUITE_TESTS = "tests"; private static final String ATTR_TESTSUITE_TIME = "time"; private static final String ATTR_TESTSUITE_TIMESTAMP = "timestamp"; private static final String TAG_PROPERTIES = "properties"; private static final String TAG_PROPERTY = "property"; private static final String ATTR_PROPERTY_NAME = "name"; private static final String ATTR_PROPERTY_VALUE = "value"; private static final String TAG_TESTCASE = "testcase"; private static final String ATTR_TESTCASE_NAME = "name"; private static final String ATTR_TESTCASE_CLASSNAME = "classname"; private static final String ATTR_TESTCASE_TIME = "time"; private static final String TAG_ERROR = "error"; private static final String TAG_FAILURE = "failure"; private static final String ATTR_MESSAGE = "message"; private static final String ATTR_TYPE = "type"; /** time format for the output of milliseconds in seconds in the xml file **/ private final NumberFormat timeFormatter = new DecimalFormat("#0.0000"); private int testCount = 0; private int testFailureCount = 0; private int testErrorCount = 0; private MavenProject project; private IDevice device; private long mTestStarted; private long mRunStarted; private Document junitReport; private Node testSuiteNode; private Node currentTestCaseNode; public AndroidTestRunListener(MavenProject project, IDevice device) { this.project = project; this.device = device; } public void testRunStarted(String runName, int testCount) { this.testCount = testCount; mRunStarted = new Date().getTime(); getLog().info(INDENT + "Run started: " + runName + ", " + "" + testCount + " tests:"); if (testCreateReport) { try { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = null; parser = fact.newDocumentBuilder(); junitReport = parser.newDocument(); Node testSuitesNode = junitReport.createElement(TAG_TESTSUITES); junitReport.appendChild(testSuitesNode); testSuiteNode = junitReport.createElement(TAG_TESTSUITE); NamedNodeMap testSuiteAttributes = testSuiteNode.getAttributes(); Attr nameAttr = junitReport.createAttribute(ATTR_TESTSUITE_NAME); nameAttr.setValue(runName); testSuiteAttributes.setNamedItem(nameAttr); Attr hostnameAttr = junitReport.createAttribute(ATTR_TESTSUITE_HOSTNAME); hostnameAttr.setValue(getDeviceIdentifier()); testSuiteAttributes.setNamedItem(hostnameAttr); Node propertiesNode = junitReport.createElement(TAG_PROPERTIES); for (Map.Entry<Object, Object> property : System.getProperties().entrySet()) { Node propertyNode = junitReport.createElement(TAG_PROPERTY); NamedNodeMap propertyAttributes = propertyNode.getAttributes(); Attr propNameAttr = junitReport.createAttribute(ATTR_PROPERTY_NAME); propNameAttr.setValue(property.getKey().toString()); propertyAttributes.setNamedItem(propNameAttr); Attr propValueAttr = junitReport.createAttribute(ATTR_PROPERTY_VALUE); propValueAttr.setValue(property.getValue().toString()); propertyAttributes.setNamedItem(propValueAttr); propertiesNode.appendChild(propertyNode); } testSuiteNode.appendChild(propertiesNode); testSuitesNode.appendChild(testSuiteNode); } catch (ParserConfigurationException e) { // throw new MojoExecutionException("Failed to create junit document", e); } } } public void testStarted(TestIdentifier test) { mTestStarted = new Date().getTime(); getLog().info(INDENT + INDENT +"Start: " + test.toString()); if (testCreateReport) { currentTestCaseNode = junitReport.createElement(TAG_TESTCASE); NamedNodeMap testCaseAttributes = currentTestCaseNode.getAttributes(); Attr classAttr = junitReport.createAttribute(ATTR_TESTCASE_CLASSNAME); classAttr.setValue(test.getClassName()); testCaseAttributes.setNamedItem(classAttr); Attr methodAttr = junitReport.createAttribute(ATTR_TESTCASE_NAME); methodAttr.setValue(test.getTestName()); testCaseAttributes.setNamedItem(methodAttr); } } public void testFailed(TestFailure status, TestIdentifier test, String trace) { if (status==ERROR) { ++testErrorCount; } else { ++testFailureCount; } getLog().info(INDENT + INDENT + status.name() + ":" + test.toString()); getLog().info(INDENT + INDENT + trace); if (testCreateReport) { Node errorFailureNode; NamedNodeMap errorfailureAttributes; if (status == ERROR) { errorFailureNode = junitReport.createElement(TAG_ERROR); errorfailureAttributes = errorFailureNode.getAttributes(); } else { errorFailureNode = junitReport.createElement(TAG_FAILURE); errorfailureAttributes= errorFailureNode.getAttributes(); } errorFailureNode.setTextContent(trace); Attr msgAttr = junitReport.createAttribute(ATTR_MESSAGE); msgAttr.setValue(parseForMessage(trace)); errorfailureAttributes.setNamedItem(msgAttr); Attr typeAttr = junitReport.createAttribute(ATTR_TYPE); typeAttr.setValue(parseForException(trace)); errorfailureAttributes.setNamedItem(typeAttr); currentTestCaseNode.appendChild(errorFailureNode); } } public void testEnded(TestIdentifier test, Map<String, String> testMetrics) { getLog().info( INDENT + INDENT +"End: " + test.toString()); logMetrics(testMetrics); if (testCreateReport) { testSuiteNode.appendChild(currentTestCaseNode); NamedNodeMap testCaseAttributes = currentTestCaseNode.getAttributes(); Attr timeAttr = junitReport.createAttribute(ATTR_TESTCASE_TIME); timeAttr.setValue(getTestDuration()); testCaseAttributes.setNamedItem(timeAttr); } } public void testRunEnded(long elapsedTime, Map<String, String> runMetrics) { getLog().info(INDENT +"Run ended: " + elapsedTime + " ms"); if (hasFailuresOrErrors()) { getLog().error(INDENT + "FAILURES!!!"); } getLog().info(INDENT + "Tests run: " + testCount + ", Failures: " + testFailureCount + ", Errors: " + testErrorCount); if (testCreateReport) { NamedNodeMap testSuiteAttributes = testSuiteNode.getAttributes(); Attr testCountAttr = junitReport.createAttribute(ATTR_TESTSUITE_TESTS); testCountAttr.setValue(Integer.toString(testCount)); testSuiteAttributes.setNamedItem(testCountAttr); Attr testFailuresAttr = junitReport.createAttribute(ATTR_TESTSUITE_FAILURES); testFailuresAttr.setValue(Integer.toString(testFailureCount)); testSuiteAttributes.setNamedItem(testFailuresAttr); Attr testErrorsAttr = junitReport.createAttribute(ATTR_TESTSUITE_ERRORS); testErrorsAttr.setValue(Integer.toString(testErrorCount)); testSuiteAttributes.setNamedItem(testErrorsAttr); Attr timeAttr = junitReport.createAttribute(ATTR_TESTSUITE_TIME); timeAttr.setValue(timeFormatter.format(elapsedTime / 1000.0)); testSuiteAttributes.setNamedItem(timeAttr); Attr timeStampAttr = junitReport.createAttribute(ATTR_TESTSUITE_TIMESTAMP); timeStampAttr.setValue( new Date().toString()); testSuiteAttributes.setNamedItem(timeStampAttr); } logMetrics(runMetrics); if (testCreateReport) { writeJunitReportToFile(); } } private String getTestDuration() { long now = new Date().getTime(); double seconds = (now - mTestStarted)/1000.0; return timeFormatter.format(seconds); } public void testRunFailed(String errorMessage) { getLog().info(INDENT +"Run failed: " + errorMessage); } public void testRunStopped(long elapsedTime) { getLog().info(INDENT +"Run stopped:" + elapsedTime); } private String parseForMessage(String trace) { return trace.substring(trace.indexOf(":") + 2, trace.indexOf("\r\n")); } private String parseForException(String trace) { return trace.substring(0, trace.indexOf(":")); } private void writeJunitReportToFile() { TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = null; try { xformer = xfactory.newTransformer(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } Source source = new DOMSource(junitReport); FileWriter writer = null; try { String directory = new StringBuilder() .append(project.getBuild().getDirectory()) .append("/") .append(testReportDirectory).toString(); createDirectoryIfNecessary(directory); String fileName = new StringBuilder() .append(project.getBuild().getDirectory()) .append("/") .append(testReportDirectory) .append("/TEST-") .append(getDeviceIdentifier()) .append(".xml") .toString(); File reportFile = new File(fileName); writer = new FileWriter(reportFile); Result result = new StreamResult(writer); xformer.transform(source, result); getLog().info("Report file written to " + reportFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (TransformerException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } finally { IOUtils.closeQuietly(writer); } } private void logMetrics(Map<String, String> metrics) { for (Map.Entry<String, String> entry : metrics.entrySet()) { getLog().info(INDENT + INDENT + entry.getKey() + ": " + entry.getValue()); } } public boolean hasFailuresOrErrors() { return testErrorCount > 0 || testFailureCount > 0; } private String getDeviceIdentifier() { StringBuilder identfier = new StringBuilder() .append(device.getSerialNumber()); if (device.getAvdName() != null) { identfier.append("_").append(device.getAvdName()); } return identfier.toString(); } } private void createDirectoryIfNecessary(String testReportDirectory) { File directory = new File(testReportDirectory); if (!directory.isDirectory()) { directory.mkdir(); } } }
propagating exceptions from test runs up
src/main/java/com/jayway/maven/plugins/android/standalonemojos/AbstractInstrumentationMojo.java
propagating exceptions from test runs up
Java
apache-2.0
669d013fafaf6d12d7f3e65611e09253af70d568
0
real-logic/Agrona,tbrooks8/Agrona
/* * Copyright 2014-2018 Real Logic 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.agrona; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.util.Arrays; import java.util.function.BiConsumer; import static java.nio.channels.FileChannel.MapMode.READ_ONLY; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; /** * Collection of IO utilities. */ public class IoUtil { /** * Size in bytes of a file page. */ public static final int BLOCK_SIZE = 4 * 1024; private static final byte[] FILLER = new byte[BLOCK_SIZE]; private static final int MAP_READ_ONLY = 0; private static final int MAP_READ_WRITE = 1; private static final int MAP_PRIVATE = 2; private static final Method MAP_ADDRESS; private static final Method UNMAP_ADDRESS; private static final Method UNMAP_BUFFER; static { MAP_ADDRESS = getFileChannelMethod("map0", int.class, long.class, long.class); UNMAP_ADDRESS = getFileChannelMethod("unmap0", long.class, long.class); UNMAP_BUFFER = getFileChannelMethod("unmap", MappedByteBuffer.class); } /** * Fill a region of a file with a given byte value. * * @param fileChannel to fill * @param position at which to start writing. * @param length of the region to write. * @param value to fill the region with. */ public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value) { try { final byte[] filler; if (0 != value) { filler = new byte[BLOCK_SIZE]; Arrays.fill(filler, value); } else { filler = FILLER; } final ByteBuffer byteBuffer = ByteBuffer.wrap(filler); fileChannel.position(position); final int blocks = (int)(length / BLOCK_SIZE); final int blockRemainder = (int)(length % BLOCK_SIZE); for (int i = 0; i < blocks; i++) { byteBuffer.position(0); fileChannel.write(byteBuffer); } if (blockRemainder > 0) { byteBuffer.position(0); byteBuffer.limit(blockRemainder); fileChannel.write(byteBuffer); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } /** * Recursively delete a file or directory tree. * * @param file to be deleted. * @param ignoreFailures don't throw an exception if a delete fails. */ public static void delete(final File file, final boolean ignoreFailures) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files) { delete(f, ignoreFailures); } } } if (!file.delete() && !ignoreFailures) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Create a directory if it doesn't already exist. * * @param directory the directory which definitely exists after this method call. * @param descriptionLabel to associate with the directory for any exceptions. */ public static void ensureDirectoryExists(final File directory, final String descriptionLabel) { if (!directory.exists()) { if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } } /** * Create a directory, removing previous directory if it already exists. * <p> * Call callback if it does exist. * * @param directory the directory which definitely exists after this method call. * @param descriptionLabel to associate with the directory for any exceptions and callback. * @param callback to call if directory exists passing back absolute path and descriptionLabel. */ public static void ensureDirectoryIsRecreated( final File directory, final String descriptionLabel, final BiConsumer<String, String> callback) { if (directory.exists()) { delete(directory, false); callback.accept(directory.getAbsolutePath(), descriptionLabel); } if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } /** * Delete file only if it already exists. * * @param file to delete */ public static void deleteIfExists(final File file) { if (file.exists()) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Create an empty file, fill with 0s, and return the {@link FileChannel} * * @param file to create * @param length of the file to create * @return {@link java.nio.channels.FileChannel} for the file */ public static FileChannel createEmptyFile(final File file, final long length) { return createEmptyFile(file, length, true); } /** * Create an empty file, and optionally fill with 0s, and return the {@link FileChannel} * * @param file to create * @param length of the file to create * @param fillWithZeros to the length of the file to force allocation. * @return {@link java.nio.channels.FileChannel} for the file */ public static FileChannel createEmptyFile(final File file, final long length, final boolean fillWithZeros) { ensureDirectoryExists(file.getParentFile(), file.getParent()); FileChannel templateFile = null; try { final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.setLength(length); templateFile = randomAccessFile.getChannel(); if (fillWithZeros) { fill(templateFile, 0, length, (byte)0); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return templateFile; } /** * Check that file exists, open file, and return MappedByteBuffer for entire file * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to map * @param descriptionLabel to be associated for any exceptions * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapExistingFile(final File location, final String descriptionLabel) { checkFileExists(location, descriptionLabel); MappedByteBuffer mappedByteBuffer = null; try (RandomAccessFile file = new RandomAccessFile(location, "rw"); FileChannel channel = file.getChannel()) { mappedByteBuffer = channel.map(READ_WRITE, 0, channel.size()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Check that file exists, open file, and return MappedByteBuffer for only region specified * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to map * @param descriptionLabel to be associated for an exceptions * @param offset offset to start mapping at * @param length length to map region * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapExistingFile( final File location, final String descriptionLabel, final long offset, final long length) { checkFileExists(location, descriptionLabel); MappedByteBuffer mappedByteBuffer = null; try (RandomAccessFile file = new RandomAccessFile(location, "rw"); FileChannel channel = file.getChannel()) { mappedByteBuffer = channel.map(READ_WRITE, offset, length); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Create a new file, fill with 0s, and return a {@link java.nio.MappedByteBuffer} for the file. * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to create and map * @param length of the file to create and map * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapNewFile(final File location, final long length) { return mapNewFile(location, length, true); } /** * Create a new file, and optionally fill with 0s, and return a {@link java.nio.MappedByteBuffer} for the file. * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to create and map * @param length of the file to create and map * @param fillWithZeros to force allocation. * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapNewFile(final File location, final long length, final boolean fillWithZeros) { MappedByteBuffer mappedByteBuffer = null; try (FileChannel channel = FileChannel.open(location.toPath(), CREATE_NEW, READ, WRITE)) { mappedByteBuffer = channel.map(READ_WRITE, 0, length); if (fillWithZeros) { int pos = 0; while (pos < length) { mappedByteBuffer.put(pos, (byte)0); pos += BLOCK_SIZE; } } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Check that a file exists and throw an exception if not. * * @param file to check existence of. * @param name to associate for the exception */ public static void checkFileExists(final File file, final String name) { if (!file.exists()) { final String msg = "Missing file for " + name + " : " + file.getAbsolutePath(); throw new IllegalStateException(msg); } } /** * Unmap a {@link MappedByteBuffer} without waiting for the next GC cycle. * * @param buffer to be unmapped. */ public static void unmap(final MappedByteBuffer buffer) { if (null != buffer) { try { UNMAP_BUFFER.invoke(null, buffer); } catch (final Exception ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Map a range of a file and return the address at which the range begins. * * @param fileChannel to be mapped. * @param mode for the mapped region. * @param offset within the file the mapped region should start. * @param length of the mapped region. * @return the address at which the mapping starts. */ public static long map( final FileChannel fileChannel, final FileChannel.MapMode mode, final long offset, final long length) { try { return (long)MAP_ADDRESS.invoke(fileChannel, getMode(mode), offset, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } return 0; } /** * Unmap a region of a file. * * @param fileChannel which has been mapped. * @param address at which the mapping begins. * @param length of the mapped region. */ public static void unmap(final FileChannel fileChannel, final long address, final long length) { try { UNMAP_ADDRESS.invoke(fileChannel, address, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } } /** * Unmap a {@link ByteBuffer} without waiting for the next GC cycle if its memory mapped. * * @param buffer to be unmapped. */ public static void unmap(final ByteBuffer buffer) { if (buffer instanceof MappedByteBuffer) { unmap((MappedByteBuffer)buffer); } } /** * Return the system property for java.io.tmpdir ensuring a {@link File#separator} is at the end. * * @return tmp directory for the runtime */ public static String tmpDirName() { String tmpDirName = System.getProperty("java.io.tmpdir"); if (!tmpDirName.endsWith(File.separator)) { tmpDirName += File.separator; } return tmpDirName; } private static Method getFileChannelMethod(final String name, final Class<?>... parameterTypes) { Method method = null; try { method = Class.forName("sun.nio.ch.FileChannelImpl").getDeclaredMethod(name, parameterTypes); method.setAccessible(true); } catch (final Exception ex) { LangUtil.rethrowUnchecked(ex); } return method; } private static int getMode(final FileChannel.MapMode mode) { if (mode == READ_ONLY) { return MAP_READ_ONLY; } else if (mode == READ_WRITE) { return MAP_READ_WRITE; } else { return MAP_PRIVATE; } } }
agrona/src/main/java/org/agrona/IoUtil.java
/* * Copyright 2014-2018 Real Logic 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.agrona; import sun.nio.ch.FileChannelImpl; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.util.Arrays; import java.util.function.BiConsumer; import static java.nio.channels.FileChannel.MapMode.READ_ONLY; import static java.nio.channels.FileChannel.MapMode.READ_WRITE; import static java.nio.file.StandardOpenOption.CREATE_NEW; import static java.nio.file.StandardOpenOption.READ; import static java.nio.file.StandardOpenOption.WRITE; /** * Collection of IO utilities. */ public class IoUtil { /** * Size in bytes of a file page. */ public static final int BLOCK_SIZE = 4 * 1024; private static final byte[] FILLER = new byte[BLOCK_SIZE]; private static final int MAP_READ_ONLY = 0; private static final int MAP_READ_WRITE = 1; private static final int MAP_PRIVATE = 2; private static final Method MAP_ADDRESS; private static final Method UNMAP_ADDRESS; private static final Method UNMAP_BUFFER; static { MAP_ADDRESS = getFileChannelMethod("map0", int.class, long.class, long.class); UNMAP_ADDRESS = getFileChannelMethod("unmap0", long.class, long.class); UNMAP_BUFFER = getFileChannelMethod("unmap", MappedByteBuffer.class); } /** * Fill a region of a file with a given byte value. * * @param fileChannel to fill * @param position at which to start writing. * @param length of the region to write. * @param value to fill the region with. */ public static void fill(final FileChannel fileChannel, final long position, final long length, final byte value) { try { final byte[] filler; if (0 != value) { filler = new byte[BLOCK_SIZE]; Arrays.fill(filler, value); } else { filler = FILLER; } final ByteBuffer byteBuffer = ByteBuffer.wrap(filler); fileChannel.position(position); final int blocks = (int)(length / BLOCK_SIZE); final int blockRemainder = (int)(length % BLOCK_SIZE); for (int i = 0; i < blocks; i++) { byteBuffer.position(0); fileChannel.write(byteBuffer); } if (blockRemainder > 0) { byteBuffer.position(0); byteBuffer.limit(blockRemainder); fileChannel.write(byteBuffer); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } /** * Recursively delete a file or directory tree. * * @param file to be deleted. * @param ignoreFailures don't throw an exception if a delete fails. */ public static void delete(final File file, final boolean ignoreFailures) { if (file.isDirectory()) { final File[] files = file.listFiles(); if (null != files) { for (final File f : files) { delete(f, ignoreFailures); } } } if (!file.delete() && !ignoreFailures) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Create a directory if it doesn't already exist. * * @param directory the directory which definitely exists after this method call. * @param descriptionLabel to associate with the directory for any exceptions. */ public static void ensureDirectoryExists(final File directory, final String descriptionLabel) { if (!directory.exists()) { if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } } /** * Create a directory, removing previous directory if it already exists. * <p> * Call callback if it does exist. * * @param directory the directory which definitely exists after this method call. * @param descriptionLabel to associate with the directory for any exceptions and callback. * @param callback to call if directory exists passing back absolute path and descriptionLabel. */ public static void ensureDirectoryIsRecreated( final File directory, final String descriptionLabel, final BiConsumer<String, String> callback) { if (directory.exists()) { delete(directory, false); callback.accept(directory.getAbsolutePath(), descriptionLabel); } if (!directory.mkdirs()) { throw new IllegalArgumentException("could not create " + descriptionLabel + " directory: " + directory); } } /** * Delete file only if it already exists. * * @param file to delete */ public static void deleteIfExists(final File file) { if (file.exists()) { try { Files.delete(file.toPath()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Create an empty file, fill with 0s, and return the {@link FileChannel} * * @param file to create * @param length of the file to create * @return {@link java.nio.channels.FileChannel} for the file */ public static FileChannel createEmptyFile(final File file, final long length) { return createEmptyFile(file, length, true); } /** * Create an empty file, and optionally fill with 0s, and return the {@link FileChannel} * * @param file to create * @param length of the file to create * @param fillWithZeros to the length of the file to force allocation. * @return {@link java.nio.channels.FileChannel} for the file */ public static FileChannel createEmptyFile(final File file, final long length, final boolean fillWithZeros) { ensureDirectoryExists(file.getParentFile(), file.getParent()); FileChannel templateFile = null; try { final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); randomAccessFile.setLength(length); templateFile = randomAccessFile.getChannel(); if (fillWithZeros) { fill(templateFile, 0, length, (byte)0); } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return templateFile; } /** * Check that file exists, open file, and return MappedByteBuffer for entire file * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to map * @param descriptionLabel to be associated for any exceptions * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapExistingFile(final File location, final String descriptionLabel) { checkFileExists(location, descriptionLabel); MappedByteBuffer mappedByteBuffer = null; try (RandomAccessFile file = new RandomAccessFile(location, "rw"); FileChannel channel = file.getChannel()) { mappedByteBuffer = channel.map(READ_WRITE, 0, channel.size()); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Check that file exists, open file, and return MappedByteBuffer for only region specified * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to map * @param descriptionLabel to be associated for an exceptions * @param offset offset to start mapping at * @param length length to map region * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapExistingFile( final File location, final String descriptionLabel, final long offset, final long length) { checkFileExists(location, descriptionLabel); MappedByteBuffer mappedByteBuffer = null; try (RandomAccessFile file = new RandomAccessFile(location, "rw"); FileChannel channel = file.getChannel()) { mappedByteBuffer = channel.map(READ_WRITE, offset, length); } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Create a new file, fill with 0s, and return a {@link java.nio.MappedByteBuffer} for the file. * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to create and map * @param length of the file to create and map * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapNewFile(final File location, final long length) { return mapNewFile(location, length, true); } /** * Create a new file, and optionally fill with 0s, and return a {@link java.nio.MappedByteBuffer} for the file. * <p> * The file itself will be closed, but the mapping will persist. * * @param location of the file to create and map * @param length of the file to create and map * @param fillWithZeros to force allocation. * @return {@link java.nio.MappedByteBuffer} for the file */ public static MappedByteBuffer mapNewFile(final File location, final long length, final boolean fillWithZeros) { MappedByteBuffer mappedByteBuffer = null; try (FileChannel channel = FileChannel.open(location.toPath(), CREATE_NEW, READ, WRITE)) { mappedByteBuffer = channel.map(READ_WRITE, 0, length); if (fillWithZeros) { int pos = 0; while (pos < length) { mappedByteBuffer.put(pos, (byte)0); pos += BLOCK_SIZE; } } } catch (final IOException ex) { LangUtil.rethrowUnchecked(ex); } return mappedByteBuffer; } /** * Check that a file exists and throw an exception if not. * * @param file to check existence of. * @param name to associate for the exception */ public static void checkFileExists(final File file, final String name) { if (!file.exists()) { final String msg = "Missing file for " + name + " : " + file.getAbsolutePath(); throw new IllegalStateException(msg); } } /** * Unmap a {@link MappedByteBuffer} without waiting for the next GC cycle. * * @param buffer to be unmapped. */ public static void unmap(final MappedByteBuffer buffer) { if (null != buffer) { try { UNMAP_BUFFER.invoke(null, buffer); } catch (final Exception ex) { LangUtil.rethrowUnchecked(ex); } } } /** * Map a range of a file and return the address at which the range begins. * * @param fileChannel to be mapped. * @param mode for the mapped region. * @param offset within the file the mapped region should start. * @param length of the mapped region. * @return the address at which the mapping starts. */ public static long map( final FileChannel fileChannel, final FileChannel.MapMode mode, final long offset, final long length) { try { return (long)MAP_ADDRESS.invoke(fileChannel, getMode(mode), offset, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } return 0; } /** * Unmap a region of a file. * * @param fileChannel which has been mapped. * @param address at which the mapping begins. * @param length of the mapped region. */ public static void unmap(final FileChannel fileChannel, final long address, final long length) { try { UNMAP_ADDRESS.invoke(fileChannel, address, length); } catch (final IllegalAccessException | InvocationTargetException ex) { LangUtil.rethrowUnchecked(ex); } } /** * Unmap a {@link ByteBuffer} without waiting for the next GC cycle if its memory mapped. * * @param buffer to be unmapped. */ public static void unmap(final ByteBuffer buffer) { if (buffer instanceof MappedByteBuffer) { unmap((MappedByteBuffer)buffer); } } /** * Return the system property for java.io.tmpdir ensuring a {@link File#separator} is at the end. * * @return tmp directory for the runtime */ public static String tmpDirName() { String tmpDirName = System.getProperty("java.io.tmpdir"); if (!tmpDirName.endsWith(File.separator)) { tmpDirName += File.separator; } return tmpDirName; } private static Method getFileChannelMethod(final String name, final Class<?>... parameterTypes) { Method method = null; try { method = FileChannelImpl.class.getDeclaredMethod(name, parameterTypes); method.setAccessible(true); } catch (final NoSuchMethodException ex) { LangUtil.rethrowUnchecked(ex); } return method; } private static int getMode(final FileChannel.MapMode mode) { if (mode == READ_ONLY) { return MAP_READ_ONLY; } else if (mode == READ_WRITE) { return MAP_READ_WRITE; } else { return MAP_PRIVATE; } } }
[Java] Fix build under Java 10.
agrona/src/main/java/org/agrona/IoUtil.java
[Java] Fix build under Java 10.
Java
apache-2.0
c253cb7704c92ac6797608b1342a75ab88c35e91
0
vineetgarg02/hive,vineetgarg02/hive,lirui-apache/hive,alanfgates/hive,vineetgarg02/hive,jcamachor/hive,sankarh/hive,sankarh/hive,vergilchiu/hive,lirui-apache/hive,jcamachor/hive,alanfgates/hive,b-slim/hive,lirui-apache/hive,lirui-apache/hive,vineetgarg02/hive,vergilchiu/hive,alanfgates/hive,jcamachor/hive,anishek/hive,nishantmonu51/hive,sankarh/hive,anishek/hive,b-slim/hive,nishantmonu51/hive,vergilchiu/hive,anishek/hive,sankarh/hive,b-slim/hive,b-slim/hive,anishek/hive,vergilchiu/hive,sankarh/hive,alanfgates/hive,vergilchiu/hive,nishantmonu51/hive,alanfgates/hive,sankarh/hive,jcamachor/hive,vergilchiu/hive,lirui-apache/hive,nishantmonu51/hive,vergilchiu/hive,lirui-apache/hive,jcamachor/hive,nishantmonu51/hive,b-slim/hive,alanfgates/hive,nishantmonu51/hive,nishantmonu51/hive,sankarh/hive,b-slim/hive,anishek/hive,nishantmonu51/hive,anishek/hive,jcamachor/hive,lirui-apache/hive,alanfgates/hive,anishek/hive,b-slim/hive,vineetgarg02/hive,alanfgates/hive,vineetgarg02/hive,sankarh/hive,b-slim/hive,b-slim/hive,alanfgates/hive,vergilchiu/hive,lirui-apache/hive,jcamachor/hive,vineetgarg02/hive,vineetgarg02/hive,vineetgarg02/hive,lirui-apache/hive,vergilchiu/hive,jcamachor/hive,sankarh/hive,jcamachor/hive,anishek/hive,nishantmonu51/hive,anishek/hive
/** * 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.hive.ql.exec; import java.io.IOException; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; 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.Enumeration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.common.JavaUtils; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.MapRedStats; import org.apache.hadoop.hive.ql.exec.Operator.ProgressCounter; import org.apache.hadoop.hive.ql.exec.errors.ErrorAndSolution; import org.apache.hadoop.hive.ql.exec.errors.TaskLogProcessor; import org.apache.hadoop.hive.ql.history.HiveHistory.Keys; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.hadoop.hive.ql.stats.ClientStatsPublisher; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.mapred.TaskCompletionEvent; import org.apache.hadoop.mapred.TaskReport; import org.apache.hadoop.mapred.Counters.Counter; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.LogManager; public class HadoopJobExecHelper { static final private Log LOG = LogFactory.getLog(HadoopJobExecHelper.class.getName()); protected transient JobConf job; protected Task<? extends Serializable> task; protected transient int mapProgress = 0; protected transient int reduceProgress = 0; public transient String jobId; private LogHelper console; private HadoopJobExecHook callBackObj; /** * Update counters relevant to this task. */ private void updateCounters(Counters ctrs, RunningJob rj) throws IOException { mapProgress = Math.round(rj.mapProgress() * 100); reduceProgress = Math.round(rj.reduceProgress() * 100); task.taskCounters.put("CNTR_NAME_" + task.getId() + "_MAP_PROGRESS", Long.valueOf(mapProgress)); task.taskCounters.put("CNTR_NAME_" + task.getId() + "_REDUCE_PROGRESS", Long.valueOf(reduceProgress)); if (ctrs == null) { // hadoop might return null if it cannot locate the job. // we may still be able to retrieve the job status - so ignore return; } if(callBackObj != null) { callBackObj.updateCounters(ctrs, rj); } } /** * This msg pattern is used to track when a job is started. * * @param jobId * @return */ private static String getJobStartMsg(String jobId) { return "Starting Job = " + jobId; } /** * this msg pattern is used to track when a job is successfully done. * * @param jobId * @return */ public static String getJobEndMsg(String jobId) { return "Ended Job = " + jobId; } private String getTaskAttemptLogUrl(String taskTrackerHttpAddress, String taskAttemptId) { return taskTrackerHttpAddress + "/tasklog?taskid=" + taskAttemptId + "&all=true"; } public boolean mapStarted() { return mapProgress > 0; } public boolean reduceStarted() { return reduceProgress > 0; } public boolean mapDone() { return mapProgress == 100; } public boolean reduceDone() { return reduceProgress == 100; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public HadoopJobExecHelper() { } public HadoopJobExecHelper(JobConf job, LogHelper console, Task<? extends Serializable> task, HadoopJobExecHook hookCallBack) { this.job = job; this.console = console; this.task = task; this.callBackObj = hookCallBack; } /** * A list of the currently running jobs spawned in this Hive instance that is used to kill all * running jobs in the event of an unexpected shutdown - i.e., the JVM shuts down while there are * still jobs running. */ public static Map<String, String> runningJobKillURIs = Collections .synchronizedMap(new HashMap<String, String>()); /** * In Hive, when the user control-c's the command line, any running jobs spawned from that command * line are best-effort killed. * * This static constructor registers a shutdown thread to iterate over all the running job kill * URLs and do a get on them. * */ static { if (new org.apache.hadoop.conf.Configuration() .getBoolean("webinterface.private.actions", false)) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { killRunningJobs(); } }); } } public static void killRunningJobs() { synchronized (runningJobKillURIs) { for (String uri : runningJobKillURIs.values()) { try { System.err.println("killing job with: " + uri); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) new java.net.URL(uri) .openConnection(); conn.setRequestMethod("POST"); int retCode = conn.getResponseCode(); if (retCode != 200) { System.err.println("Got an error trying to kill job with URI: " + uri + " = " + retCode); } } catch (Exception e) { System.err.println("trying to kill job, caught: " + e); // do nothing } } } } public boolean checkFatalErrors(Counters ctrs, StringBuilder errMsg) { if (ctrs == null) { // hadoop might return null if it cannot locate the job. // we may still be able to retrieve the job status - so ignore return false; } // check for number of created files long numFiles = ctrs.getCounter(ProgressCounter.CREATED_FILES); long upperLimit = HiveConf.getLongVar(job, HiveConf.ConfVars.MAXCREATEDFILES); if (numFiles > upperLimit) { errMsg.append("total number of created files now is " + numFiles + ", which exceeds ").append(upperLimit); return true; } return this.callBackObj.checkFatalErrors(ctrs, errMsg); } private MapRedStats progress(ExecDriverTaskHandle th) throws IOException { JobClient jc = th.getJobClient(); RunningJob rj = th.getRunningJob(); String lastReport = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); //DecimalFormat longFormatter = new DecimalFormat("###,###"); long reportTime = System.currentTimeMillis(); long maxReportInterval = 60 * 1000; // One minute boolean fatal = false; StringBuilder errMsg = new StringBuilder(); long pullInterval = HiveConf.getLongVar(job, HiveConf.ConfVars.HIVECOUNTERSPULLINTERVAL); boolean initializing = true; boolean initOutputPrinted = false; long cpuMsec = -1; int numMap = -1; int numReduce = -1; List<ClientStatsPublisher> clientStatPublishers = getClientStatPublishers(); while (!rj.isComplete()) { try { Thread.sleep(pullInterval); } catch (InterruptedException e) { } if (initializing && ShimLoader.getHadoopShims().isJobPreparing(rj)) { // No reason to poll untill the job is initialized continue; } else { // By now the job is initialized so no reason to do // rj.getJobState() again and we do not want to do an extra RPC call initializing = false; } if (!initOutputPrinted) { SessionState ss = SessionState.get(); String logMapper; String logReducer; TaskReport[] mappers = jc.getMapTaskReports(rj.getJobID()); if (mappers == null) { logMapper = "no information for number of mappers; "; } else { numMap = mappers.length; if (ss != null) { ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_NUM_MAPPERS, Integer.toString(numMap)); } logMapper = "number of mappers: " + numMap + "; "; } TaskReport[] reducers = jc.getReduceTaskReports(rj.getJobID()); if (reducers == null) { logReducer = "no information for number of reducers. "; } else { numReduce = reducers.length; if (ss != null) { ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_NUM_REDUCERS, Integer.toString(numReduce)); } logReducer = "number of reducers: " + numReduce; } console .printInfo("Hadoop job information for " + getId() + ": " + logMapper + logReducer); initOutputPrinted = true; } RunningJob newRj = jc.getJob(rj.getJobID()); if (newRj == null) { // under exceptional load, hadoop may not be able to look up status // of finished jobs (because it has purged them from memory). From // hive's perspective - it's equivalent to the job having failed. // So raise a meaningful exception throw new IOException("Could not find status of job: + rj.getJobID()"); } else { th.setRunningJob(newRj); rj = newRj; } // If fatal errors happen we should kill the job immediately rather than // let the job retry several times, which eventually lead to failure. if (fatal) { continue; // wait until rj.isComplete } Counters ctrs = th.getCounters(); if (fatal = checkFatalErrors(ctrs, errMsg)) { console.printError("[Fatal Error] " + errMsg.toString() + ". Killing the job."); rj.killJob(); continue; } errMsg.setLength(0); updateCounters(ctrs, rj); // Prepare data for Client Stat Publishers (if any present) and execute them if (clientStatPublishers.size() > 0 && ctrs != null) { Map<String, Double> exctractedCounters = extractAllCounterValues(ctrs); for (ClientStatsPublisher clientStatPublisher : clientStatPublishers) { try { clientStatPublisher.run(exctractedCounters, rj.getID().toString()); } catch (RuntimeException runtimeException) { LOG.error("Exception " + runtimeException.getClass().getCanonicalName() + " thrown when running clientStatsPublishers. The stack trace is: ", runtimeException); } } } String report = " " + getId() + " map = " + mapProgress + "%, reduce = " + reduceProgress + "%"; if (!report.equals(lastReport) || System.currentTimeMillis() >= reportTime + maxReportInterval) { // find out CPU msecs // In the case that we can't find out this number, we just skip the step to print // it out. if (ctrs != null) { Counter counterCpuMsec = ctrs.findCounter("org.apache.hadoop.mapred.Task$Counter", "CPU_MILLISECONDS"); if (counterCpuMsec != null) { long newCpuMSec = counterCpuMsec.getValue(); if (newCpuMSec > 0) { cpuMsec = newCpuMSec; report += ", Cumulative CPU " + (cpuMsec / 1000D) + " sec"; } } } // write out serialized plan with counters to log file // LOG.info(queryPlan); String output = dateFormat.format(Calendar.getInstance().getTime()) + report; SessionState ss = SessionState.get(); if (ss != null) { ss.getHiveHistory().setTaskCounters(SessionState.get().getQueryId(), getId(), ctrs); ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_PROGRESS, output); ss.getHiveHistory().progressTask(SessionState.get().getQueryId(), this.task); this.callBackObj.logPlanProgress(ss); } console.printInfo(output); lastReport = report; reportTime = System.currentTimeMillis(); } } if (cpuMsec > 0) { console.printInfo("MapReduce Total cumulative CPU time: " + Utilities.formatMsecToStr(cpuMsec)); } boolean success; Counters ctrs = th.getCounters(); if (fatal) { success = false; } else { // check for fatal error again in case it occurred after // the last check before the job is completed if (checkFatalErrors(ctrs, errMsg)) { console.printError("[Fatal Error] " + errMsg.toString()); success = false; } else { success = rj.isSuccessful(); } } if (ctrs != null) { Counter counterCpuMsec = ctrs.findCounter("org.apache.hadoop.mapred.Task$Counter", "CPU_MILLISECONDS"); if (counterCpuMsec != null) { long newCpuMSec = counterCpuMsec.getValue(); if (newCpuMSec > cpuMsec) { cpuMsec = newCpuMSec; } } } MapRedStats mapRedStats = new MapRedStats(numMap, numReduce, cpuMsec, success, rj.getID().toString()); mapRedStats.setCounters(ctrs); this.task.setDone(); // update based on the final value of the counters updateCounters(ctrs, rj); SessionState ss = SessionState.get(); if (ss != null) { this.callBackObj.logPlanProgress(ss); } // LOG.info(queryPlan); return mapRedStats; } private String getId() { return this.task.getId(); } /** * from StreamJob.java. */ public void jobInfo(RunningJob rj) { if (job.get("mapred.job.tracker", "local").equals("local")) { console.printInfo("Job running in-process (local Hadoop)"); } else { String hp = job.get("mapred.job.tracker"); if (SessionState.get() != null) { SessionState.get().getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_ID, rj.getJobID()); } console.printInfo(getJobStartMsg(rj.getJobID()) + ", Tracking URL = " + rj.getTrackingURL()); console.printInfo("Kill Command = " + HiveConf.getVar(job, HiveConf.ConfVars.HADOOPBIN) + " job -Dmapred.job.tracker=" + hp + " -kill " + rj.getJobID()); } } /** * This class contains the state of the running task Going forward, we will return this handle * from execute and Driver can split execute into start, monitorProgess and postProcess. */ private static class ExecDriverTaskHandle extends TaskHandle { JobClient jc; RunningJob rj; JobClient getJobClient() { return jc; } RunningJob getRunningJob() { return rj; } public ExecDriverTaskHandle(JobClient jc, RunningJob rj) { this.jc = jc; this.rj = rj; } public void setRunningJob(RunningJob job) { rj = job; } @Override public Counters getCounters() throws IOException { return rj.getCounters(); } } // Used for showJobFailDebugInfo private static class TaskInfo { String jobId; HashSet<String> logUrls; public TaskInfo(String jobId) { this.jobId = jobId; logUrls = new HashSet<String>(); } public void addLogUrl(String logUrl) { logUrls.add(logUrl); } public HashSet<String> getLogUrls() { return logUrls; } public String getJobId() { return jobId; } } @SuppressWarnings("deprecation") private void showJobFailDebugInfo(JobConf conf, RunningJob rj) throws IOException { // Mapping from task ID to the number of failures Map<String, Integer> failures = new HashMap<String, Integer>(); // Successful task ID's Set<String> successes = new HashSet<String>(); Map<String, TaskInfo> taskIdToInfo = new HashMap<String, TaskInfo>(); int startIndex = 0; console.printError("Error during job, obtaining debugging information..."); // Loop to get all task completion events because getTaskCompletionEvents // only returns a subset per call while (true) { TaskCompletionEvent[] taskCompletions = rj.getTaskCompletionEvents(startIndex); if (taskCompletions == null || taskCompletions.length == 0) { break; } boolean more = true; for (TaskCompletionEvent t : taskCompletions) { // getTaskJobIDs returns Strings for compatibility with Hadoop versions // without TaskID or TaskAttemptID String[] taskJobIds = ShimLoader.getHadoopShims().getTaskJobIDs(t); if (taskJobIds == null) { console.printError("Task attempt info is unavailable in this Hadoop version"); more = false; break; } // For each task completion event, get the associated task id, job id // and the logs String taskId = taskJobIds[0]; String jobId = taskJobIds[1]; console.printError("Examining task ID: " + taskId + " from job " + jobId); TaskInfo ti = taskIdToInfo.get(taskId); if (ti == null) { ti = new TaskInfo(jobId); taskIdToInfo.put(taskId, ti); } // These tasks should have come from the same job. assert (ti.getJobId() != null && ti.getJobId().equals(jobId)); ti.getLogUrls().add(getTaskAttemptLogUrl(t.getTaskTrackerHttp(), t.getTaskId())); // If a task failed, then keep track of the total number of failures // for that task (typically, a task gets re-run up to 4 times if it // fails if (t.getTaskStatus() != TaskCompletionEvent.Status.SUCCEEDED) { Integer failAttempts = failures.get(taskId); if (failAttempts == null) { failAttempts = Integer.valueOf(0); } failAttempts = Integer.valueOf(failAttempts.intValue() + 1); failures.put(taskId, failAttempts); } else { successes.add(taskId); } } if (!more) { break; } startIndex += taskCompletions.length; } // Remove failures for tasks that succeeded for (String task : successes) { failures.remove(task); } if (failures.keySet().size() == 0) { return; } // Find the highest failure count int maxFailures = 0; for (Integer failCount : failures.values()) { if (maxFailures < failCount.intValue()) { maxFailures = failCount.intValue(); } } // Display Error Message for tasks with the highest failure count String jtUrl = JobTrackerURLResolver.getURL(conf); for (String task : failures.keySet()) { if (failures.get(task).intValue() == maxFailures) { TaskInfo ti = taskIdToInfo.get(task); String jobId = ti.getJobId(); String taskUrl = jtUrl + "/taskdetails.jsp?jobid=" + jobId + "&tipid=" + task.toString(); TaskLogProcessor tlp = new TaskLogProcessor(conf); for (String logUrl : ti.getLogUrls()) { tlp.addTaskAttemptLogUrl(logUrl); } List<ErrorAndSolution> errors = tlp.getErrors(); StringBuilder sb = new StringBuilder(); // We use a StringBuilder and then call printError only once as // printError will write to both stderr and the error log file. In // situations where both the stderr and the log file output is // simultaneously output to a single stream, this will look cleaner. sb.append("\n"); sb.append("Task with the most failures(" + maxFailures + "): \n"); sb.append("-----\n"); sb.append("Task ID:\n " + task + "\n\n"); sb.append("URL:\n " + taskUrl + "\n"); for (ErrorAndSolution e : errors) { sb.append("\n"); sb.append("Possible error:\n " + e.getError() + "\n\n"); sb.append("Solution:\n " + e.getSolution() + "\n"); } sb.append("-----\n"); console.printError(sb.toString()); // Only print out one task because that's good enough for debugging. break; } } return; } public void localJobDebugger(int exitVal, String taskId) { StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Task failed!\n"); sb.append("Task ID:\n " + taskId + "\n\n"); sb.append("Logs:\n"); console.printError(sb.toString()); for (Appender a : Collections.list((Enumeration<Appender>) LogManager.getRootLogger().getAllAppenders())) { if (a instanceof FileAppender) { console.printError(((FileAppender)a).getFile()); } } } public int progressLocal(Process runningJob, String taskId) { int exitVal = -101; try { exitVal = runningJob.waitFor(); //TODO: poll periodically } catch (InterruptedException e) { } if (exitVal != 0) { console.printError("Execution failed with exit status: " + exitVal); console.printError("Obtaining error information"); if (HiveConf.getBoolVar(job, HiveConf.ConfVars.SHOW_JOB_FAIL_DEBUG_INFO)) { // Since local jobs are run sequentially, all relevant information is already available // Therefore, no need to fetch job debug info asynchronously localJobDebugger(exitVal, taskId); } } else { console.printInfo("Execution completed successfully"); console.printInfo("Mapred Local Task Succeeded . Convert the Join into MapJoin"); } return exitVal; } public int progress(RunningJob rj, JobClient jc) throws IOException { jobId = rj.getJobID(); int returnVal = 0; // remove the pwd from conf file so that job tracker doesn't show this // logs String pwd = HiveConf.getVar(job, HiveConf.ConfVars.METASTOREPWD); if (pwd != null) { HiveConf.setVar(job, HiveConf.ConfVars.METASTOREPWD, "HIVE"); } // replace it back if (pwd != null) { HiveConf.setVar(job, HiveConf.ConfVars.METASTOREPWD, pwd); } // add to list of running jobs to kill in case of abnormal shutdown runningJobKillURIs.put(rj.getJobID(), rj.getTrackingURL() + "&action=kill"); ExecDriverTaskHandle th = new ExecDriverTaskHandle(jc, rj); jobInfo(rj); MapRedStats mapRedStats = progress(th); // Not always there is a SessionState. Sometimes ExeDriver is directly invoked // for special modes. In that case, SessionState.get() is empty. if (SessionState.get() != null) { SessionState.get().getLastMapRedStatsList().add(mapRedStats); } boolean success = mapRedStats.isSuccess(); String statusMesg = getJobEndMsg(rj.getJobID()); if (!success) { statusMesg += " with errors"; returnVal = 2; console.printError(statusMesg); if (HiveConf.getBoolVar(job, HiveConf.ConfVars.SHOW_JOB_FAIL_DEBUG_INFO)) { try { JobDebugger jd = new JobDebugger(job, rj, console); Thread t = new Thread(jd); t.start(); t.join(HiveConf.getIntVar(job, HiveConf.ConfVars.JOB_DEBUG_TIMEOUT)); } catch (InterruptedException e) { console.printError("Timed out trying to grab more detailed job failure" + " information, please check jobtracker for more info"); } } } else { console.printInfo(statusMesg); } return returnVal; } private Map<String, Double> extractAllCounterValues(Counters counters) { Map<String, Double> exctractedCounters = new HashMap<String, Double>(); for (Counters.Group cg : counters) { for (Counter c : cg) { exctractedCounters.put(cg.getName() + "::" + c.getName(), new Double(c.getCounter())); } } return exctractedCounters; } private List<ClientStatsPublisher> getClientStatPublishers() { List<ClientStatsPublisher> clientStatsPublishers = new ArrayList<ClientStatsPublisher>(); String confString = HiveConf.getVar(job, HiveConf.ConfVars.CLIENTSTATSPUBLISHERS); confString = confString.trim(); if (confString.equals("")) { return clientStatsPublishers; } String[] clientStatsPublisherClasses = confString.split(","); for (String clientStatsPublisherClass : clientStatsPublisherClasses) { try { clientStatsPublishers.add((ClientStatsPublisher) Class.forName( clientStatsPublisherClass.trim(), true, JavaUtils.getClassLoader()).newInstance()); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.warn(e.getClass().getName() + " occured when trying to create class: " + clientStatsPublisherClass.trim() + " implementing ClientStatsPublisher interface"); LOG.warn("The exception message is: " + e.getMessage()); LOG.warn("Program will continue, but without this ClientStatsPublisher working"); } } return clientStatsPublishers; } }
ql/src/java/org/apache/hadoop/hive/ql/exec/HadoopJobExecHelper.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.hive.ql.exec; import java.io.IOException; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; 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.Enumeration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.common.JavaUtils; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.MapRedStats; import org.apache.hadoop.hive.ql.exec.Operator.ProgressCounter; import org.apache.hadoop.hive.ql.exec.errors.ErrorAndSolution; import org.apache.hadoop.hive.ql.exec.errors.TaskLogProcessor; import org.apache.hadoop.hive.ql.history.HiveHistory.Keys; import org.apache.hadoop.hive.ql.session.SessionState; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.hadoop.hive.ql.stats.ClientStatsPublisher; import org.apache.hadoop.hive.shims.ShimLoader; import org.apache.hadoop.mapred.Counters; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.RunningJob; import org.apache.hadoop.mapred.TaskCompletionEvent; import org.apache.hadoop.mapred.TaskReport; import org.apache.hadoop.mapred.Counters.Counter; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.LogManager; public class HadoopJobExecHelper { static final private Log LOG = LogFactory.getLog(HadoopJobExecHelper.class.getName()); protected transient JobConf job; protected Task<? extends Serializable> task; protected transient int mapProgress = 0; protected transient int reduceProgress = 0; public transient String jobId; private LogHelper console; private HadoopJobExecHook callBackObj; /** * Update counters relevant to this task. */ private void updateCounters(Counters ctrs, RunningJob rj) throws IOException { mapProgress = Math.round(rj.mapProgress() * 100); reduceProgress = Math.round(rj.reduceProgress() * 100); task.taskCounters.put("CNTR_NAME_" + task.getId() + "_MAP_PROGRESS", Long.valueOf(mapProgress)); task.taskCounters.put("CNTR_NAME_" + task.getId() + "_REDUCE_PROGRESS", Long.valueOf(reduceProgress)); if (ctrs == null) { // hadoop might return null if it cannot locate the job. // we may still be able to retrieve the job status - so ignore return; } if(callBackObj != null) { callBackObj.updateCounters(ctrs, rj); } } /** * This msg pattern is used to track when a job is started. * * @param jobId * @return */ private static String getJobStartMsg(String jobId) { return "Starting Job = " + jobId; } /** * this msg pattern is used to track when a job is successfully done. * * @param jobId * @return */ public static String getJobEndMsg(String jobId) { return "Ended Job = " + jobId; } private String getTaskAttemptLogUrl(String taskTrackerHttpAddress, String taskAttemptId) { return taskTrackerHttpAddress + "/tasklog?taskid=" + taskAttemptId + "&all=true"; } public boolean mapStarted() { return mapProgress > 0; } public boolean reduceStarted() { return reduceProgress > 0; } public boolean mapDone() { return mapProgress == 100; } public boolean reduceDone() { return reduceProgress == 100; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public HadoopJobExecHelper() { } public HadoopJobExecHelper(JobConf job, LogHelper console, Task<? extends Serializable> task, HadoopJobExecHook hookCallBack) { this.job = job; this.console = console; this.task = task; this.callBackObj = hookCallBack; } /** * A list of the currently running jobs spawned in this Hive instance that is used to kill all * running jobs in the event of an unexpected shutdown - i.e., the JVM shuts down while there are * still jobs running. */ public static Map<String, String> runningJobKillURIs = Collections .synchronizedMap(new HashMap<String, String>()); /** * In Hive, when the user control-c's the command line, any running jobs spawned from that command * line are best-effort killed. * * This static constructor registers a shutdown thread to iterate over all the running job kill * URLs and do a get on them. * */ static { if (new org.apache.hadoop.conf.Configuration() .getBoolean("webinterface.private.actions", false)) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { killRunningJobs(); } }); } } public static void killRunningJobs() { synchronized (runningJobKillURIs) { for (String uri : runningJobKillURIs.values()) { try { System.err.println("killing job with: " + uri); java.net.HttpURLConnection conn = (java.net.HttpURLConnection) new java.net.URL(uri) .openConnection(); conn.setRequestMethod("POST"); int retCode = conn.getResponseCode(); if (retCode != 200) { System.err.println("Got an error trying to kill job with URI: " + uri + " = " + retCode); } } catch (Exception e) { System.err.println("trying to kill job, caught: " + e); // do nothing } } } } public boolean checkFatalErrors(Counters ctrs, StringBuilder errMsg) { if (ctrs == null) { // hadoop might return null if it cannot locate the job. // we may still be able to retrieve the job status - so ignore return false; } // check for number of created files long numFiles = ctrs.getCounter(ProgressCounter.CREATED_FILES); long upperLimit = HiveConf.getLongVar(job, HiveConf.ConfVars.MAXCREATEDFILES); if (numFiles > upperLimit) { errMsg.append("total number of created files now is " + numFiles + ", which exceeds ").append(upperLimit); return true; } return this.callBackObj.checkFatalErrors(ctrs, errMsg); } private MapRedStats progress(ExecDriverTaskHandle th) throws IOException { JobClient jc = th.getJobClient(); RunningJob rj = th.getRunningJob(); String lastReport = ""; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"); //DecimalFormat longFormatter = new DecimalFormat("###,###"); long reportTime = System.currentTimeMillis(); long maxReportInterval = 60 * 1000; // One minute boolean fatal = false; StringBuilder errMsg = new StringBuilder(); long pullInterval = HiveConf.getLongVar(job, HiveConf.ConfVars.HIVECOUNTERSPULLINTERVAL); boolean initializing = true; boolean initOutputPrinted = false; long cpuMsec = -1; int numMap = -1; int numReduce = -1; List<ClientStatsPublisher> clientStatPublishers = getClientStatPublishers(); while (!rj.isComplete()) { try { Thread.sleep(pullInterval); } catch (InterruptedException e) { } if (initializing && ShimLoader.getHadoopShims().isJobPreparing(rj)) { // No reason to poll untill the job is initialized continue; } else { // By now the job is initialized so no reason to do // rj.getJobState() again and we do not want to do an extra RPC call initializing = false; } if (!initOutputPrinted) { SessionState ss = SessionState.get(); String logMapper; String logReducer; TaskReport[] mappers = jc.getMapTaskReports(rj.getJobID()); if (mappers == null) { logMapper = "no information for number of mappers; "; } else { numMap = mappers.length; if (ss != null) { ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_NUM_MAPPERS, Integer.toString(numMap)); } logMapper = "number of mappers: " + numMap + "; "; } TaskReport[] reducers = jc.getReduceTaskReports(rj.getJobID()); if (reducers == null) { logReducer = "no information for number of reducers. "; } else { numReduce = reducers.length; if (ss != null) { ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_NUM_REDUCERS, Integer.toString(numReduce)); } logReducer = "number of reducers: " + numReduce; } console .printInfo("Hadoop job information for " + getId() + ": " + logMapper + logReducer); initOutputPrinted = true; } RunningJob newRj = jc.getJob(rj.getJobID()); if (newRj == null) { // under exceptional load, hadoop may not be able to look up status // of finished jobs (because it has purged them from memory). From // hive's perspective - it's equivalent to the job having failed. // So raise a meaningful exception throw new IOException("Could not find status of job: + rj.getJobID()"); } else { th.setRunningJob(newRj); rj = newRj; } // If fatal errors happen we should kill the job immediately rather than // let the job retry several times, which eventually lead to failure. if (fatal) { continue; // wait until rj.isComplete } Counters ctrs = th.getCounters(); if (fatal = checkFatalErrors(ctrs, errMsg)) { console.printError("[Fatal Error] " + errMsg.toString() + ". Killing the job."); rj.killJob(); continue; } errMsg.setLength(0); updateCounters(ctrs, rj); String report = " " + getId() + " map = " + mapProgress + "%, reduce = " + reduceProgress + "%"; if (!report.equals(lastReport) || System.currentTimeMillis() >= reportTime + maxReportInterval) { // find out CPU msecs // In the case that we can't find out this number, we just skip the step to print // it out. if (ctrs != null) { Counter counterCpuMsec = ctrs.findCounter("org.apache.hadoop.mapred.Task$Counter", "CPU_MILLISECONDS"); if (counterCpuMsec != null) { long newCpuMSec = counterCpuMsec.getValue(); if (newCpuMSec > 0) { cpuMsec = newCpuMSec; report += ", Cumulative CPU " + (cpuMsec / 1000D) + " sec"; } } } // write out serialized plan with counters to log file // LOG.info(queryPlan); String output = dateFormat.format(Calendar.getInstance().getTime()) + report; SessionState ss = SessionState.get(); if (ss != null) { ss.getHiveHistory().setTaskCounters(SessionState.get().getQueryId(), getId(), ctrs); ss.getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_PROGRESS, output); ss.getHiveHistory().progressTask(SessionState.get().getQueryId(), this.task); this.callBackObj.logPlanProgress(ss); } console.printInfo(output); lastReport = report; reportTime = System.currentTimeMillis(); } } if (cpuMsec > 0) { console.printInfo("MapReduce Total cumulative CPU time: " + Utilities.formatMsecToStr(cpuMsec)); } boolean success; Counters ctrs = th.getCounters(); if (fatal) { success = false; } else { // check for fatal error again in case it occurred after // the last check before the job is completed if (checkFatalErrors(ctrs, errMsg)) { console.printError("[Fatal Error] " + errMsg.toString()); success = false; } else { success = rj.isSuccessful(); } } //Prepare data for Client Stat Publishers (if any present) and execute them if (clientStatPublishers.size() > 0 && ctrs != null){ Map<String, Double> exctractedCounters = extractAllCounterValues(ctrs); for(ClientStatsPublisher clientStatPublisher : clientStatPublishers){ clientStatPublisher.run(exctractedCounters, rj.getID().toString()); } } if (ctrs != null) { Counter counterCpuMsec = ctrs.findCounter("org.apache.hadoop.mapred.Task$Counter", "CPU_MILLISECONDS"); if (counterCpuMsec != null) { long newCpuMSec = counterCpuMsec.getValue(); if (newCpuMSec > cpuMsec) { cpuMsec = newCpuMSec; } } } MapRedStats mapRedStats = new MapRedStats(numMap, numReduce, cpuMsec, success, rj.getID().toString()); mapRedStats.setCounters(ctrs); this.task.setDone(); // update based on the final value of the counters updateCounters(ctrs, rj); SessionState ss = SessionState.get(); if (ss != null) { this.callBackObj.logPlanProgress(ss); } // LOG.info(queryPlan); return mapRedStats; } private String getId() { return this.task.getId(); } /** * from StreamJob.java. */ public void jobInfo(RunningJob rj) { if (job.get("mapred.job.tracker", "local").equals("local")) { console.printInfo("Job running in-process (local Hadoop)"); } else { String hp = job.get("mapred.job.tracker"); if (SessionState.get() != null) { SessionState.get().getHiveHistory().setTaskProperty(SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_ID, rj.getJobID()); } console.printInfo(getJobStartMsg(rj.getJobID()) + ", Tracking URL = " + rj.getTrackingURL()); console.printInfo("Kill Command = " + HiveConf.getVar(job, HiveConf.ConfVars.HADOOPBIN) + " job -Dmapred.job.tracker=" + hp + " -kill " + rj.getJobID()); } } /** * This class contains the state of the running task Going forward, we will return this handle * from execute and Driver can split execute into start, monitorProgess and postProcess. */ private static class ExecDriverTaskHandle extends TaskHandle { JobClient jc; RunningJob rj; JobClient getJobClient() { return jc; } RunningJob getRunningJob() { return rj; } public ExecDriverTaskHandle(JobClient jc, RunningJob rj) { this.jc = jc; this.rj = rj; } public void setRunningJob(RunningJob job) { rj = job; } @Override public Counters getCounters() throws IOException { return rj.getCounters(); } } // Used for showJobFailDebugInfo private static class TaskInfo { String jobId; HashSet<String> logUrls; public TaskInfo(String jobId) { this.jobId = jobId; logUrls = new HashSet<String>(); } public void addLogUrl(String logUrl) { logUrls.add(logUrl); } public HashSet<String> getLogUrls() { return logUrls; } public String getJobId() { return jobId; } } @SuppressWarnings("deprecation") private void showJobFailDebugInfo(JobConf conf, RunningJob rj) throws IOException { // Mapping from task ID to the number of failures Map<String, Integer> failures = new HashMap<String, Integer>(); // Successful task ID's Set<String> successes = new HashSet<String>(); Map<String, TaskInfo> taskIdToInfo = new HashMap<String, TaskInfo>(); int startIndex = 0; console.printError("Error during job, obtaining debugging information..."); // Loop to get all task completion events because getTaskCompletionEvents // only returns a subset per call while (true) { TaskCompletionEvent[] taskCompletions = rj.getTaskCompletionEvents(startIndex); if (taskCompletions == null || taskCompletions.length == 0) { break; } boolean more = true; for (TaskCompletionEvent t : taskCompletions) { // getTaskJobIDs returns Strings for compatibility with Hadoop versions // without TaskID or TaskAttemptID String[] taskJobIds = ShimLoader.getHadoopShims().getTaskJobIDs(t); if (taskJobIds == null) { console.printError("Task attempt info is unavailable in this Hadoop version"); more = false; break; } // For each task completion event, get the associated task id, job id // and the logs String taskId = taskJobIds[0]; String jobId = taskJobIds[1]; console.printError("Examining task ID: " + taskId + " from job " + jobId); TaskInfo ti = taskIdToInfo.get(taskId); if (ti == null) { ti = new TaskInfo(jobId); taskIdToInfo.put(taskId, ti); } // These tasks should have come from the same job. assert (ti.getJobId() != null && ti.getJobId().equals(jobId)); ti.getLogUrls().add(getTaskAttemptLogUrl(t.getTaskTrackerHttp(), t.getTaskId())); // If a task failed, then keep track of the total number of failures // for that task (typically, a task gets re-run up to 4 times if it // fails if (t.getTaskStatus() != TaskCompletionEvent.Status.SUCCEEDED) { Integer failAttempts = failures.get(taskId); if (failAttempts == null) { failAttempts = Integer.valueOf(0); } failAttempts = Integer.valueOf(failAttempts.intValue() + 1); failures.put(taskId, failAttempts); } else { successes.add(taskId); } } if (!more) { break; } startIndex += taskCompletions.length; } // Remove failures for tasks that succeeded for (String task : successes) { failures.remove(task); } if (failures.keySet().size() == 0) { return; } // Find the highest failure count int maxFailures = 0; for (Integer failCount : failures.values()) { if (maxFailures < failCount.intValue()) { maxFailures = failCount.intValue(); } } // Display Error Message for tasks with the highest failure count String jtUrl = JobTrackerURLResolver.getURL(conf); for (String task : failures.keySet()) { if (failures.get(task).intValue() == maxFailures) { TaskInfo ti = taskIdToInfo.get(task); String jobId = ti.getJobId(); String taskUrl = jtUrl + "/taskdetails.jsp?jobid=" + jobId + "&tipid=" + task.toString(); TaskLogProcessor tlp = new TaskLogProcessor(conf); for (String logUrl : ti.getLogUrls()) { tlp.addTaskAttemptLogUrl(logUrl); } List<ErrorAndSolution> errors = tlp.getErrors(); StringBuilder sb = new StringBuilder(); // We use a StringBuilder and then call printError only once as // printError will write to both stderr and the error log file. In // situations where both the stderr and the log file output is // simultaneously output to a single stream, this will look cleaner. sb.append("\n"); sb.append("Task with the most failures(" + maxFailures + "): \n"); sb.append("-----\n"); sb.append("Task ID:\n " + task + "\n\n"); sb.append("URL:\n " + taskUrl + "\n"); for (ErrorAndSolution e : errors) { sb.append("\n"); sb.append("Possible error:\n " + e.getError() + "\n\n"); sb.append("Solution:\n " + e.getSolution() + "\n"); } sb.append("-----\n"); console.printError(sb.toString()); // Only print out one task because that's good enough for debugging. break; } } return; } public void localJobDebugger(int exitVal, String taskId) { StringBuilder sb = new StringBuilder(); sb.append("\n"); sb.append("Task failed!\n"); sb.append("Task ID:\n " + taskId + "\n\n"); sb.append("Logs:\n"); console.printError(sb.toString()); for (Appender a : Collections.list((Enumeration<Appender>) LogManager.getRootLogger().getAllAppenders())) { if (a instanceof FileAppender) { console.printError(((FileAppender)a).getFile()); } } } public int progressLocal(Process runningJob, String taskId) { int exitVal = -101; try { exitVal = runningJob.waitFor(); //TODO: poll periodically } catch (InterruptedException e) { } if (exitVal != 0) { console.printError("Execution failed with exit status: " + exitVal); console.printError("Obtaining error information"); if (HiveConf.getBoolVar(job, HiveConf.ConfVars.SHOW_JOB_FAIL_DEBUG_INFO)) { // Since local jobs are run sequentially, all relevant information is already available // Therefore, no need to fetch job debug info asynchronously localJobDebugger(exitVal, taskId); } } else { console.printInfo("Execution completed successfully"); console.printInfo("Mapred Local Task Succeeded . Convert the Join into MapJoin"); } return exitVal; } public int progress(RunningJob rj, JobClient jc) throws IOException { jobId = rj.getJobID(); int returnVal = 0; // remove the pwd from conf file so that job tracker doesn't show this // logs String pwd = HiveConf.getVar(job, HiveConf.ConfVars.METASTOREPWD); if (pwd != null) { HiveConf.setVar(job, HiveConf.ConfVars.METASTOREPWD, "HIVE"); } // replace it back if (pwd != null) { HiveConf.setVar(job, HiveConf.ConfVars.METASTOREPWD, pwd); } // add to list of running jobs to kill in case of abnormal shutdown runningJobKillURIs.put(rj.getJobID(), rj.getTrackingURL() + "&action=kill"); ExecDriverTaskHandle th = new ExecDriverTaskHandle(jc, rj); jobInfo(rj); MapRedStats mapRedStats = progress(th); // Not always there is a SessionState. Sometimes ExeDriver is directly invoked // for special modes. In that case, SessionState.get() is empty. if (SessionState.get() != null) { SessionState.get().getLastMapRedStatsList().add(mapRedStats); } boolean success = mapRedStats.isSuccess(); String statusMesg = getJobEndMsg(rj.getJobID()); if (!success) { statusMesg += " with errors"; returnVal = 2; console.printError(statusMesg); if (HiveConf.getBoolVar(job, HiveConf.ConfVars.SHOW_JOB_FAIL_DEBUG_INFO)) { try { JobDebugger jd = new JobDebugger(job, rj, console); Thread t = new Thread(jd); t.start(); t.join(HiveConf.getIntVar(job, HiveConf.ConfVars.JOB_DEBUG_TIMEOUT)); } catch (InterruptedException e) { console.printError("Timed out trying to grab more detailed job failure" + " information, please check jobtracker for more info"); } } } else { console.printInfo(statusMesg); } return returnVal; } private Map<String, Double> extractAllCounterValues(Counters counters) { Map<String, Double> exctractedCounters = new HashMap<String, Double>(); for (Counters.Group cg : counters) { for (Counter c : cg) { exctractedCounters.put(cg.getName() + "::" + c.getName(), new Double(c.getCounter())); } } return exctractedCounters; } private List<ClientStatsPublisher> getClientStatPublishers() { List<ClientStatsPublisher> clientStatsPublishers = new ArrayList<ClientStatsPublisher>(); String confString = HiveConf.getVar(job, HiveConf.ConfVars.CLIENTSTATSPUBLISHERS); confString = confString.trim(); if (confString.equals("")) { return clientStatsPublishers; } String[] clientStatsPublisherClasses = confString.split(","); for (String clientStatsPublisherClass : clientStatsPublisherClasses) { try { clientStatsPublishers.add((ClientStatsPublisher) Class.forName( clientStatsPublisherClass.trim(), true, JavaUtils.getClassLoader()).newInstance()); } catch (RuntimeException e) { throw e; } catch (Exception e) { LOG.warn(e.getClass().getName() + " occured when trying to create class: " + clientStatsPublisherClass.trim() + " implementing ClientStatsPublisher interface"); LOG.warn("The exception message is: " + e.getMessage()); LOG.warn("Program will continue, but without this ClientStatsPublisher working"); } } return clientStatsPublishers; } }
HIVE-2487: Bug from HIVE-2446, the code that calls client stats publishers should be inside the while loop (Robert Surรณwka via He Yongqiang) git-svn-id: c2303eb81cb646bce052f55f7f0d14f181a5956c@1185767 13f79535-47bb-0310-9956-ffa450edef68
ql/src/java/org/apache/hadoop/hive/ql/exec/HadoopJobExecHelper.java
HIVE-2487: Bug from HIVE-2446, the code that calls client stats publishers should be inside the while loop (Robert Surรณwka via He Yongqiang)
Java
apache-2.0
3e4aadb1180c22caf007604e5a10b7ab608e4bb9
0
anvayarai/my-ChatSecure,joskarthic/chatsecure,bonashen/ChatSecureAndroid,eighthave/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,eighthave/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,prive/prive-android,n8fr8/ChatSecureAndroid,n8fr8/AwesomeApp,n8fr8/AwesomeApp,kden/ChatSecureAndroid,prive/prive-android,joskarthic/chatsecure,ChatSecure/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,Heart2009/ChatSecureAndroid,n8fr8/AwesomeApp,prembasumatary/ChatSecureAndroid,kden/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,joskarthic/chatsecure,maheshwarishivam/ChatSecureAndroid,bonashen/ChatSecureAndroid,guardianproject/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,guardianproject/ChatSecureAndroid,bonashen/ChatSecureAndroid,h2ri/ChatSecureAndroid,10045125/ChatSecureAndroid,n8fr8/ChatSecureAndroid,prive/prive-android,ChatSecure/ChatSecureAndroid,h2ri/ChatSecureAndroid,n8fr8/ChatSecureAndroid,Heart2009/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,guardianproject/ChatSecureAndroid,kden/ChatSecureAndroid,10045125/ChatSecureAndroid,anvayarai/my-ChatSecure,maheshwarishivam/ChatSecureAndroid,Heart2009/ChatSecureAndroid,eighthave/ChatSecureAndroid,prive/prive-android,anvayarai/my-ChatSecure,31H0B1eV/ChatSecureAndroid,h2ri/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,10045125/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid
/* * Copyright (C) 2008 Esmertec AG. Copyright (C) 2008 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 info.guardianproject.otr.app.im.app; import info.guardianproject.cacheword.CacheWordActivityHandler; import info.guardianproject.cacheword.ICacheWordSubscriber; import info.guardianproject.otr.OtrDataHandler; import info.guardianproject.otr.app.im.IChatSession; import info.guardianproject.otr.app.im.IChatSessionManager; import info.guardianproject.otr.app.im.IImConnection; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.otr.app.im.service.ImServiceConstants; import info.guardianproject.util.LogCleaner; import info.guardianproject.util.SystemServices; import info.guardianproject.util.SystemServices.FileInfo; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Iterator; import java.util.List; import java.util.Set; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; public class ImUrlActivity extends ThemeableActivity implements ICacheWordSubscriber { private static final String[] ACCOUNT_PROJECTION = { Imps.Account._ID, Imps.Account.PASSWORD, }; private static final int ACCOUNT_ID_COLUMN = 0; private static final int ACCOUNT_PW_COLUMN = 1; private static final int REQUEST_PICK_CONTACTS = RESULT_FIRST_USER + 1; private String mProviderName; private String mToAddress; private String mFromAddress; private String mHost; private ImApp mApp; private IImConnection mConn; private long mProviderId; private long mAccountId; private IChatSessionManager mChatSessionManager; private String mUrl; private String mType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CacheWordActivityHandler cacheWord = new CacheWordActivityHandler(this, (ICacheWordSubscriber)this); cacheWord.connectToService(); Intent intent = getIntent(); if (Intent.ACTION_SENDTO.equals(intent.getAction())) { if (!resolveIntent(intent)) { finish(); return; } if (TextUtils.isEmpty(mToAddress)) { LogCleaner.warn(ImApp.LOG_TAG, "<ImUrlActivity>Invalid to address"); // finish(); return; } mApp = (ImApp)getApplication(); if (mApp.serviceConnected()) handleIntent(); else { mApp.callWhenServiceConnected(new Handler(), new Runnable() { public void run() { handleIntent(); } }); } } else { finish(); } } void handleIntent() { ContentResolver cr = getContentResolver(); long providerId = Imps.Provider.getProviderIdForName(cr, mProviderName); long accountId; List<IImConnection> listConns = ((ImApp)getApplication()).getActiveConnections(); if (!listConns.isEmpty()) { mConn = listConns.get(0); try { providerId = mConn.getProviderId(); accountId = mConn.getAccountId(); } catch (RemoteException e) { e.printStackTrace(); } } if (mConn == null) { Cursor c = DatabaseUtils.queryAccountsForProvider(cr, ACCOUNT_PROJECTION, providerId); if (c == null) { addAccount(providerId); } else { accountId = c.getLong(ACCOUNT_ID_COLUMN); if (c.isNull(ACCOUNT_PW_COLUMN)) { editAccount(accountId); } else { signInAccount(accountId); } } } else { try { int state = mConn.getState(); accountId = mConn.getAccountId(); if (state < ImConnection.LOGGED_IN) { signInAccount(accountId); } else if (state == ImConnection.LOGGED_IN || state == ImConnection.SUSPENDED) { Uri data = getIntent().getData(); if (data.getScheme().equals("immu")) { this.openMultiUserChat(data); } else if (!isValidToAddress()) { showContactList(accountId); } else { openChat(providerId, accountId); } finish(); } } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w("ImUrlActivity", "Connection disappeared!"); } } } private void addAccount(long providerId) { Intent intent = new Intent(this, AccountActivity.class); intent.setAction(Intent.ACTION_INSERT); intent.setData(ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId)); // intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress); if (mFromAddress != null) intent.putExtra("newuser", mFromAddress + '@' + mHost); startActivity(intent); } private void editAccount(long accountId) { Uri accountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId); Intent intent = new Intent(this, AccountActivity.class); intent.setAction(Intent.ACTION_EDIT); intent.setData(accountUri); intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress); startActivity(intent); } private void signInAccount(long accountId) { editAccount(accountId); // TODO sign in? security implications? } private void showContactList(long accountId) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Imps.Contacts.CONTENT_URI); intent.addCategory(ImApp.IMPS_CATEGORY); intent.putExtra("accountId", accountId); startActivity(intent); } private void openChat(long provider, long account) { try { IChatSessionManager manager = mConn.getChatSessionManager(); IChatSession session = manager.getChatSession(mToAddress); if (session == null) { session = manager.createChatSession(mToAddress); } Uri data = ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, session.getId()); Intent intent = new Intent(Intent.ACTION_VIEW, data); intent.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, mToAddress); intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, provider); intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, account); intent.addCategory(ImApp.IMPS_CATEGORY); startActivity(intent); } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w("ImUrlActivity", "Connection disappeared!"); } } private boolean resolveIntent(Intent intent) { Uri data = intent.getData(); mHost = data.getHost(); if (data.getScheme().equals("immu")) { mFromAddress = data.getUserInfo(); String chatRoom = null; if (data.getPathSegments().size() > 0) chatRoom = data.getPathSegments().get(0); mToAddress = chatRoom + '@' + mHost; mProviderName = Imps.ProviderNames.XMPP; return true; } if (data.getScheme().equals("otr-in-band")) { this.openOtrInBand(data, intent.getType()); return true; } if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) { log("resolveIntent: host=" + mHost); } if (TextUtils.isEmpty(mHost)) { Set<String> categories = intent.getCategories(); if (categories != null) { Iterator<String> iter = categories.iterator(); if (iter.hasNext()) { String category = iter.next(); String providerName = getProviderNameForCategory(category); mProviderName = findMatchingProvider(providerName); if (mProviderName == null) { Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + category + " not supported"); return false; } } } mToAddress = data.getSchemeSpecificPart(); } else { mProviderName = findMatchingProvider(mHost); if (mProviderName == null) { Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + mHost + " not supported"); return false; } String path = data.getPath(); if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) log("resolveIntent: path=" + path); if (!TextUtils.isEmpty(path)) { int index; if ((index = path.indexOf('/')) != -1) { mToAddress = path.substring(index + 1); } } } if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) { log("resolveIntent: provider=" + mProviderName + ", to=" + mToAddress); } return true; } private String getProviderNameForCategory(String providerCategory) { return Imps.ProviderNames.XMPP; } private String findMatchingProvider(String provider) { if (TextUtils.isEmpty(provider)) { return null; } if (provider.equalsIgnoreCase("xmpp")) return Imps.ProviderNames.XMPP; return null; } private boolean isValidToAddress() { if (TextUtils.isEmpty(mToAddress)) { return false; } if (mToAddress.indexOf('/') != -1) { return false; } return true; } private static void log(String msg) { Log.d(ImApp.LOG_TAG, "<ImUrlActivity> " + msg); } @Override public void onCacheWordUninitialized() { Log.d(ImApp.LOG_TAG,"cache word uninit"); showLockScreen(); } void openMultiUserChat(final Uri data) { new AlertDialog.Builder(this) .setTitle("Join Chat Room?") .setMessage("An external app is attempting to connect you to a chatroom. Allow?") .setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(ImUrlActivity.this, NewChatActivity.class); intent.setData(data); startActivity(intent); finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do some stuff */ finish(); } }) .create().show(); } void openOtrInBand(final Uri data, final String type) { String url = data.toString(); if (url.startsWith(OtrDataHandler.URI_PREFIX_OTR_IN_BAND)) { String localUrl; try { localUrl = URLDecoder.decode(url.replaceFirst(OtrDataHandler.URI_PREFIX_OTR_IN_BAND, ""), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } FileInfo info = SystemServices.getFileInfoFromURI(ImUrlActivity.this, Uri.parse(localUrl)); mUrl = info.path; mType = type != null ? type : info.type; } startContactPicker(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) { if (resultCode == RESULT_OK) { if (requestCode == REQUEST_PICK_CONTACTS) { String username = resultIntent.getExtras().getString(ContactsPickerActivity.EXTRA_RESULT_USERNAME); sendOtrInBand(username); } finish(); } else { finish(); } } private void sendOtrInBand(String username) { IChatSession session = getChatSession(username); try { session.offerData( mUrl, mType ); } catch (RemoteException e) { throw new RuntimeException(e); } } private IChatSession getChatSession(String username) { IChatSessionManager sessionMgr = mChatSessionManager; if (sessionMgr != null) { try { IChatSession session = sessionMgr.getChatSession(username); if (session == null) session = sessionMgr.createChatSession(username); return session; } catch (RemoteException e) { LogCleaner.error(ImApp.LOG_TAG, "send message error",e); } } return null; } private void startContactPicker() { Uri.Builder builder = Imps.Contacts.CONTENT_URI_ONLINE_CONTACTS_BY.buildUpon(); List<IImConnection> listConns = ((ImApp)getApplication()).getActiveConnections(); IImConnection conn = listConns.get(0); // FIXME try { mChatSessionManager = conn.getChatSessionManager(); mProviderId = conn.getProviderId(); mAccountId = conn.getAccountId(); } catch (RemoteException e) { throw new RuntimeException(e); } ContentUris.appendId(builder, mProviderId); ContentUris.appendId(builder, mAccountId); Uri data = builder.build(); Intent i = new Intent(Intent.ACTION_PICK, data); startActivityForResult(i, REQUEST_PICK_CONTACTS); } void showLockScreen() { Intent intent = new Intent(this, LockScreenActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra("originalIntent", getIntent()); startActivity(intent); } @Override public void onCacheWordLocked() { showLockScreen(); } @Override public void onCacheWordOpened() { } }
src/info/guardianproject/otr/app/im/app/ImUrlActivity.java
/* * Copyright (C) 2008 Esmertec AG. Copyright (C) 2008 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 info.guardianproject.otr.app.im.app; import info.guardianproject.cacheword.CacheWordActivityHandler; import info.guardianproject.cacheword.ICacheWordSubscriber; import info.guardianproject.otr.OtrDataHandler; import info.guardianproject.otr.app.im.IChatSession; import info.guardianproject.otr.app.im.IChatSessionManager; import info.guardianproject.otr.app.im.IImConnection; import info.guardianproject.otr.app.im.R; import info.guardianproject.otr.app.im.engine.ImConnection; import info.guardianproject.otr.app.im.provider.Imps; import info.guardianproject.otr.app.im.service.ImServiceConstants; import info.guardianproject.util.LogCleaner; import info.guardianproject.util.SystemServices; import info.guardianproject.util.SystemServices.FileInfo; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Iterator; import java.util.List; import java.util.Set; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentUris; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; public class ImUrlActivity extends ThemeableActivity implements ICacheWordSubscriber { private static final String[] ACCOUNT_PROJECTION = { Imps.Account._ID, Imps.Account.PASSWORD, }; private static final int ACCOUNT_ID_COLUMN = 0; private static final int ACCOUNT_PW_COLUMN = 1; private static final int REQUEST_PICK_CONTACTS = RESULT_FIRST_USER + 1; private String mProviderName; private String mToAddress; private String mFromAddress; private String mHost; private ImApp mApp; private IImConnection mConn; private long mProviderId; private long mAccountId; private IChatSessionManager mChatSessionManager; private String mUrl; private String mType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CacheWordActivityHandler cacheWord = new CacheWordActivityHandler(this, (ICacheWordSubscriber)this); cacheWord.connectToService(); Intent intent = getIntent(); if (Intent.ACTION_SENDTO.equals(intent.getAction())) { if (!resolveIntent(intent)) { finish(); return; } if (TextUtils.isEmpty(mToAddress)) { LogCleaner.warn(ImApp.LOG_TAG, "<ImUrlActivity>Invalid to address"); // finish(); return; } mApp = (ImApp)getApplication(); if (mApp.serviceConnected()) handleIntent(); else { mApp.callWhenServiceConnected(new Handler(), new Runnable() { public void run() { handleIntent(); } }); } } else { finish(); } } void handleIntent() { ContentResolver cr = getContentResolver(); long providerId = Imps.Provider.getProviderIdForName(cr, mProviderName); long accountId; List<IImConnection> listConns = ((ImApp)getApplication()).getActiveConnections(); if (!listConns.isEmpty()) { mConn = listConns.get(0); try { providerId = mConn.getProviderId(); accountId = mConn.getAccountId(); } catch (RemoteException e) { e.printStackTrace(); } } if (mConn == null) { Cursor c = DatabaseUtils.queryAccountsForProvider(cr, ACCOUNT_PROJECTION, providerId); if (c == null) { addAccount(providerId); } else { accountId = c.getLong(ACCOUNT_ID_COLUMN); if (c.isNull(ACCOUNT_PW_COLUMN)) { editAccount(accountId); } else { signInAccount(accountId); } } } else { try { int state = mConn.getState(); accountId = mConn.getAccountId(); if (state < ImConnection.LOGGED_IN) { signInAccount(accountId); } else if (state == ImConnection.LOGGED_IN || state == ImConnection.SUSPENDED) { Uri data = getIntent().getData(); if (data.getScheme().equals("immu")) { this.openMultiUserChat(data); } else if (!isValidToAddress()) { showContactList(accountId); } else { openChat(providerId, accountId); } finish(); } } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w("ImUrlActivity", "Connection disappeared!"); } } } private void addAccount(long providerId) { Intent intent = new Intent(this, AccountActivity.class); intent.setAction(Intent.ACTION_INSERT); intent.setData(ContentUris.withAppendedId(Imps.Provider.CONTENT_URI, providerId)); // intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress); if (mFromAddress != null) intent.putExtra("newuser", mFromAddress + '@' + mHost); startActivity(intent); } private void editAccount(long accountId) { Uri accountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId); Intent intent = new Intent(this, AccountActivity.class); intent.setAction(Intent.ACTION_EDIT); intent.setData(accountUri); intent.putExtra(ImApp.EXTRA_INTENT_SEND_TO_USER, mToAddress); startActivity(intent); } private void signInAccount(long accountId) { editAccount(accountId); // TODO sign in? security implications? } private void showContactList(long accountId) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Imps.Contacts.CONTENT_URI); intent.addCategory(ImApp.IMPS_CATEGORY); intent.putExtra("accountId", accountId); startActivity(intent); } private void openChat(long provider, long account) { try { IChatSessionManager manager = mConn.getChatSessionManager(); IChatSession session = manager.getChatSession(mToAddress); if (session == null) { session = manager.createChatSession(mToAddress); } Uri data = ContentUris.withAppendedId(Imps.Chats.CONTENT_URI, session.getId()); Intent intent = new Intent(Intent.ACTION_VIEW, data); intent.putExtra(ImServiceConstants.EXTRA_INTENT_FROM_ADDRESS, mToAddress); intent.putExtra(ImServiceConstants.EXTRA_INTENT_PROVIDER_ID, provider); intent.putExtra(ImServiceConstants.EXTRA_INTENT_ACCOUNT_ID, account); intent.addCategory(ImApp.IMPS_CATEGORY); startActivity(intent); } catch (RemoteException e) { // Ouch! Service died! We'll just disappear. Log.w("ImUrlActivity", "Connection disappeared!"); } } private boolean resolveIntent(Intent intent) { Uri data = intent.getData(); mHost = data.getHost(); if (data.getScheme().equals("immu")) { this.openMultiUserChat(data); // mFromAddress = data.getUserInfo(); // String chatRoom = null; // // if (data.getPathSegments().size() > 0) // chatRoom = data.getPathSegments().get(0); // // mToAddress = chatRoom + '@' + mHost; // // mProviderName = Imps.ProviderNames.XMPP; return true; } if (data.getScheme().equals("otr-in-band")) { this.openOtrInBand(data, intent.getType()); return true; } if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) { log("resolveIntent: host=" + mHost); } if (TextUtils.isEmpty(mHost)) { Set<String> categories = intent.getCategories(); if (categories != null) { Iterator<String> iter = categories.iterator(); if (iter.hasNext()) { String category = iter.next(); String providerName = getProviderNameForCategory(category); mProviderName = findMatchingProvider(providerName); if (mProviderName == null) { Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + category + " not supported"); return false; } } } mToAddress = data.getSchemeSpecificPart(); } else { mProviderName = findMatchingProvider(mHost); if (mProviderName == null) { Log.w(ImApp.LOG_TAG, "resolveIntent: IM provider " + mHost + " not supported"); return false; } String path = data.getPath(); if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) log("resolveIntent: path=" + path); if (!TextUtils.isEmpty(path)) { int index; if ((index = path.indexOf('/')) != -1) { mToAddress = path.substring(index + 1); } } } if (Log.isLoggable(ImApp.LOG_TAG, Log.DEBUG)) { log("resolveIntent: provider=" + mProviderName + ", to=" + mToAddress); } return true; } private String getProviderNameForCategory(String providerCategory) { return Imps.ProviderNames.XMPP; } private String findMatchingProvider(String provider) { if (TextUtils.isEmpty(provider)) { return null; } if (provider.equalsIgnoreCase("xmpp")) return Imps.ProviderNames.XMPP; return null; } private boolean isValidToAddress() { if (TextUtils.isEmpty(mToAddress)) { return false; } if (mToAddress.indexOf('/') != -1) { return false; } return true; } private static void log(String msg) { Log.d(ImApp.LOG_TAG, "<ImUrlActivity> " + msg); } @Override public void onCacheWordUninitialized() { Log.d(ImApp.LOG_TAG,"cache word uninit"); showLockScreen(); } void openMultiUserChat(final Uri data) { new AlertDialog.Builder(this) .setTitle("Join Chat Room?") .setMessage("An external app is attempting to connect you to a chatroom. Allow?") .setPositiveButton(R.string.connect, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Intent intent = new Intent(ImUrlActivity.this, NewChatActivity.class); intent.setData(data); startActivity(intent); finish(); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do some stuff */ finish(); } }) .create().show(); } void openOtrInBand(final Uri data, final String type) { String url = data.toString(); if (url.startsWith(OtrDataHandler.URI_PREFIX_OTR_IN_BAND)) { String localUrl; try { localUrl = URLDecoder.decode(url.replaceFirst(OtrDataHandler.URI_PREFIX_OTR_IN_BAND, ""), "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } FileInfo info = SystemServices.getFileInfoFromURI(ImUrlActivity.this, Uri.parse(localUrl)); mUrl = info.path; mType = type != null ? type : info.type; } startContactPicker(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) { if (resultCode == RESULT_OK) { if (requestCode == REQUEST_PICK_CONTACTS) { String username = resultIntent.getExtras().getString(ContactsPickerActivity.EXTRA_RESULT_USERNAME); sendOtrInBand(username); } finish(); } else { finish(); } } private void sendOtrInBand(String username) { IChatSession session = getChatSession(username); try { session.offerData( mUrl, mType ); } catch (RemoteException e) { throw new RuntimeException(e); } } private IChatSession getChatSession(String username) { IChatSessionManager sessionMgr = mChatSessionManager; if (sessionMgr != null) { try { IChatSession session = sessionMgr.getChatSession(username); if (session == null) session = sessionMgr.createChatSession(username); return session; } catch (RemoteException e) { LogCleaner.error(ImApp.LOG_TAG, "send message error",e); } } return null; } private void startContactPicker() { Uri.Builder builder = Imps.Contacts.CONTENT_URI_ONLINE_CONTACTS_BY.buildUpon(); List<IImConnection> listConns = ((ImApp)getApplication()).getActiveConnections(); IImConnection conn = listConns.get(0); // FIXME try { mChatSessionManager = conn.getChatSessionManager(); mProviderId = conn.getProviderId(); mAccountId = conn.getAccountId(); } catch (RemoteException e) { throw new RuntimeException(e); } ContentUris.appendId(builder, mProviderId); ContentUris.appendId(builder, mAccountId); Uri data = builder.build(); Intent i = new Intent(Intent.ACTION_PICK, data); startActivityForResult(i, REQUEST_PICK_CONTACTS); } void showLockScreen() { Intent intent = new Intent(this, LockScreenActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra("originalIntent", getIntent()); startActivity(intent); } @Override public void onCacheWordLocked() { showLockScreen(); } @Override public void onCacheWordOpened() { } }
missed a file
src/info/guardianproject/otr/app/im/app/ImUrlActivity.java
missed a file
Java
bsd-2-clause
9b9888035b60550397612f67985493399a715bdf
0
scifio/scifio
// // FormatReaderTest.java // /* LOCI software automated test suite for TestNG. Copyright (C) 2007-@year@ Melissa Linkert and Curtis Rueden. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the UW-Madison LOCI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UW-MADISON LOCI ``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 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. */ package loci.tests.testng; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.FileStitcher; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.ImageReader; import loci.formats.ReaderWrapper; import loci.formats.gui.AWTImageTools; import loci.formats.gui.BufferedImageReader; import loci.formats.in.*; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.SkipException; import org.testng.annotations.AfterClass; /** * TestNG tester for Bio-Formats file format readers. * Details on failed tests are written to a log file, for easier processing. * * NB: {@link loci.formats.ome} and ome-xml.jar * are required for some of the tests. * * To run tests: * ant -Dtestng.directory="/path" -Dtestng.multiplier="1.0" test-all * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/test-suite/src/loci/tests/testng/FormatReaderTest.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/test-suite/src/loci/tests/testng/FormatReaderTest.java;hb=HEAD">Gitweb</a></dd></dl> */ public class FormatReaderTest { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(FormatReaderTest.class); /** Message to give for why a test was skipped. */ private static final String SKIP_MESSAGE = "Dataset already tested."; // -- Static fields -- /** Configuration tree structure containing dataset metadata. */ public static ConfigurationTree configTree; /** List of files to skip. */ private static List<String> skipFiles = new LinkedList<String>(); /** Global shared reader for use in all tests. */ private static BufferedImageReader reader; // -- Fields -- private String id; private boolean skip = false; private Configuration config; /** * Multiplier for use adjusting timing values. Slower machines take longer to * complete the timing test, and thus need to set a higher (&gt;1) multiplier * to avoid triggering false timing test failures. Conversely, faster * machines should set a lower (&lt;1) multipler to ensure things finish as * quickly as expected. */ private float timeMultiplier = 1; private boolean inMemory = false; private OMEXMLService omexmlService = null; // -- Constructor -- public FormatReaderTest(String filename, float multiplier, boolean inMemory) { id = filename; timeMultiplier = multiplier; this.inMemory = inMemory; try { ServiceFactory factory = new ServiceFactory(); omexmlService = factory.getInstance(OMEXMLService.class); } catch (DependencyException e) { LOGGER.warn("OMEXMLService not available", e); } } // -- Setup/teardown methods -- @AfterClass public void close() throws IOException { reader.close(); HashMap<String, Object> idMap = Location.getIdMap(); idMap.clear(); Location.setIdMap(idMap); } // -- Tests -- /** * @testng.test groups = "all pixels" */ public void testBufferedImageDimensions() { String testName = "testBufferedImageDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { BufferedImage b = null; for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getSizeX(); int y = reader.getSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int plane = x * y * c * bytes; long checkPlane = (long) x * y * c * bytes; // account for the fact that most histology (big image) files // require more memory for decoding/re-encoding BufferedImages if (DataTools.indexOf(reader.getDomains(), FormatTools.HISTOLOGY_DOMAIN) >= 0) { plane *= 2; checkPlane *= 2; } if (c > 4 || plane < 0 || plane != checkPlane || !TestTools.canFitInMemory(plane)) { continue; } int num = reader.getImageCount(); if (num > 3) num = 3; // test first three image planes only, for speed for (int j=0; j<num && success; j++) { b = reader.openImage(j); int actualX = b.getWidth(); boolean passX = x == actualX; if (!passX) msg = "X: was " + actualX + ", expected " + x; int actualY = b.getHeight(); boolean passY = y == actualY; if (!passY) msg = "Y: was " + actualY + ", expected " + y; int actualC = b.getRaster().getNumBands(); boolean passC = c == actualC; if (!passC) msg = "C: was " + actualC + ", expected " + c; int actualType = AWTImageTools.getPixelType(b); boolean passType = type == actualType; if (!passType && actualType == FormatTools.UINT16 && type == FormatTools.INT16) { passType = true; } if (!passType) msg = "type: was " + actualType + ", expected " + type; success = passX && passY && passC && passType; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testByteArrayDimensions() { String testName = "testByteArrayDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { byte[] b = null; for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getSizeX(); int y = reader.getSizeY(); int c = reader.getRGBChannelCount(); int bytes = FormatTools.getBytesPerPixel(reader.getPixelType()); int expected = x * y * c * bytes; if (!TestTools.canFitInMemory(expected) || expected < 0) { continue; } int num = reader.getImageCount(); if (num > 3) num = 3; // test first three planes only, for speed for (int j=0; j<num && success; j++) { b = reader.openBytes(j); success = b.length == expected; if (!success) { msg = "series #" + i + ", image #" + j + ": was " + b.length + ", expected " + expected; } } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testThumbnailImageDimensions() { String testName = "testThumbnailImageDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getThumbSizeX(); int y = reader.getThumbSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int fx = reader.getSizeX(); int fy = reader.getSizeY(); if (c > 4 || type == FormatTools.FLOAT || type == FormatTools.DOUBLE || !TestTools.canFitInMemory((long) fx * fy * c * bytes)) { continue; } BufferedImage b = null; try { b = reader.openThumbImage(0); } catch (OutOfMemoryError e) { result(testName, true, "Image too large"); return; } int actualX = b.getWidth(); boolean passX = x == actualX; if (!passX) { msg = "series #" + i + ": X: was " + actualX + ", expected " + x; } int actualY = b.getHeight(); boolean passY = y == actualY; if (!passY) { msg = "series #" + i + ": Y: was " + actualY + ", expected " + y; } int actualC = b.getRaster().getNumBands(); boolean passC = c == actualC; if (!passC) { msg = "series #" + i + ": C: was " + actualC + ", expected < " + c; } int actualType = AWTImageTools.getPixelType(b); boolean passType = type == actualType; if (!passType && actualType == FormatTools.UINT16 && type == FormatTools.INT16) { passType = true; } if (!passType) { msg = "series #" + i + ": type: was " + actualType + ", expected " + type; } success = passX && passY && passC && passType; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testThumbnailByteArrayDimensions() { String testName = "testThumbnailByteArrayDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getThumbSizeX(); int y = reader.getThumbSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int expected = x * y * c * bytes; int fx = reader.getSizeX(); int fy = reader.getSizeY(); if (c > 4 || type == FormatTools.FLOAT || type == FormatTools.DOUBLE || !TestTools.canFitInMemory((long) fx * fy * c * bytes * 20)) { continue; } byte[] b = null; try { b = reader.openThumbBytes(0); } catch (OutOfMemoryError e) { result(testName, true, "Image too large"); return; } success = b.length == expected; if (!success) { msg = "series #" + i + ": was " + b.length + ", expected " + expected; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all fast" */ public void testImageCount() { String testName = "testImageCount"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int imageCount = reader.getImageCount(); int z = reader.getSizeZ(); int c = reader.getEffectiveSizeC(); int t = reader.getSizeT(); success = imageCount == z * c * t; msg = "series #" + i + ": imageCount=" + imageCount + ", z=" + z + ", c=" + c + ", t=" + t; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all xml fast" */ public void testOMEXML() { String testName = "testOMEXML"; if (!initFile()) result(testName, false, "initFile"); String msg = null; try { MetadataRetrieve retrieve = (MetadataRetrieve) reader.getMetadataStore(); boolean success = omexmlService.isOMEXMLMetadata(retrieve); if (!success) msg = TestTools.shortClassName(retrieve); for (int i=0; i<reader.getSeriesCount() && msg == null; i++) { reader.setSeries(i); String type = FormatTools.getPixelTypeString(reader.getPixelType()); if (reader.getSizeX() != retrieve.getPixelsSizeX(i).getValue().intValue()) { msg = "SizeX"; } if (reader.getSizeY() != retrieve.getPixelsSizeY(i).getValue().intValue()) { msg = "SizeY"; } if (reader.getSizeZ() != retrieve.getPixelsSizeZ(i).getValue().intValue()) { msg = "SizeZ"; } if (reader.getSizeC() != retrieve.getPixelsSizeC(i).getValue().intValue()) { msg = "SizeC"; } if (reader.getSizeT() != retrieve.getPixelsSizeT(i).getValue().intValue()) { msg = "SizeT"; } // NB: OME-TIFF files do not have a BinData element under Pixels IFormatReader r = reader.unwrap(); if (r instanceof FileStitcher) r = ((FileStitcher) r).getReader(); if (r instanceof ReaderWrapper) r = ((ReaderWrapper) r).unwrap(); if (!(r instanceof OMETiffReader)) { if (reader.isLittleEndian() == retrieve.getPixelsBinDataBigEndian(i, 0).booleanValue()) { msg = "BigEndian"; } } if (!reader.getDimensionOrder().equals( retrieve.getPixelsDimensionOrder(i).toString())) { msg = "DimensionOrder"; } if (!type.equalsIgnoreCase(retrieve.getPixelsType(i).toString())) { msg = "PixelType"; } } } catch (Throwable t) { LOGGER.info("", t); msg = t.getMessage(); } result(testName, msg == null, msg); } /** * @testng.test groups = "all fast" */ public void testConsistentReader() { if (config == null) throw new SkipException("No config tree"); String testName = "testConsistentReader"; if (!initFile()) result(testName, false, "initFile"); String format = config.getReader(); IFormatReader r = reader; if (r instanceof ImageReader) { r = ((ImageReader) r).getReader(); } else if (r instanceof ReaderWrapper) { try { r = ((ReaderWrapper) r).unwrap(); } catch (FormatException e) { } catch (IOException e) { } } String realFormat = TestTools.shortClassName(r); result(testName, realFormat.equals(format), realFormat); } /** * @testng.test groups = "all xml" */ public void testSaneOMEXML() { String testName = "testSaneOMEXML"; if (!initFile()) result(testName, false, "initFile"); String msg = null; try { String format = config.getReader(); if (format.equals("OMETiffReader") || format.equals("OMEXMLReader")) { result(testName, true); return; } MetadataRetrieve retrieve = (MetadataRetrieve) reader.getMetadataStore(); boolean success = omexmlService.isOMEXMLMetadata(retrieve); if (!success) msg = TestTools.shortClassName(retrieve); for (int i=0; i<reader.getSeriesCount() && msg == null; i++) { // total number of ChannelComponents should match SizeC int sizeC = retrieve.getPixelsSizeC(i).getValue().intValue(); int nChannelComponents = retrieve.getChannelCount(i); int samplesPerPixel = retrieve.getChannelSamplesPerPixel(i, 0).getValue(); if (sizeC != nChannelComponents * samplesPerPixel) { msg = "ChannelComponent"; } // Z, C and T indices should be populated if PlaneTiming is present Double deltaT = null; Double exposure = null; Integer z = null, c = null, t = null; if (retrieve.getPlaneCount(i) > 0) { deltaT = retrieve.getPlaneDeltaT(i, 0); exposure = retrieve.getPlaneExposureTime(i, 0); z = retrieve.getPlaneTheZ(i, 0).getValue(); c = retrieve.getPlaneTheC(i, 0).getValue(); t = retrieve.getPlaneTheT(i, 0).getValue(); } if ((deltaT != null || exposure != null) && (z == null || c == null || t == null)) { msg = "PlaneTiming"; } // if CreationDate is before 1990, it's probably invalid String date = retrieve.getImageAcquiredDate(i); String configDate = config.getDate(); if (date != null && !date.equals(configDate)) { date = date.trim(); long acquiredDate = DateTools.getTime(date, DateTools.ISO8601_FORMAT); long saneDate = DateTools.getTime("1990-01-01T00:00:00", DateTools.ISO8601_FORMAT); long fileDate = new Location( reader.getCurrentFile()).getAbsoluteFile().lastModified(); if (acquiredDate < saneDate && fileDate >= saneDate) { msg = "CreationDate"; } } } } catch (Throwable t) { LOGGER.info("", t); msg = t.getMessage(); } result(testName, msg == null, msg); } // -- Consistency tests -- /** * @testng.test groups = "all fast" */ public void testSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeX"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeX() != config.getSizeX()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeY"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeY() != config.getSizeY()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeZ() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeZ"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeZ() != config.getSizeZ()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeC() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeC"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeC() != config.getSizeC()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeT() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeT"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeT() != config.getSizeT()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testDimensionOrder() { if (config == null) throw new SkipException("No config tree"); String testName = "DimensionOrder"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); String realOrder = reader.getDimensionOrder(); String expectedOrder = config.getDimensionOrder(); if (!realOrder.equals(expectedOrder)) { result(testName, false, "Series " + i + " (got " + realOrder + ", expected " + expectedOrder + ")"); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testIsInterleaved() { if (config == null) throw new SkipException("No config tree"); String testName = "Interleaved"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isInterleaved() != config.isInterleaved()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testIndexed() { if (config == null) throw new SkipException("No config tree"); String testName = "Indexed"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isIndexed() != config.isIndexed()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testFalseColor() { if (config == null) throw new SkipException("No config tree"); String testName = "FalseColor"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isFalseColor() != config.isFalseColor()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testRGB() { if (config == null) throw new SkipException("No config tree"); String testName = "RGB"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isRGB() != config.isRGB()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testThumbSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "ThumbSizeX"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getThumbSizeX() != config.getThumbSizeX()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testThumbSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "ThumbSizeY"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getThumbSizeY() != config.getThumbSizeY()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPixelType() { if (config == null) throw new SkipException("No config tree"); String testName = "PixelType"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getPixelType() != FormatTools.pixelTypeFromString(config.getPixelType())) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testLittleEndian() { if (config == null) throw new SkipException("No config tree"); String testName = "LittleEndian"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isLittleEndian() != config.isLittleEndian()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeX"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeX(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeX(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeY"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeY(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeY(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeZ() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeZ"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeZ(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeZ(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testTimeIncrement() { if (config == null) throw new SkipException("No config tree"); String testName = "TimeIncrement"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedIncrement = config.getTimeIncrement(); Double realIncrement = retrieve.getPixelsTimeIncrement(i); if (!(expectedIncrement == null && realIncrement == null) && !expectedIncrement.equals(realIncrement)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testLightSources() { if (config == null) throw new SkipException("No config tree"); String testName = "LightSources"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String expectedLightSource = config.getLightSource(c); String realLightSource = null; try { realLightSource = retrieve.getChannelLightSourceSettingsID(i, c); } catch (NullPointerException e) { } if (!(expectedLightSource == null && realLightSource == null) && !expectedLightSource.equals(realLightSource)) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testChannelNames() { if (config == null) throw new SkipException("No config tree"); String testName = "ChannelNames"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String realName = retrieve.getChannelName(i, c); String expectedName = config.getChannelName(c); if (!expectedName.equals(realName) && (realName == null && !expectedName.equals("null"))) { result(testName, false, "Series " + i + " channel " + c + " (got '" + realName + "', expected '" + expectedName + "')"); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testEmissionWavelengths() { if (config == null) throw new SkipException("No config tree"); String testName = "EmissionWavelengths"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { PositiveInteger realWavelength = retrieve.getChannelEmissionWavelength(i, c); Integer expectedWavelength = config.getEmissionWavelength(c); if (realWavelength == null && expectedWavelength == null) { continue; } if (realWavelength == null || expectedWavelength == null || !expectedWavelength.equals(realWavelength.getValue())) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testExcitationWavelengths() { if (config == null) throw new SkipException("No config tree"); String testName = "ExcitationWavelengths"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { PositiveInteger realWavelength = retrieve.getChannelExcitationWavelength(i, c); Integer expectedWavelength = config.getExcitationWavelength(c); if (realWavelength == null && expectedWavelength == null) { continue; } if (realWavelength == null || expectedWavelength == null || !expectedWavelength.equals(realWavelength.getValue())) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testDetectors() { if (config == null) throw new SkipException("No config tree"); String testName = "Detectors"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String expectedDetector = config.getDetector(c); String realDetector = null; try { realDetector = retrieve.getDetectorSettingsID(i, c); } catch (NullPointerException e) { } if (!(expectedDetector == null && realDetector == null)) { if ((expectedDetector == null || !expectedDetector.equals(realDetector)) && (realDetector == null || !realDetector.equals(expectedDetector))) { result(testName, false, "Series " + i + " channel " + c); } } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testImageNames() { if (config == null) throw new SkipException("No config tree"); String testName = "ImageNames"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); String realName = retrieve.getImageName(i); String expectedName = config.getImageName(); if (!expectedName.equals(realName) && !(realName == null && expectedName.equals("null"))) { result(testName, false, "Series " + i + " (got '" + realName + "', expected '" + expectedName + "')"); } } result(testName, true); } /** * @testng.test groups = "all" */ public void testPerformance() { if (config == null) throw new SkipException("No config tree"); String testName = "testPerformance"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { int properMem = config.getMemory(); double properTime = config.getAccessTimeMillis(); if (properMem <= 0 || properTime <= 0) { success = true; msg = "no configuration"; } else { Runtime r = Runtime.getRuntime(); System.gc(); // clean memory before we start long m1 = r.totalMemory() - r.freeMemory(); long t1 = System.currentTimeMillis(); int totalPlanes = 0; int seriesCount = reader.getSeriesCount(); for (int i=0; i<seriesCount; i++) { reader.setSeries(i); int imageCount = reader.getImageCount(); totalPlanes += imageCount; int planeSize = FormatTools.getPlaneSize(reader); if (planeSize < 0) { continue; } byte[] buf = new byte[planeSize]; for (int j=0; j<imageCount; j++) { try { reader.openBytes(j, buf); } catch (FormatException e) { LOGGER.info("", e); } catch (IOException e) { LOGGER.info("", e); } } } long t2 = System.currentTimeMillis(); System.gc(); long m2 = r.totalMemory() - r.freeMemory(); double actualTime = (double) (t2 - t1) / totalPlanes; int actualMem = (int) ((m2 - m1) >> 20); // check time elapsed if (actualTime - timeMultiplier * properTime > 20.0) { success = false; msg = "got " + actualTime + " ms, expected " + properTime + " ms"; } // check memory used else if (actualMem > properMem) { success = false; msg = "used " + actualMem + " MB; expected <= " + properMem + " MB"; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all type" */ public void testSaneUsedFiles() { if (!initFile()) return; String file = reader.getCurrentFile(); String testName = "testSaneUsedFiles"; boolean success = true; String msg = null; try { String[] base = reader.getUsedFiles(); if (base.length == 1) { if (!base[0].equals(file)) success = false; } else { Arrays.sort(base); IFormatReader r = /*config.noStitching() ? new ImageReader() :*/ new FileStitcher(); for (int i=0; i<base.length && success; i++) { // .xlog files in InCell 1000/2000 files may belong to more // than one dataset if (file.toLowerCase().endsWith(".xdce") && !base[i].toLowerCase().endsWith(".xdce")) { continue; } // Volocity datasets can only be detected with the .mvd2 file if (file.toLowerCase().endsWith(".mvd2") && !base[i].toLowerCase().endsWith(".mvd2")) { continue; } // Bruker datasets can only be detected with the // 'fid' and 'acqp' files if ((file.toLowerCase().endsWith("fid") || file.toLowerCase().endsWith("acqp")) && !base[i].toLowerCase().endsWith("fid") && !base[i].toLowerCase().endsWith("acqp") && reader.getFormat().equals("Bruker")) { continue; } r.setId(base[i]); String[] comp = r.getUsedFiles(); // If an .mdb file was initialized, then .lsm files are grouped. // If one of the .lsm files is initialized, though, then files // are not grouped. This is expected behavior; see ticket #3701. if (base[i].toLowerCase().endsWith(".lsm") && comp.length == 1) { r.close(); continue; } // Deltavision datasets are allowed to have different // used file counts. In some cases, a log file is associated // with multiple .dv files, so initializing the log file // will give different results. if (file.toLowerCase().endsWith(".dv") && base[i].toLowerCase().endsWith(".log")) { continue; } // Hitachi datasets consist of one text file and one pixels file // in a common format (e.g. BMP, JPEG, TIF). // It is acceptable for the pixels file to have a different // used file count from the text file. if (reader.getFormat().equals("Hitachi")) { continue; } // JPEG files that are part of a Trestle dataset can be detected // separately if (reader.getFormat().equals("Trestle")) { continue; } // TIFF files in CellR datasets are detected separately if (reader.getFormat().equals("Olympus APL") && base[i].toLowerCase().endsWith(".tif")) { continue; } // TIFF files in Li-Cor datasets are detected separately if (reader.getFormat().equals("Li-Cor L2D") && !base[i].toLowerCase().endsWith("l2d")) { continue; } if (comp.length != base.length) { success = false; msg = base[i] + " (file list length was " + comp.length + "; expected " + base.length + ")"; } if (success) Arrays.sort(comp); // NRRD datasets are allowed to have differing used files. // One raw file can have multiple header files associated with // it, in which case selecting the raw file will always produce // a test failure (which we can do nothing about). if (file.toLowerCase().endsWith(".nhdr") || base[i].toLowerCase().endsWith(".nhdr")) { continue; } for (int j=0; j<comp.length && success; j++) { if (!comp[j].equals(base[j])) { success = false; msg = base[i] + "(file @ " + j + " was '" + comp[j] + "', expected '" + base[j] + "')"; } } r.close(); } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all xml fast" */ public void testValidXML() { if (config == null) throw new SkipException("No config tree"); String testName = "testValidXML"; if (!initFile()) result(testName, false, "initFile"); String format = config.getReader(); if (format.equals("OMETiffReader") || format.equals("OMEXMLReader")) { result(testName, true); return; } boolean success = true; try { MetadataStore store = reader.getMetadataStore(); MetadataRetrieve retrieve = omexmlService.asRetrieve(store); String xml = omexmlService.getOMEXML(retrieve); success = xml != null && omexmlService.validateOMEXML(xml); } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success); } /** * @testng.test groups = "all pixels" */ public void testPixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testPixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { // check the MD5 of the first plane in each series for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); long planeSize = FormatTools.getPlaneSize(reader); if (planeSize < 0 || !TestTools.canFitInMemory(planeSize)) { continue; } String md5 = TestTools.md5(reader.openBytes(0)); String expected1 = config.getMD5(); String expected2 = config.getAlternateMD5(); if (expected1 == null && expected2 == null) { continue; } if (!md5.equals(expected1) && !md5.equals(expected2)) { success = false; msg = "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ /* public void testReorderedPixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testReorderedPixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); for (int j=0; j<3; j++) { int index = (int) (Math.random() * reader.getImageCount()); reader.openBytes(index); } String md5 = TestTools.md5(reader.openBytes(0)); String expected1 = config.getMD5(); String expected2 = config.getAlternateMD5(); if (!md5.equals(expected1) && !md5.equals(expected2)) { success = false; msg = expected1 == null && expected2 == null ? "no configuration" : "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } */ /** * @testng.test groups = "all pixels" */ public void testSubimagePixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testSubimagePixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { // check the MD5 of the first 512x512 tile of // the first plane in each series for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); int w = (int) Math.min(Configuration.TILE_SIZE, reader.getSizeX()); int h = (int) Math.min(Configuration.TILE_SIZE, reader.getSizeY()); String md5 = TestTools.md5(reader.openBytes(0, 0, 0, w, h)); String expected1 = config.getTileMD5(); String expected2 = config.getTileAlternateMD5(); if (!md5.equals(expected1) && !md5.equals(expected2) && (expected1 != null || expected2 != null)) { success = false; msg = "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all fast" */ public void testIsThisTypeConsistent() { String testName = "testIsThisTypeConsistent"; if (!initFile()) result(testName, false, "initFile"); String file = reader.getCurrentFile(); boolean isThisTypeOpen = reader.isThisType(file, true); boolean isThisTypeNotOpen = reader.isThisType(file, false); result(testName, (isThisTypeOpen == isThisTypeNotOpen) || (isThisTypeOpen && !isThisTypeNotOpen), "open = " + isThisTypeOpen + ", !open = " + isThisTypeNotOpen); } /** * @testng.test groups = "all fast" */ public void testIsThisType() { String testName = "testIsThisType"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { IFormatReader r = reader; // unwrap reader while (true) { if (r instanceof ReaderWrapper) { r = ((ReaderWrapper) r).getReader(); } else if (r instanceof FileStitcher) { r = ((FileStitcher) r).getReader(); } else break; } if (r instanceof ImageReader) { ImageReader ir = (ImageReader) r; r = ir.getReader(); IFormatReader[] readers = ir.getReaders(); String[] used = reader.getUsedFiles(); for (int i=0; i<used.length && success; i++) { // for each used file, make sure that one reader, // and only one reader, identifies the dataset as its own for (int j=0; j<readers.length; j++) { boolean result = readers[j].isThisType(used[i]); // TIFF reader is allowed to redundantly green-light files if (result && readers[j] instanceof TiffDelegateReader) continue; // Bio-Rad reader is allowed to redundantly // green-light PIC files from NRRD datasets if (result && r instanceof NRRDReader && readers[j] instanceof BioRadReader) { String low = used[i].toLowerCase(); boolean isPic = low.endsWith(".pic") || low.endsWith(".pic.gz"); if (isPic) continue; } // Analyze reader is allowed to redundantly accept NIfTI files if (result && r instanceof NiftiReader && readers[j] instanceof AnalyzeReader) { continue; } if (result && r instanceof MetamorphReader && readers[j] instanceof MetamorphTiffReader) { continue; } if (result && (readers[j] instanceof L2DReader) || ((r instanceof L2DReader) && (readers[j] instanceof GelReader) || readers[j] instanceof L2DReader)) { continue; } // ND2Reader is allowed to accept JPEG-2000 files if (result && r instanceof JPEG2000Reader && readers[j] instanceof ND2Reader) { continue; } if ((result && r instanceof APLReader && readers[j] instanceof SISReader) || (!result && r instanceof APLReader && readers[j] instanceof APLReader)) { continue; } // Prairie datasets can consist of OME-TIFF files with // extra metadata files, so it is acceptable for the OME-TIFF // reader to pick up TIFFs from a Prairie dataset if (result && r instanceof PrairieReader && readers[j] instanceof OMETiffReader) { continue; } if (result && r instanceof TrestleReader && (readers[j] instanceof JPEGReader || readers[j] instanceof PGMReader || readers[j] instanceof TiffDelegateReader)) { continue; } if (result && r instanceof HitachiReader) { continue; } if (!result && r instanceof VolocityReader && readers[j] instanceof VolocityReader) { continue; } if (!result && r instanceof InCellReader && readers[j] instanceof InCellReader && !used[i].toLowerCase().endsWith(".xdce")) { continue; } if (!result && r instanceof BrukerReader && readers[j] instanceof BrukerReader && !used[i].toLowerCase().equals("acqp") && !used[i].toLowerCase().equals("fid")) { continue; } boolean expected = r == readers[j]; if (result != expected) { success = false; if (result) { msg = TestTools.shortClassName(readers[j]) + " flagged \"" + used[i] + "\" but so did " + TestTools.shortClassName(r); } else { msg = TestTools.shortClassName(readers[j]) + " skipped \"" + used[i] + "\""; } break; } } } } else { success = false; msg = "Reader " + r.getClass().getName() + " is not an ImageReader"; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "config" */ public void writeConfigFile() { reader = new BufferedImageReader(new FileStitcher()); setupReader(); if (!initFile(false)) return; String file = reader.getCurrentFile(); LOGGER.info("Generating configuration: {}", file); try { File f = new File(new Location(file).getParent(), ".bioformats"); Configuration newConfig = new Configuration(reader, f.getAbsolutePath()); newConfig.saveToFile(); reader.close(); } catch (Throwable t) { LOGGER.info("", t); assert false; } } // -- Helper methods -- /** Sets up the current IFormatReader. */ private void setupReader() { reader.setNormalized(true); reader.setOriginalMetadataPopulated(true); reader.setMetadataFiltered(true); MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } reader.setMetadataStore(store); } /** Initializes the reader and configuration tree. */ private boolean initFile() { return initFile(true); } private boolean initFile(boolean removeDuplicateFiles) { if (skip) throw new SkipException(SKIP_MESSAGE); // initialize configuration tree if (config == null) { try { config = configTree.get(id); } catch (IOException e) { } } if (reader == null) { /* if (config.noStitching()) { reader = new BufferedImageReader(); } else { */ reader = new BufferedImageReader(new FileStitcher()); //} reader.setNormalized(true); reader.setMetadataFiltered(true); MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } reader.setMetadataStore(store); } if (id.equals(reader.getCurrentFile())) return true; // already initialized // skip files that were already tested as part of another file's dataset int ndx = skipFiles.indexOf(id); if (ndx >= 0 && removeDuplicateFiles) { LOGGER.info("Skipping {}", id); skipFiles.remove(ndx); skip = true; throw new SkipException(SKIP_MESSAGE); } // only test for missing configuration *after* we have removed duplicates // this prevents failures for missing configuration of files that are on // the used files list for a different file (e.g. TIFFs in a Leica LEI // dataset) if (config == null && removeDuplicateFiles) { throw new RuntimeException(id + " not configured."); } LOGGER.info("Initializing {}: ", id); try { boolean reallyInMemory = false; if (inMemory) { HashMap<String, Object> idMap = Location.getIdMap(); idMap.clear(); Location.setIdMap(idMap); reallyInMemory = mapFile(id); } reader.setId(id); // remove used files String[] used = reader.getUsedFiles(); boolean base = false; for (int i=0; i<used.length; i++) { if (id.equals(used[i])) { base = true; continue; } skipFiles.add(used[i]); if (reallyInMemory) { mapFile(used[i]); } } boolean single = used.length == 1; if (single && base) LOGGER.info("OK"); else LOGGER.info("{} {}", used.length, single ? "file" : "files"); if (!base) { LOGGER.error("Used files list does not include base file"); } } catch (Throwable t) { LOGGER.error("", t); return false; } return true; } /** Outputs test result and generates appropriate assertion. */ private static void result(String testName, boolean success) { result(testName, success, null); } /** * Outputs test result with optional extra message * and generates appropriate assertion. */ private static void result(String testName, boolean success, String msg) { LOGGER.info("\t{}: {} ({})", new Object[] {testName, success ? "PASSED" : "FAILED", msg == null ? "" : msg}); if (msg == null) assert success; else assert success : msg; } private static boolean mapFile(String id) throws IOException { RandomAccessInputStream stream = new RandomAccessInputStream(id); Runtime rt = Runtime.getRuntime(); long maxMem = rt.freeMemory(); long length = stream.length(); if (length < Integer.MAX_VALUE && length < maxMem) { stream.close(); FileInputStream fis = new FileInputStream(id); FileChannel channel = fis.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, length); ByteArrayHandle handle = new ByteArrayHandle(buf); Location.mapFile(id, handle); fis.close(); return true; } stream.close(); return false; } }
components/test-suite/src/loci/tests/testng/FormatReaderTest.java
// // FormatReaderTest.java // /* LOCI software automated test suite for TestNG. Copyright (C) 2007-@year@ Melissa Linkert and Curtis Rueden. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the UW-Madison LOCI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE UW-MADISON LOCI ``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 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. */ package loci.tests.testng; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.formats.FileStitcher; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.ImageReader; import loci.formats.ReaderWrapper; import loci.formats.gui.AWTImageTools; import loci.formats.gui.BufferedImageReader; import loci.formats.in.*; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testng.SkipException; import org.testng.annotations.AfterClass; /** * TestNG tester for Bio-Formats file format readers. * Details on failed tests are written to a log file, for easier processing. * * NB: {@link loci.formats.ome} and ome-xml.jar * are required for some of the tests. * * To run tests: * ant -Dtestng.directory="/path" -Dtestng.multiplier="1.0" test-all * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/test-suite/src/loci/tests/testng/FormatReaderTest.java">Trac</a>, * <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/test-suite/src/loci/tests/testng/FormatReaderTest.java;hb=HEAD">Gitweb</a></dd></dl> */ public class FormatReaderTest { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(FormatReaderTest.class); /** Message to give for why a test was skipped. */ private static final String SKIP_MESSAGE = "Dataset already tested."; // -- Static fields -- /** Configuration tree structure containing dataset metadata. */ public static ConfigurationTree configTree; /** List of files to skip. */ private static List<String> skipFiles = new LinkedList<String>(); /** Global shared reader for use in all tests. */ private static BufferedImageReader reader; // -- Fields -- private String id; private boolean skip = false; private Configuration config; /** * Multiplier for use adjusting timing values. Slower machines take longer to * complete the timing test, and thus need to set a higher (&gt;1) multiplier * to avoid triggering false timing test failures. Conversely, faster * machines should set a lower (&lt;1) multipler to ensure things finish as * quickly as expected. */ private float timeMultiplier = 1; private boolean inMemory = false; private OMEXMLService omexmlService = null; // -- Constructor -- public FormatReaderTest(String filename, float multiplier, boolean inMemory) { id = filename; timeMultiplier = multiplier; this.inMemory = inMemory; try { ServiceFactory factory = new ServiceFactory(); omexmlService = factory.getInstance(OMEXMLService.class); } catch (DependencyException e) { LOGGER.warn("OMEXMLService not available", e); } } // -- Setup/teardown methods -- @AfterClass public void close() throws IOException { reader.close(); HashMap<String, Object> idMap = Location.getIdMap(); idMap.clear(); Location.setIdMap(idMap); } // -- Tests -- /** * @testng.test groups = "all pixels" */ public void testBufferedImageDimensions() { String testName = "testBufferedImageDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { BufferedImage b = null; for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getSizeX(); int y = reader.getSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int plane = x * y * c * bytes; long checkPlane = (long) x * y * c * bytes; // account for the fact that most histology (big image) files // require more memory for decoding/re-encoding BufferedImages if (DataTools.indexOf(reader.getDomains(), FormatTools.HISTOLOGY_DOMAIN) >= 0) { plane *= 2; checkPlane *= 2; } if (c > 4 || plane < 0 || plane != checkPlane || !TestTools.canFitInMemory(plane)) { continue; } int num = reader.getImageCount(); if (num > 3) num = 3; // test first three image planes only, for speed for (int j=0; j<num && success; j++) { b = reader.openImage(j); int actualX = b.getWidth(); boolean passX = x == actualX; if (!passX) msg = "X: was " + actualX + ", expected " + x; int actualY = b.getHeight(); boolean passY = y == actualY; if (!passY) msg = "Y: was " + actualY + ", expected " + y; int actualC = b.getRaster().getNumBands(); boolean passC = c == actualC; if (!passC) msg = "C: was " + actualC + ", expected " + c; int actualType = AWTImageTools.getPixelType(b); boolean passType = type == actualType; if (!passType && actualType == FormatTools.UINT16 && type == FormatTools.INT16) { passType = true; } if (!passType) msg = "type: was " + actualType + ", expected " + type; success = passX && passY && passC && passType; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testByteArrayDimensions() { String testName = "testByteArrayDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { byte[] b = null; for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getSizeX(); int y = reader.getSizeY(); int c = reader.getRGBChannelCount(); int bytes = FormatTools.getBytesPerPixel(reader.getPixelType()); int expected = x * y * c * bytes; if (!TestTools.canFitInMemory(expected) || expected < 0) { continue; } int num = reader.getImageCount(); if (num > 3) num = 3; // test first three planes only, for speed for (int j=0; j<num && success; j++) { b = reader.openBytes(j); success = b.length == expected; if (!success) { msg = "series #" + i + ", image #" + j + ": was " + b.length + ", expected " + expected; } } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testThumbnailImageDimensions() { String testName = "testThumbnailImageDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getThumbSizeX(); int y = reader.getThumbSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int fx = reader.getSizeX(); int fy = reader.getSizeY(); if (c > 4 || type == FormatTools.FLOAT || type == FormatTools.DOUBLE || !TestTools.canFitInMemory((long) fx * fy * c * bytes)) { continue; } BufferedImage b = null; try { b = reader.openThumbImage(0); } catch (OutOfMemoryError e) { result(testName, true, "Image too large"); return; } int actualX = b.getWidth(); boolean passX = x == actualX; if (!passX) { msg = "series #" + i + ": X: was " + actualX + ", expected " + x; } int actualY = b.getHeight(); boolean passY = y == actualY; if (!passY) { msg = "series #" + i + ": Y: was " + actualY + ", expected " + y; } int actualC = b.getRaster().getNumBands(); boolean passC = c == actualC; if (!passC) { msg = "series #" + i + ": C: was " + actualC + ", expected < " + c; } int actualType = AWTImageTools.getPixelType(b); boolean passType = type == actualType; if (!passType && actualType == FormatTools.UINT16 && type == FormatTools.INT16) { passType = true; } if (!passType) { msg = "series #" + i + ": type: was " + actualType + ", expected " + type; } success = passX && passY && passC && passType; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ public void testThumbnailByteArrayDimensions() { String testName = "testThumbnailByteArrayDimensions"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int x = reader.getThumbSizeX(); int y = reader.getThumbSizeY(); int c = reader.getRGBChannelCount(); int type = reader.getPixelType(); int bytes = FormatTools.getBytesPerPixel(type); int expected = x * y * c * bytes; int fx = reader.getSizeX(); int fy = reader.getSizeY(); if (c > 4 || type == FormatTools.FLOAT || type == FormatTools.DOUBLE || !TestTools.canFitInMemory((long) fx * fy * c * bytes * 20)) { continue; } byte[] b = null; try { b = reader.openThumbBytes(0); } catch (OutOfMemoryError e) { result(testName, true, "Image too large"); return; } success = b.length == expected; if (!success) { msg = "series #" + i + ": was " + b.length + ", expected " + expected; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all fast" */ public void testImageCount() { String testName = "testImageCount"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); int imageCount = reader.getImageCount(); int z = reader.getSizeZ(); int c = reader.getEffectiveSizeC(); int t = reader.getSizeT(); success = imageCount == z * c * t; msg = "series #" + i + ": imageCount=" + imageCount + ", z=" + z + ", c=" + c + ", t=" + t; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all xml fast" */ public void testOMEXML() { String testName = "testOMEXML"; if (!initFile()) result(testName, false, "initFile"); String msg = null; try { MetadataRetrieve retrieve = (MetadataRetrieve) reader.getMetadataStore(); boolean success = omexmlService.isOMEXMLMetadata(retrieve); if (!success) msg = TestTools.shortClassName(retrieve); for (int i=0; i<reader.getSeriesCount() && msg == null; i++) { reader.setSeries(i); String type = FormatTools.getPixelTypeString(reader.getPixelType()); if (reader.getSizeX() != retrieve.getPixelsSizeX(i).getValue().intValue()) { msg = "SizeX"; } if (reader.getSizeY() != retrieve.getPixelsSizeY(i).getValue().intValue()) { msg = "SizeY"; } if (reader.getSizeZ() != retrieve.getPixelsSizeZ(i).getValue().intValue()) { msg = "SizeZ"; } if (reader.getSizeC() != retrieve.getPixelsSizeC(i).getValue().intValue()) { msg = "SizeC"; } if (reader.getSizeT() != retrieve.getPixelsSizeT(i).getValue().intValue()) { msg = "SizeT"; } // NB: OME-TIFF files do not have a BinData element under Pixels IFormatReader r = reader.unwrap(); if (r instanceof FileStitcher) r = ((FileStitcher) r).getReader(); if (r instanceof ReaderWrapper) r = ((ReaderWrapper) r).unwrap(); if (!(r instanceof OMETiffReader)) { if (reader.isLittleEndian() == retrieve.getPixelsBinDataBigEndian(i, 0).booleanValue()) { msg = "BigEndian"; } } if (!reader.getDimensionOrder().equals( retrieve.getPixelsDimensionOrder(i).toString())) { msg = "DimensionOrder"; } if (!type.equalsIgnoreCase(retrieve.getPixelsType(i).toString())) { msg = "PixelType"; } } } catch (Throwable t) { LOGGER.info("", t); msg = t.getMessage(); } result(testName, msg == null, msg); } /** * @testng.test groups = "all fast" */ public void testConsistentReader() { if (config == null) throw new SkipException("No config tree"); String testName = "testConsistentReader"; if (!initFile()) result(testName, false, "initFile"); String format = config.getReader(); IFormatReader r = reader; if (r instanceof ImageReader) { r = ((ImageReader) r).getReader(); } else if (r instanceof ReaderWrapper) { try { r = ((ReaderWrapper) r).unwrap(); } catch (FormatException e) { } catch (IOException e) { } } String realFormat = TestTools.shortClassName(r); result(testName, realFormat.equals(format), realFormat); } /** * @testng.test groups = "all xml" */ public void testSaneOMEXML() { String testName = "testSaneOMEXML"; if (!initFile()) result(testName, false, "initFile"); String msg = null; try { String format = config.getReader(); if (format.equals("OMETiffReader") || format.equals("OMEXMLReader")) { result(testName, true); return; } MetadataRetrieve retrieve = (MetadataRetrieve) reader.getMetadataStore(); boolean success = omexmlService.isOMEXMLMetadata(retrieve); if (!success) msg = TestTools.shortClassName(retrieve); for (int i=0; i<reader.getSeriesCount() && msg == null; i++) { // total number of ChannelComponents should match SizeC int sizeC = retrieve.getPixelsSizeC(i).getValue().intValue(); int nChannelComponents = retrieve.getChannelCount(i); int samplesPerPixel = retrieve.getChannelSamplesPerPixel(i, 0).getValue(); if (sizeC != nChannelComponents * samplesPerPixel) { msg = "ChannelComponent"; } // Z, C and T indices should be populated if PlaneTiming is present Double deltaT = null; Double exposure = null; Integer z = null, c = null, t = null; if (retrieve.getPlaneCount(i) > 0) { deltaT = retrieve.getPlaneDeltaT(i, 0); exposure = retrieve.getPlaneExposureTime(i, 0); z = retrieve.getPlaneTheZ(i, 0).getValue(); c = retrieve.getPlaneTheC(i, 0).getValue(); t = retrieve.getPlaneTheT(i, 0).getValue(); } if ((deltaT != null || exposure != null) && (z == null || c == null || t == null)) { msg = "PlaneTiming"; } // if CreationDate is before 1990, it's probably invalid String date = retrieve.getImageAcquiredDate(i); String configDate = config.getDate(); if (date != null && !date.equals(configDate)) { date = date.trim(); long acquiredDate = DateTools.getTime(date, DateTools.ISO8601_FORMAT); long saneDate = DateTools.getTime("1990-01-01T00:00:00", DateTools.ISO8601_FORMAT); long fileDate = new Location( reader.getCurrentFile()).getAbsoluteFile().lastModified(); if (acquiredDate < saneDate && fileDate >= saneDate) { msg = "CreationDate"; } } } } catch (Throwable t) { LOGGER.info("", t); msg = t.getMessage(); } result(testName, msg == null, msg); } // -- Consistency tests -- /** * @testng.test groups = "all fast" */ public void testSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeX"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeX() != config.getSizeX()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeY"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeY() != config.getSizeY()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeZ() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeZ"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeZ() != config.getSizeZ()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeC() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeC"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeC() != config.getSizeC()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testSizeT() { if (config == null) throw new SkipException("No config tree"); String testName = "SizeT"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getSizeT() != config.getSizeT()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testDimensionOrder() { if (config == null) throw new SkipException("No config tree"); String testName = "DimensionOrder"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); String realOrder = reader.getDimensionOrder(); String expectedOrder = config.getDimensionOrder(); if (!realOrder.equals(expectedOrder)) { result(testName, false, "Series " + i + " (got " + realOrder + ", expected " + expectedOrder + ")"); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testIsInterleaved() { if (config == null) throw new SkipException("No config tree"); String testName = "Interleaved"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isInterleaved() != config.isInterleaved()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testIndexed() { if (config == null) throw new SkipException("No config tree"); String testName = "Indexed"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isIndexed() != config.isIndexed()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testFalseColor() { if (config == null) throw new SkipException("No config tree"); String testName = "FalseColor"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isFalseColor() != config.isFalseColor()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testRGB() { if (config == null) throw new SkipException("No config tree"); String testName = "RGB"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isRGB() != config.isRGB()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testThumbSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "ThumbSizeX"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getThumbSizeX() != config.getThumbSizeX()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testThumbSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "ThumbSizeY"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getThumbSizeY() != config.getThumbSizeY()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPixelType() { if (config == null) throw new SkipException("No config tree"); String testName = "PixelType"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.getPixelType() != FormatTools.pixelTypeFromString(config.getPixelType())) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testLittleEndian() { if (config == null) throw new SkipException("No config tree"); String testName = "LittleEndian"; if (!initFile()) result(testName, false, "initFile"); for (int i=0; i<reader.getSeriesCount(); i++) { reader.setSeries(i); config.setSeries(i); if (reader.isLittleEndian() != config.isLittleEndian()) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeX() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeX"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeX(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeX(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeY() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeY"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeY(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeY(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testPhysicalSizeZ() { if (config == null) throw new SkipException("No config tree"); String testName = "PhysicalSizeZ"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedSize = config.getPhysicalSizeZ(); if (expectedSize == null || expectedSize == 0d) { expectedSize = null; } PositiveFloat realSize = retrieve.getPixelsPhysicalSizeZ(i); Double size = realSize == null ? null : realSize.getValue(); if (!(expectedSize == null && realSize == null) && !expectedSize.equals(size)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testTimeIncrement() { if (config == null) throw new SkipException("No config tree"); String testName = "TimeIncrement"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); Double expectedIncrement = config.getTimeIncrement(); Double realIncrement = retrieve.getPixelsTimeIncrement(i); if (!(expectedIncrement == null && realIncrement == null) && !expectedIncrement.equals(realIncrement)) { result(testName, false, "Series " + i); } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testLightSources() { if (config == null) throw new SkipException("No config tree"); String testName = "LightSources"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String expectedLightSource = config.getLightSource(c); String realLightSource = null; try { realLightSource = retrieve.getChannelLightSourceSettingsID(i, c); } catch (NullPointerException e) { } if (!(expectedLightSource == null && realLightSource == null) && !expectedLightSource.equals(realLightSource)) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testChannelNames() { if (config == null) throw new SkipException("No config tree"); String testName = "ChannelNames"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String realName = retrieve.getChannelName(i, c); String expectedName = config.getChannelName(c); if (!expectedName.equals(realName) && (realName == null && !expectedName.equals("null"))) { result(testName, false, "Series " + i + " channel " + c + " (got '" + realName + "', expected '" + expectedName + "')"); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testEmissionWavelengths() { if (config == null) throw new SkipException("No config tree"); String testName = "EmissionWavelengths"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { PositiveInteger realWavelength = retrieve.getChannelEmissionWavelength(i, c); Integer expectedWavelength = config.getEmissionWavelength(c); if (realWavelength == null && expectedWavelength == null) { continue; } if (realWavelength == null || expectedWavelength == null || !expectedWavelength.equals(realWavelength.getValue())) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testExcitationWavelengths() { if (config == null) throw new SkipException("No config tree"); String testName = "ExcitationWavelengths"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { PositiveInteger realWavelength = retrieve.getChannelExcitationWavelength(i, c); Integer expectedWavelength = config.getExcitationWavelength(c); if (realWavelength == null && expectedWavelength == null) { continue; } if (realWavelength == null || expectedWavelength == null || !expectedWavelength.equals(realWavelength.getValue())) { result(testName, false, "Series " + i + " channel " + c); } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testDetectors() { if (config == null) throw new SkipException("No config tree"); String testName = "Detectors"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); for (int c=0; c<config.getChannelCount(); c++) { String expectedDetector = config.getDetector(c); String realDetector = null; try { realDetector = retrieve.getDetectorSettingsID(i, c); } catch (NullPointerException e) { } if (!(expectedDetector == null && realDetector == null)) { if ((expectedDetector == null || !expectedDetector.equals(realDetector)) && (realDetector == null || !realDetector.equals(expectedDetector))) { result(testName, false, "Series " + i + " channel " + c); } } } } result(testName, true); } /** * @testng.test groups = "all fast" */ public void testImageNames() { if (config == null) throw new SkipException("No config tree"); String testName = "ImageNames"; if (!initFile()) result(testName, false, "initFile"); IMetadata retrieve = (IMetadata) reader.getMetadataStore(); for (int i=0; i<reader.getSeriesCount(); i++) { config.setSeries(i); String realName = retrieve.getImageName(i); String expectedName = config.getImageName(); if (!expectedName.equals(realName) && !(realName == null && expectedName.equals("null"))) { result(testName, false, "Series " + i + " (got '" + realName + "', expected '" + expectedName + "')"); } } result(testName, true); } /** * @testng.test groups = "all" */ public void testPerformance() { if (config == null) throw new SkipException("No config tree"); String testName = "testPerformance"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { int properMem = config.getMemory(); double properTime = config.getAccessTimeMillis(); if (properMem <= 0 || properTime <= 0) { success = true; msg = "no configuration"; } else { Runtime r = Runtime.getRuntime(); System.gc(); // clean memory before we start long m1 = r.totalMemory() - r.freeMemory(); long t1 = System.currentTimeMillis(); int totalPlanes = 0; int seriesCount = reader.getSeriesCount(); for (int i=0; i<seriesCount; i++) { reader.setSeries(i); int imageCount = reader.getImageCount(); totalPlanes += imageCount; int planeSize = FormatTools.getPlaneSize(reader); if (planeSize < 0) { continue; } byte[] buf = new byte[planeSize]; for (int j=0; j<imageCount; j++) { try { reader.openBytes(j, buf); } catch (FormatException e) { LOGGER.info("", e); } catch (IOException e) { LOGGER.info("", e); } } } long t2 = System.currentTimeMillis(); System.gc(); long m2 = r.totalMemory() - r.freeMemory(); double actualTime = (double) (t2 - t1) / totalPlanes; int actualMem = (int) ((m2 - m1) >> 20); // check time elapsed if (actualTime - timeMultiplier * properTime > 20.0) { success = false; msg = "got " + actualTime + " ms, expected " + properTime + " ms"; } // check memory used else if (actualMem > properMem) { success = false; msg = "used " + actualMem + " MB; expected <= " + properMem + " MB"; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all type" */ public void testSaneUsedFiles() { if (!initFile()) return; String file = reader.getCurrentFile(); String testName = "testSaneUsedFiles"; boolean success = true; String msg = null; try { String[] base = reader.getUsedFiles(); if (base.length == 1) { if (!base[0].equals(file)) success = false; } else { Arrays.sort(base); IFormatReader r = /*config.noStitching() ? new ImageReader() :*/ new FileStitcher(); for (int i=0; i<base.length && success; i++) { // .xlog files in InCell 1000/2000 files may belong to more // than one dataset if (file.toLowerCase().endsWith(".xdce") && !base[i].toLowerCase().endsWith(".xdce")) { continue; } // Volocity datasets can only be detected with the .mvd2 file if (file.toLowerCase().endsWith(".mvd2") && !base[i].toLowerCase().endsWith(".mvd2")) { continue; } // Bruker datasets can only be detected with the // 'fid' and 'acqp' files if ((file.toLowerCase().endsWith("fid") || file.toLowerCase().endsWith("acqp")) && !base[i].toLowerCase().endsWith("fid") && !base[i].toLowerCase().endsWith("acqp") && reader.getFormat().equals("Bruker")) { continue; } r.setId(base[i]); String[] comp = r.getUsedFiles(); // If an .mdb file was initialized, then .lsm files are grouped. // If one of the .lsm files is initialized, though, then files // are not grouped. This is expected behavior; see ticket #3701. if (base[i].toLowerCase().endsWith(".lsm") && comp.length == 1) { r.close(); continue; } // Deltavision datasets are allowed to have different // used file counts. In some cases, a log file is associated // with multiple .dv files, so initializing the log file // will give different results. if (file.toLowerCase().endsWith(".dv") && base[i].toLowerCase().endsWith(".log")) { continue; } // Hitachi datasets consist of one text file and one pixels file // in a common format (e.g. BMP, JPEG, TIF). // It is acceptable for the pixels file to have a different // used file count from the text file. if (reader.getFormat().equals("Hitachi")) { continue; } // JPEG files that are part of a Trestle dataset can be detected // separately if (reader.getFormat().equals("Trestle")) { continue; } // TIFF files in CellR datasets are detected separately if (reader.getFormat().equals("Olympus APL") && base[i].toLowerCase().endsWith(".tif")) { continue; } // TIFF files in Li-Cor datasets are detected separately if (reader.getFormat().equals("Li-Cor L2D") && !base[i].toLowerCase().endsWith("l2d")) { continue; } if (comp.length != base.length) { success = false; msg = base[i] + " (file list length was " + comp.length + "; expected " + base.length + ")"; } if (success) Arrays.sort(comp); // NRRD datasets are allowed to have differing used files. // One raw file can have multiple header files associated with // it, in which case selecting the raw file will always produce // a test failure (which we can do nothing about). if (file.toLowerCase().endsWith(".nhdr") || base[i].toLowerCase().endsWith(".nhdr")) { continue; } for (int j=0; j<comp.length && success; j++) { if (!comp[j].equals(base[j])) { success = false; msg = base[i] + "(file @ " + j + " was '" + comp[j] + "', expected '" + base[j] + "')"; } } r.close(); } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all xml fast" */ public void testValidXML() { if (config == null) throw new SkipException("No config tree"); String testName = "testValidXML"; if (!initFile()) result(testName, false, "initFile"); String format = config.getReader(); if (format.equals("OMETiffReader") || format.equals("OMEXMLReader")) { result(testName, true); return; } boolean success = true; try { MetadataStore store = reader.getMetadataStore(); MetadataRetrieve retrieve = omexmlService.asRetrieve(store); String xml = omexmlService.getOMEXML(retrieve); success = xml != null && omexmlService.validateOMEXML(xml); } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success); } /** * @testng.test groups = "all pixels" */ public void testPixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testPixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { // check the MD5 of the first plane in each series for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); long planeSize = FormatTools.getPlaneSize(reader); if (planeSize < 0 || !TestTools.canFitInMemory(planeSize)) { continue; } String md5 = TestTools.md5(reader.openBytes(0)); String expected1 = config.getMD5(); String expected2 = config.getAlternateMD5(); if (expected1 == null && expected2 == null) { continue; } if (!md5.equals(expected1) && !md5.equals(expected2)) { success = false; msg = "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all pixels" */ /* public void testReorderedPixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testReorderedPixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); for (int j=0; j<3; j++) { int index = (int) (Math.random() * reader.getImageCount()); reader.openBytes(index); } String md5 = TestTools.md5(reader.openBytes(0)); String expected1 = config.getMD5(); String expected2 = config.getAlternateMD5(); if (!md5.equals(expected1) && !md5.equals(expected2)) { success = false; msg = expected1 == null && expected2 == null ? "no configuration" : "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } */ /** * @testng.test groups = "all pixels" */ public void testSubimagePixelsHashes() { if (config == null) throw new SkipException("No config tree"); String testName = "testSubimagePixelsHashes"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { // check the MD5 of the first 512x512 tile of // the first plane in each series for (int i=0; i<reader.getSeriesCount() && success; i++) { reader.setSeries(i); config.setSeries(i); int w = (int) Math.min(Configuration.TILE_SIZE, reader.getSizeX()); int h = (int) Math.min(Configuration.TILE_SIZE, reader.getSizeY()); String md5 = TestTools.md5(reader.openBytes(0, 0, 0, w, h)); String expected1 = config.getTileMD5(); String expected2 = config.getTileAlternateMD5(); if (!md5.equals(expected1) && !md5.equals(expected2) && (expected1 != null || expected2 != null)) { success = false; msg = "series " + i; } } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "all fast" */ public void testIsThisTypeConsistent() { String testName = "testIsThisTypeConsistent"; if (!initFile()) result(testName, false, "initFile"); String file = reader.getCurrentFile(); boolean isThisTypeOpen = reader.isThisType(file, true); boolean isThisTypeNotOpen = reader.isThisType(file, false); result(testName, (isThisTypeOpen == isThisTypeNotOpen) || (isThisTypeOpen && !isThisTypeNotOpen), "open = " + isThisTypeOpen + ", !open = " + isThisTypeNotOpen); } /** * @testng.test groups = "all fast" */ public void testIsThisType() { String testName = "testIsThisType"; if (!initFile()) result(testName, false, "initFile"); boolean success = true; String msg = null; try { IFormatReader r = reader; // unwrap reader while (true) { if (r instanceof ReaderWrapper) { r = ((ReaderWrapper) r).getReader(); } else if (r instanceof FileStitcher) { r = ((FileStitcher) r).getReader(); } else break; } if (r instanceof ImageReader) { ImageReader ir = (ImageReader) r; r = ir.getReader(); IFormatReader[] readers = ir.getReaders(); String[] used = reader.getUsedFiles(); for (int i=0; i<used.length && success; i++) { // for each used file, make sure that one reader, // and only one reader, identifies the dataset as its own for (int j=0; j<readers.length; j++) { boolean result = readers[j].isThisType(used[i]); // TIFF reader is allowed to redundantly green-light files if (result && readers[j] instanceof TiffDelegateReader) continue; // Bio-Rad reader is allowed to redundantly // green-light PIC files from NRRD datasets if (result && r instanceof NRRDReader && readers[j] instanceof BioRadReader) { String low = used[i].toLowerCase(); boolean isPic = low.endsWith(".pic") || low.endsWith(".pic.gz"); if (isPic) continue; } // Analyze reader is allowed to redundantly accept NIfTI files if (result && r instanceof NiftiReader && readers[j] instanceof AnalyzeReader) { continue; } if (result && r instanceof MetamorphReader && readers[j] instanceof MetamorphTiffReader) { continue; } if (result && (readers[j] instanceof L2DReader) || ((r instanceof L2DReader) && (readers[j] instanceof GelReader) || readers[j] instanceof L2DReader)) { continue; } // ND2Reader is allowed to accept JPEG-2000 files if (result && r instanceof JPEG2000Reader && readers[j] instanceof ND2Reader) { continue; } if ((result && r instanceof APLReader && readers[j] instanceof SISReader) || (!result && r instanceof APLReader && readers[j] instanceof APLReader)) { continue; } // Prairie datasets can consist of OME-TIFF files with // extra metadata files, so it is acceptable for the OME-TIFF // reader to pick up TIFFs from a Prairie dataset if (result && r instanceof PrairieReader && readers[j] instanceof OMETiffReader) { continue; } if (result && r instanceof TrestleReader && (readers[j] instanceof JPEGReader || readers[j] instanceof PGMReader || readers[j] instanceof TiffDelegateReader)) { continue; } if (result && r instanceof HitachiReader) { continue; } if (!result && r instanceof VolocityReader && readers[j] instanceof VolocityReader) { continue; } if (!result && r instanceof InCellReader && readers[j] instanceof InCellReader && !used[i].toLowerCase().endsWith(".xdce")) { continue; } boolean expected = r == readers[j]; if (result != expected) { success = false; if (result) { msg = TestTools.shortClassName(readers[j]) + " flagged \"" + used[i] + "\" but so did " + TestTools.shortClassName(r); } else { msg = TestTools.shortClassName(readers[j]) + " skipped \"" + used[i] + "\""; } break; } } } } else { success = false; msg = "Reader " + r.getClass().getName() + " is not an ImageReader"; } } catch (Throwable t) { LOGGER.info("", t); success = false; } result(testName, success, msg); } /** * @testng.test groups = "config" */ public void writeConfigFile() { reader = new BufferedImageReader(new FileStitcher()); setupReader(); if (!initFile(false)) return; String file = reader.getCurrentFile(); LOGGER.info("Generating configuration: {}", file); try { File f = new File(new Location(file).getParent(), ".bioformats"); Configuration newConfig = new Configuration(reader, f.getAbsolutePath()); newConfig.saveToFile(); reader.close(); } catch (Throwable t) { LOGGER.info("", t); assert false; } } // -- Helper methods -- /** Sets up the current IFormatReader. */ private void setupReader() { reader.setNormalized(true); reader.setOriginalMetadataPopulated(true); reader.setMetadataFiltered(true); MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } reader.setMetadataStore(store); } /** Initializes the reader and configuration tree. */ private boolean initFile() { return initFile(true); } private boolean initFile(boolean removeDuplicateFiles) { if (skip) throw new SkipException(SKIP_MESSAGE); // initialize configuration tree if (config == null) { try { config = configTree.get(id); } catch (IOException e) { } } if (reader == null) { /* if (config.noStitching()) { reader = new BufferedImageReader(); } else { */ reader = new BufferedImageReader(new FileStitcher()); //} reader.setNormalized(true); reader.setMetadataFiltered(true); MetadataStore store = null; try { store = omexmlService.createOMEXMLMetadata(); } catch (ServiceException e) { LOGGER.warn("Could not parse OME-XML", e); } reader.setMetadataStore(store); } if (id.equals(reader.getCurrentFile())) return true; // already initialized // skip files that were already tested as part of another file's dataset int ndx = skipFiles.indexOf(id); if (ndx >= 0 && removeDuplicateFiles) { LOGGER.info("Skipping {}", id); skipFiles.remove(ndx); skip = true; throw new SkipException(SKIP_MESSAGE); } // only test for missing configuration *after* we have removed duplicates // this prevents failures for missing configuration of files that are on // the used files list for a different file (e.g. TIFFs in a Leica LEI // dataset) if (config == null && removeDuplicateFiles) { throw new RuntimeException(id + " not configured."); } LOGGER.info("Initializing {}: ", id); try { boolean reallyInMemory = false; if (inMemory) { HashMap<String, Object> idMap = Location.getIdMap(); idMap.clear(); Location.setIdMap(idMap); reallyInMemory = mapFile(id); } reader.setId(id); // remove used files String[] used = reader.getUsedFiles(); boolean base = false; for (int i=0; i<used.length; i++) { if (id.equals(used[i])) { base = true; continue; } skipFiles.add(used[i]); if (reallyInMemory) { mapFile(used[i]); } } boolean single = used.length == 1; if (single && base) LOGGER.info("OK"); else LOGGER.info("{} {}", used.length, single ? "file" : "files"); if (!base) { LOGGER.error("Used files list does not include base file"); } } catch (Throwable t) { LOGGER.error("", t); return false; } return true; } /** Outputs test result and generates appropriate assertion. */ private static void result(String testName, boolean success) { result(testName, success, null); } /** * Outputs test result with optional extra message * and generates appropriate assertion. */ private static void result(String testName, boolean success, String msg) { LOGGER.info("\t{}: {} ({})", new Object[] {testName, success ? "PASSED" : "FAILED", msg == null ? "" : msg}); if (msg == null) assert success; else assert success : msg; } private static boolean mapFile(String id) throws IOException { RandomAccessInputStream stream = new RandomAccessInputStream(id); Runtime rt = Runtime.getRuntime(); long maxMem = rt.freeMemory(); long length = stream.length(); if (length < Integer.MAX_VALUE && length < maxMem) { stream.close(); FileInputStream fis = new FileInputStream(id); FileChannel channel = fis.getChannel(); ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, length); ByteArrayHandle handle = new ByteArrayHandle(buf); Location.mapFile(id, handle); fis.close(); return true; } stream.close(); return false; } }
Fix isThisType tests for Bruker datasets.
components/test-suite/src/loci/tests/testng/FormatReaderTest.java
Fix isThisType tests for Bruker datasets.
Java
bsd-2-clause
b5030c5ab45f2fe4a0d5421dd42540f773d19bd8
0
malensek/sing
/* Copyright (c) 2013, Colorado State University All rights reserved. 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 holder 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. */ package io.sigpipe.sing.stat; import io.sigpipe.sing.serialization.ByteSerializable; import io.sigpipe.sing.serialization.SerializationInputStream; import io.sigpipe.sing.serialization.SerializationOutputStream; import java.io.IOException; import org.apache.commons.math3.distribution.TDistribution; import org.apache.commons.math3.util.FastMath; /** * Provides an online method for computing mean, variance, and standard * deviation. Based on "Note on a Method for Calculating Corrected Sums of * Squares and Products" by B. P. Welford. * * @author malensek */ public class RunningStatistics implements ByteSerializable { private long n; private double mean; private double M2; /* Initialize max/min to their respective opposite values: */ private double min = Double.MAX_VALUE; private double max = Double.MIN_VALUE; public static class WelchResult { /** T-statistic */ public double t; /** Two-tailed p-value */ public double p; public WelchResult(double t, double p) { this.t = t; this.p = p; } } /** * Creates an empty running statistics instance. */ public RunningStatistics() { } /** * Creates a copy of a {@link RunningStatistics} instance. */ public RunningStatistics(RunningStatistics that) { copyFrom(that); } /** * Create a new {@link RunningStatistics} instance by combining multiple * existing instances. */ public RunningStatistics(RunningStatistics... others) { if (others.length == 0) { return; } else if (others.length == 1) { copyFrom(others[0]); return; } /* Calculate new n */ for (RunningStatistics rs : others) { merge(rs); } } /** * Copies statistics from another RunningStatistics instance. */ private void copyFrom(RunningStatistics that) { this.n = that.n; this.mean = that.mean; this.M2 = that.M2; this.min = that.min; this.max = that.max; } public void merge(RunningStatistics that) { long newN = n + that.n; double delta = this.mean - that.mean; mean = (this.n * this.mean + that.n * that.mean) / newN; M2 = M2 + that.M2 + delta * delta * this.n * that.n / newN; n = newN; } /** * Creates a running statistics instance with an array of samples. * Samples are added to the statistics in order. */ public RunningStatistics(double... samples ) { for (double sample : samples) { put(sample); } } /** * Add multiple new samples to the running statistics. */ public void put(double... samples) { for (double sample : samples) { put(sample); } } /** * Add a new sample to the running statistics. */ public void put(double sample) { n++; double delta = sample - mean; mean = mean + delta / n; M2 = M2 + delta * (sample - mean); min = FastMath.min(this.min, sample); max = FastMath.max(this.max, sample); } /** * Removes a previously-added sample from the running statistics. WARNING: * give careful consideration when using this method. If a value is removed * that wasn't previously added, the statistics will be meaningless. * Additionally, if you're keeping track of previous additions, then it * might be worth evaluating whether a RunningStatistics instance is the * right thing to be using at all. Caveat emptor, etc, etc. */ public void remove(double sample) { if (n <= 1) { /* If we're removing the last sample, then just clear the stats. */ clear(); return; } double prevMean = (n * mean - sample) / (n - 1); M2 = M2 - (sample - mean) * (sample - prevMean); mean = prevMean; n--; } /** * Clears all values passed in, returning the RunningStatistics instance to * its original state. */ public void clear() { n = 0; mean = 0; M2 = 0; min = Double.MAX_VALUE; max = Double.MIN_VALUE; } /** * Calculates the current running mean for the values observed thus far. * * @return mean of all the samples observed thus far. */ public double mean() { return mean; } /** * Calculates the running sample variance. * * @return sample variance */ public double var() { return var(1.0); } /** * Calculates the population variance. * * @return population variance */ public double popVar() { return var(0.0); } /** * Calculates the running variance, given a bias adjustment. * * @param ddof delta degrees-of-freedom to use in the calculation. Use 1.0 * for the sample variance. * * @return variance */ public double var(double ddof) { if (n == 0) { return Double.NaN; } return M2 / (n - ddof); } /** * Calculates the standard deviation of the data observed thus far. * * @return sample standard deviation */ public double std() { return FastMath.sqrt(var()); } /** * Calculates the sample standard deviation of the data observed thus * far. * * @return population standard deviation */ public double popStd() { return FastMath.sqrt(popVar()); } /** * Calculates the standard deviation of the values observed thus far, given * a bias adjustment. * * @param ddof delta degrees-of-freedom to use in the calculation. * * @return standard deviation */ public double std(double ddof) { return FastMath.sqrt(var(ddof)); } /** * Retrieves the largest value seen thus far by this RunningStatistics * instance. */ public double max() { return this.max; } /** * Retrieves the smallest value seen thus far by this RunningStatistics * instance. */ public double min() { return this.min; } public double prob(double sample) { double norm = 1 / FastMath.sqrt(2 * FastMath.PI * this.var()); return norm * FastMath.exp((- FastMath.pow(sample - this.mean, 2)) / (2 * this.var())); } /** * Retrieves the number of samples submitted to the RunningStatistics * instance so far. * * @return number of samples */ public long n() { return n; } public static WelchResult welchT( RunningStatistics rs1, RunningStatistics rs2) { double vn1 = rs1.var() / rs1.n(); double vn2 = rs2.var() / rs2.n(); /* Calculate t */ double xbs = rs1.mean() - rs2.mean(); double t = xbs / FastMath.sqrt(vn1 + vn2); double vn12 = FastMath.pow(vn1, 2); double vn22 = FastMath.pow(vn2, 2); /* Calculate degrees of freedom */ double v = FastMath.pow(vn1 + vn2, 2) / ((vn12 / (rs1.n() - 1)) + (vn22 / (rs2.n() - 1))); if (v == Double.NaN) { v = 1; } TDistribution tdist = new TDistribution(v); double p = tdist.cumulativeProbability(t) * 2; return new WelchResult(t, p); } @Override public String toString() { String str = ""; str += "Number of Samples: " + n + System.lineSeparator(); str += "Mean: " + mean + System.lineSeparator(); str += "Variance: " + var() + System.lineSeparator(); str += "Std Dev: " + std() + System.lineSeparator(); str += "Min: " + min + System.lineSeparator(); str += "Max: " + max; return str; } @Deserialize public RunningStatistics(SerializationInputStream in) throws IOException { this.n = in.readLong(); this.mean = in.readDouble(); this.M2 = in.readDouble(); this.min = in.readDouble(); this.max = in.readDouble(); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeLong(n); out.writeDouble(mean); out.writeDouble(M2); out.writeDouble(min); out.writeDouble(max); } }
src/main/java/io/sigpipe/sing/stat/RunningStatistics.java
/* Copyright (c) 2013, Colorado State University All rights reserved. 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 holder 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. */ package io.sigpipe.sing.stat; import io.sigpipe.sing.serialization.ByteSerializable; import io.sigpipe.sing.serialization.SerializationInputStream; import io.sigpipe.sing.serialization.SerializationOutputStream; import java.io.IOException; import org.apache.commons.math3.distribution.TDistribution; import org.apache.commons.math3.util.FastMath; /** * Provides an online method for computing mean, variance, and standard * deviation. Based on "Note on a Method for Calculating Corrected Sums of * Squares and Products" by B. P. Welford. * * @author malensek */ public class RunningStatistics implements ByteSerializable { private long n; private double mean; private double M2; /* Initialize max/min to their respective opposite values: */ private double min = Double.MAX_VALUE; private double max = Double.MIN_VALUE; public static class WelchResult { /** T-statistic */ public double t; /** Two-tailed p-value */ public double p; public WelchResult(double t, double p) { this.t = t; this.p = p; } } /** * Creates an empty running statistics instance. */ public RunningStatistics() { } /** * Creates a copy of a {@link RunningStatistics} instance. */ public RunningStatistics(RunningStatistics that) { copyFrom(that); } /** * Create a new {@link RunningStatistics} instance by combining multiple * existing instances. */ public RunningStatistics(RunningStatistics... others) { if (others.length == 0) { return; } else if (others.length == 1) { copyFrom(others[0]); return; } /* Calculate new n */ for (RunningStatistics rs : others) { merge(rs); } } /** * Copies statistics from another RunningStatistics instance. */ private void copyFrom(RunningStatistics that) { this.n = that.n; this.mean = that.mean; this.M2 = that.M2; this.min = that.min; this.max = that.max; } public void merge(RunningStatistics that) { long newN = n + that.n; double delta = this.mean - that.mean; mean = (this.n * this.mean + that.n * that.mean) / newN; M2 = M2 + that.M2 + delta * delta * this.n * that.n / newN; n = newN; } /** * Creates a running statistics instance with an array of samples. * Samples are added to the statistics in order. */ public RunningStatistics(double... samples ) { for (double sample : samples) { put(sample); } } /** * Add multiple new samples to the running statistics. */ public void put(double... samples) { for (double sample : samples) { put(sample); } } /** * Add a new sample to the running statistics. */ public void put(double sample) { n++; double delta = sample - mean; mean = mean + delta / n; M2 = M2 + delta * (sample - mean); min = FastMath.min(this.min, sample); max = FastMath.max(this.max, sample); } /** * Removes a previously-added sample from the running statistics. WARNING: * give careful consideration when using this method. If a value is removed * that wasn't previously added, the statistics will be meaningless. * Additionally, if you're keeping track of previous additions, then it * might be worth evaluating whether a RunningStatistics instance is the * right thing to be using at all. Caveat emptor, etc, etc. */ public void remove(double sample) { if (n <= 1) { /* If we're removing the last sample, then just clear the stats. */ clear(); return; } double prevMean = (n * mean - sample) / (n - 1); M2 = M2 - (sample - mean) * (sample - prevMean); mean = prevMean; n--; } /** * Clears all values passed in, returning the RunningStatistics instance to * its original state. */ public void clear() { n = 0; mean = 0; M2 = 0; min = Double.MAX_VALUE; max = Double.MIN_VALUE; } /** * Calculates the current running mean for the values observed thus far. * * @return mean of all the samples observed thus far. */ public double mean() { return mean; } /** * Calculates the running sample variance. * * @return sample variance */ public double var() { return var(1.0); } /** * Calculates the population variance. * * @return population variance */ public double popVar() { return var(0.0); } /** * Calculates the running variance, given a bias adjustment. * * @param ddof delta degrees-of-freedom to use in the calculation. Use 1.0 * for the sample variance. * * @return variance */ public double var(double ddof) { if (n == 0) { return Double.NaN; } return M2 / (n - ddof); } /** * Calculates the standard deviation of the data observed thus far. * * @return sample standard deviation */ public double std() { return FastMath.sqrt(var()); } /** * Calculates the sample standard deviation of the data observed thus * far. * * @return population standard deviation */ public double popStd() { return FastMath.sqrt(popVar()); } /** * Calculates the standard deviation of the values observed thus far, given * a bias adjustment. * * @param ddof delta degrees-of-freedom to use in the calculation. * * @return standard deviation */ public double std(double ddof) { return FastMath.sqrt(var(ddof)); } /** * Retrieves the largest value seen thus far by this RunningStatistics * instance. */ public double max() { return this.max; } /** * Retrieves the smallest value seen thus far by this RunningStatistics * instance. */ public double min() { return this.min; } public double prob(double sample) { double norm = 1 / FastMath.sqrt(2 * FastMath.PI * this.var()); return norm * FastMath.exp((- FastMath.pow(sample - this.mean, 2)) / (2 * this.var())); } /** * Retrieves the number of samples submitted to the RunningStatistics * instance so far. * * @return number of samples */ public long n() { return n; } public static WelchResult welchT( RunningStatistics rs1, RunningStatistics rs2) { double vn1 = rs1.var() / rs1.n(); double vn2 = rs2.var() / rs2.n(); /* Calculate t */ double xbs = rs1.mean() - rs2.mean(); double t = xbs / FastMath.sqrt(vn1 + vn2); double vn12 = FastMath.pow(vn1, 2); double vn22 = FastMath.pow(vn2, 2); /* Calculate degrees of freedom */ double v = FastMath.pow(vn1 + vn2, 2) / ((vn12 / (rs1.n() - 1)) + (vn22 / (rs2.n() - 1))); if (v == Double.NaN) { v = 1; } TDistribution tdist = new TDistribution(v); double p = tdist.cumulativeProbability(t) * 2; return new WelchResult(t, p); } @Override public String toString() { String str = ""; str += "Number of Samples: " + n + System.lineSeparator(); str += "Mean: " + mean + System.lineSeparator(); str += "Variance: " + var() + System.lineSeparator(); str += "Std Dev: " + std() + System.lineSeparator(); str += "Min: " + min + System.lineSeparator(); str += "Max: " + max; return str; } @Deserialize public RunningStatistics(SerializationInputStream in) throws IOException { n = in.readLong(); mean = in.readDouble(); M2 = in.readDouble(); } @Override public void serialize(SerializationOutputStream out) throws IOException { out.writeLong(n); out.writeDouble(mean); out.writeDouble(M2); } }
Bugfix: min/max not serialized
src/main/java/io/sigpipe/sing/stat/RunningStatistics.java
Bugfix: min/max not serialized
Java
bsd-3-clause
487874f0373dbb77f78fd3d950bccdbc6fbf7d73
0
jnehlmeier/threetenbp,naixx/threetenbp,naixx/threetenbp,ThreeTen/threetenbp,ThreeTen/threetenbp,pepyakin/threetenbp,pepyakin/threetenbp,jnehlmeier/threetenbp
/* * Copyright (c) 2010, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * 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 OWNER 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. */ package javax.time.calendar; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.time.Duration; import org.testng.annotations.Test; /** * Test PeriodUnit. * * @author Stephen Colebourne */ @Test public class TestPeriodUnit { private static final int EQUIV1 = 30; private static final int EQUIV2 = 20; private static final PeriodUnit BASIC = basic("TestBasic", Duration.ofSeconds(1)); private static final PeriodUnit DERIVED1 = new PeriodUnit("TestDerived", EQUIV1, BASIC) { private static final long serialVersionUID = 1L; }; private static final PeriodUnit DERIVED2 = new PeriodUnit("TestDerivedDerived", EQUIV1 * EQUIV2, BASIC) { private static final long serialVersionUID = 1L; }; private static final PeriodUnit UNRELATED = basic("Unrelated", Duration.ofSeconds(4)); //----------------------------------------------------------------------- @Test(groups={"implementation"}) public void test_interfaces() { assertTrue(Comparable.class.isAssignableFrom(PeriodField.class)); assertTrue(Serializable.class.isAssignableFrom(PeriodField.class)); } //----------------------------------------------------------------------- // basic() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_factory_basic() { Duration dur = Duration.ofSeconds(EQUIV1); PeriodUnit test = basic("TestFactoryBasic1", dur); assertEquals(test.getBaseEquivalent(), test.field(1)); assertEquals(test.getName(), "TestFactoryBasic1"); assertEquals(test.toString(), "TestFactoryBasic1"); } @Test(groups={"implementation"}) public void test_factory_same() { Duration dur = Duration.ofSeconds(EQUIV1); PeriodUnit test = basic("TestFactoryBasic1", dur); assertSame(test.getBaseUnit(), test); assertSame(test.getDurationEstimate(), dur); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_basic_nullName() { basic(null, Duration.ofSeconds(EQUIV1)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_basic_nullDuration() { basic("TestFactoryBasic2", null); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void test_factory_basic_zeroDuration() { basic("TestFactoryBasic3", Duration.ZERO); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void test_factory_basic_negativeDuration() { basic("TestFactoryBasic3", Duration.ofNanos(-1)); } //----------------------------------------------------------------------- // derived() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_factory_derived() { PeriodField pf = PeriodField.of(EQUIV1, BASIC); PeriodUnit test = derived("TestFactoryDerived1", pf); assertEquals(test.getBaseEquivalent(), pf); assertEquals(test.getDurationEstimate(), Duration.ofSeconds(EQUIV1)); assertEquals(test.getName(), "TestFactoryDerived1"); assertEquals(test.toString(), "TestFactoryDerived1"); } @Test(groups={"implementation"}) public void test_factory_derived_same() { PeriodField pf = PeriodField.of(EQUIV1, BASIC); PeriodUnit test = derived("TestFactoryDerived1", pf); assertSame(test.getBaseUnit(), BASIC); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_derived_nullName() { derived(null, PeriodField.of(EQUIV1, BASIC)); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_factory_derived_nullPeriod() { derived("TestFactoryDerived2", null); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void test_factory_derived_zeroPeriod() { derived("TestFactoryDerived3", PeriodField.of(0, BASIC)); } @Test(expectedExceptions=IllegalArgumentException.class, groups={"tck"}) public void test_factory_derived_negativePeriod() { derived("TestFactoryDerived3", PeriodField.of(-1, BASIC)); } //----------------------------------------------------------------------- // serialization //----------------------------------------------------------------------- static class Basic extends PeriodUnit { static final Basic INSTANCE = new Basic(); private static final long serialVersionUID = 1L; Basic() { super("TestSerializationBasic", Duration.ofSeconds(EQUIV1)); } private Object readResolve() { return INSTANCE; } }; @Test(groups={"tck"}) public void test_serialization_basic() throws Exception { PeriodUnit original = Basic.INSTANCE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(original); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); PeriodUnit ser = (PeriodUnit) in.readObject(); assertSame(ser, original); } static class Derived extends PeriodUnit { static final Derived INSTANCE = new Derived(); private static final long serialVersionUID = 1L; Derived() { super("TestSerializationDerived", 40 * EQUIV1, BASIC); } private Object readResolve() { return INSTANCE; } }; @Test(groups={"tck"}) public void test_serialization_derived() throws Exception { PeriodUnit original = Derived.INSTANCE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(original); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); PeriodUnit ser = (PeriodUnit) in.readObject(); assertSame(ser, original); } //----------------------------------------------------------------------- // getBaseEquivalent() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_getBaseEquivalent() { assertEquals(BASIC.getBaseEquivalent(), BASIC.field(1)); assertEquals(DERIVED1.getBaseEquivalent(), BASIC.field(EQUIV1)); assertEquals(DERIVED2.getBaseEquivalent(), BASIC.field(EQUIV2 * EQUIV1)); } //----------------------------------------------------------------------- // getBaseUnit() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_getBaseUnit() { assertEquals(BASIC.getBaseUnit(), BASIC); assertEquals(DERIVED1.getBaseUnit(), BASIC); assertEquals(DERIVED2.getBaseUnit(), BASIC); } //----------------------------------------------------------------------- // getDurationEstimate() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_getDurationEstimate() { assertEquals(BASIC.getDurationEstimate(), Duration.ofSeconds(1)); assertEquals(DERIVED1.getDurationEstimate(), Duration.ofSeconds(EQUIV1)); } //----------------------------------------------------------------------- // toEquivalent(PeriodUnit) //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_getEquivalentPeriod_unit_basic() { assertEquals(BASIC.toEquivalent(BASIC), 1); assertEquals(BASIC.toEquivalent(DERIVED1), -1); assertEquals(BASIC.toEquivalent(DERIVED2), -1); } @Test(groups={"tck"}) public void test_getEquivalentPeriod_unit_derived() { assertEquals(DERIVED2.toEquivalent(BASIC), EQUIV2 * EQUIV1); assertEquals(DERIVED2.toEquivalent(DERIVED1), EQUIV2); assertEquals(DERIVED2.toEquivalent(DERIVED2), 1); assertEquals(DERIVED1.toEquivalent(DERIVED2), -1); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_getEquivalentPeriod_null() { BASIC.toEquivalent((PeriodUnit) null); } //----------------------------------------------------------------------- // convertEquivalent(PeriodField) //----------------------------------------------------------------------- @Test(groups={"implementation"}) public void test_convertEquivalent_PeriodField_same() { PeriodField field = BASIC.field(3); assertSame(BASIC.convertEquivalent(field), field); field = DERIVED1.field(-5); assertSame(DERIVED1.convertEquivalent(field), field); } @Test(groups={"tck"}) public void test_convertEquivalent_PeriodField_convertible() { assertEquals(BASIC.convertEquivalent(DERIVED1.field(4)), BASIC.field(4 * EQUIV1)); assertEquals(BASIC.convertEquivalent(DERIVED2.field(-5)), BASIC.field(-5 * EQUIV2 * EQUIV1)); } @Test(groups={"tck"}) public void test_convertEquivalent_PeriodField_notConvertible() { assertEquals(DERIVED1.convertEquivalent(BASIC.field(EQUIV1)), null); assertEquals(DERIVED2.convertEquivalent(BASIC.field(4)), null); assertEquals(UNRELATED.convertEquivalent(BASIC.field(4)), null); assertEquals(BASIC.convertEquivalent(UNRELATED.field(4)), null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_convertEquivalent_PeriodField_null() { BASIC.convertEquivalent((PeriodField) null); } //----------------------------------------------------------------------- // convertEquivalent(long,PeriodUnit) //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_convertEquivalent_PeriodUnit_same() { assertEquals(BASIC.convertEquivalent(3, BASIC), BASIC.field(3)); assertEquals(DERIVED1.convertEquivalent(-5, DERIVED1), DERIVED1.field(-5)); assertEquals(DERIVED2.convertEquivalent(12, DERIVED2), DERIVED2.field(12)); } @Test(groups={"tck"}) public void test_convertEquivalent_PeriodUnit_convertible() { assertEquals(BASIC.convertEquivalent(4, DERIVED1), BASIC.field(4 * EQUIV1)); assertEquals(BASIC.convertEquivalent(-5, DERIVED2), BASIC.field(-5 * EQUIV2 * EQUIV1)); } @Test(groups={"tck"}) public void test_convertEquivalent_PeriodUnit_notConvertible() { assertEquals(DERIVED1.convertEquivalent(EQUIV1, BASIC), null); assertEquals(DERIVED2.convertEquivalent(4, BASIC), null); assertEquals(UNRELATED.convertEquivalent(4, BASIC), null); assertEquals(BASIC.convertEquivalent(4, UNRELATED), null); } @Test(expectedExceptions=NullPointerException.class, groups={"tck"}) public void test_convertEquivalent_PeriodUnit_null() { BASIC.convertEquivalent(1, (PeriodUnit) null); } //----------------------------------------------------------------------- // field(long) //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_field() { assertEquals(BASIC.field(2), PeriodField.of(2, BASIC)); assertEquals(DERIVED1.field(-3517369), PeriodField.of(-3517369,DERIVED1)); } //----------------------------------------------------------------------- // compareTo() //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_compareTo_basic() { PeriodUnit test1 = basic("TestCompareTo1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestCompareTo2", Duration.ofSeconds(40)); assertEquals(test1.compareTo(test1), 0); assertEquals(test1.compareTo(test2), -1); assertEquals(test2.compareTo(test1), 1); } @Test(groups={"tck"}) public void test_compareTo_durationThenName() { PeriodUnit test1 = basic("TestCompareTo1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestCompareTo2", Duration.ofSeconds(EQUIV1)); PeriodUnit test3 = basic("TestCompareTo0", Duration.ofSeconds(40)); assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test1.compareTo(test3) < 0); assertTrue(test2.compareTo(test1) > 0); assertTrue(test2.compareTo(test3) < 0); assertTrue(test3.compareTo(test1) > 0); assertTrue(test3.compareTo(test2) > 0); } @Test(groups={"tck"}) public void test_compareTo_derived() { PeriodUnit test1 = DERIVED1; PeriodUnit test2 = DERIVED2; assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test2.compareTo(test1) > 0); } @Test(groups={"tck"}) public void test_compareTo_basicDerived() { PeriodUnit test1 = basic(DERIVED1.getName(), DERIVED1.getDurationEstimate()); PeriodUnit test2 = DERIVED1; assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test2.compareTo(test1) > 0); } @Test(expectedExceptions = {NullPointerException.class}, groups={"tck"}) public void test_compareTo_null() { PeriodUnit test5 = basic("TestCompareToNull", Duration.ofSeconds(EQUIV1)); test5.compareTo(null); } //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_equals_basicDerived() { PeriodUnit test1 = BASIC; PeriodUnit test2 = DERIVED1; PeriodUnit test3 = DERIVED2; PeriodUnit test4 = basic(DERIVED1.getName(), DERIVED1.getDurationEstimate()); assertEquals(test1.equals(test1), true); assertEquals(test1.equals(test2), false); assertEquals(test1.equals(test3), false); assertEquals(test1.equals(test4), false); assertEquals(test2.equals(test1), false); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test3), false); assertEquals(test2.equals(test4), false); assertEquals(test3.equals(test1), false); assertEquals(test3.equals(test2), false); assertEquals(test3.equals(test3), true); assertEquals(test3.equals(test4), false); assertEquals(test4.equals(test1), false); assertEquals(test4.equals(test2), false); assertEquals(test4.equals(test3), false); assertEquals(test4.equals(test4), true); } @Test(groups={"tck"}) public void test_equals_nameDuration() { PeriodUnit test1 = basic("TestEquals1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestEquals2", Duration.ofSeconds(EQUIV1)); PeriodUnit test3 = basic("TestEquals2", Duration.ofSeconds(40)); assertEquals(test1.equals(test1), true); assertEquals(test1.equals(test2), false); assertEquals(test1.equals(test3), false); assertEquals(test2.equals(test1), false); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test3), false); assertEquals(test3.equals(test1), false); assertEquals(test3.equals(test2), false); assertEquals(test3.equals(test3), true); } @Test(groups={"tck"}) public void test_equals_null() { PeriodUnit test = basic("TestEqualsNull", Duration.ofSeconds(EQUIV1)); assertEquals(false, test.equals(null)); } @Test(groups={"tck"}) public void test_equals_otherClass() { PeriodUnit test = basic("TestEqualsOther", Duration.ofSeconds(EQUIV1)); assertEquals(false, test.equals("")); } //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_hashCode() { PeriodUnit test1 = basic("TestHashCode", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestHashCode", Duration.ofSeconds(40)); assertEquals(test1.hashCode() == test1.hashCode(), true); assertEquals(test1.hashCode() == test2.hashCode(), false); } //----------------------------------------------------------------------- @Test(groups={"tck"}) public void test_toString() { PeriodUnit test = basic("TestToString", Duration.ofSeconds(EQUIV1)); assertEquals(test.toString(), "TestToString"); } //----------------------------------------------------------------------- private static PeriodUnit basic(String name, Duration duration) { return new PeriodUnit(name, duration) { private static final long serialVersionUID = 1L; }; } private static PeriodUnit derived(String name, PeriodField period) { return new PeriodUnit(name, period.getAmount(), period.getUnit()) { private static final long serialVersionUID = 1L; }; } }
src/test/java/javax/time/calendar/TestPeriodUnit.java
/* * Copyright (c) 2010, Stephen Colebourne & Michael Nascimento Santos * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * 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. * * * Neither the name of JSR-310 nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * 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 OWNER 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. */ package javax.time.calendar; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.time.Duration; import org.testng.annotations.Test; /** * Test PeriodUnit. * * @author Stephen Colebourne */ @Test public class TestPeriodUnit { private static final int EQUIV1 = 30; private static final int EQUIV2 = 20; private static final PeriodUnit BASIC = basic("TestBasic", Duration.ofSeconds(1)); private static final PeriodUnit DERIVED1 = new PeriodUnit("TestDerived", EQUIV1, BASIC) { private static final long serialVersionUID = 1L; }; private static final PeriodUnit DERIVED2 = new PeriodUnit("TestDerivedDerived", EQUIV1 * EQUIV2, BASIC) { private static final long serialVersionUID = 1L; }; private static final PeriodUnit UNRELATED = basic("Unrelated", Duration.ofSeconds(4)); //----------------------------------------------------------------------- public void test_interfaces() { assertTrue(Comparable.class.isAssignableFrom(PeriodField.class)); assertTrue(Serializable.class.isAssignableFrom(PeriodField.class)); } //----------------------------------------------------------------------- // basic() //----------------------------------------------------------------------- public void test_factory_basic() { Duration dur = Duration.ofSeconds(EQUIV1); PeriodUnit test = basic("TestFactoryBasic1", dur); assertSame(test.getBaseUnit(), test); assertEquals(test.getBaseEquivalent(), test.field(1)); assertSame(test.getDurationEstimate(), dur); assertEquals(test.getName(), "TestFactoryBasic1"); assertEquals(test.toString(), "TestFactoryBasic1"); } @Test(expectedExceptions=NullPointerException.class) public void test_factory_basic_nullName() { basic(null, Duration.ofSeconds(EQUIV1)); } @Test(expectedExceptions=NullPointerException.class) public void test_factory_basic_nullDuration() { basic("TestFactoryBasic2", null); } @Test(expectedExceptions=IllegalArgumentException.class) public void test_factory_basic_zeroDuration() { basic("TestFactoryBasic3", Duration.ZERO); } @Test(expectedExceptions=IllegalArgumentException.class) public void test_factory_basic_negativeDuration() { basic("TestFactoryBasic3", Duration.ofNanos(-1)); } //----------------------------------------------------------------------- // derived() //----------------------------------------------------------------------- public void test_factory_derived() { PeriodField pf = PeriodField.of(EQUIV1, BASIC); PeriodUnit test = derived("TestFactoryDerived1", pf); assertSame(test.getBaseUnit(), BASIC); assertEquals(test.getBaseEquivalent(), pf); assertEquals(test.getDurationEstimate(), Duration.ofSeconds(EQUIV1)); assertEquals(test.getName(), "TestFactoryDerived1"); assertEquals(test.toString(), "TestFactoryDerived1"); } @Test(expectedExceptions=NullPointerException.class) public void test_factory_derived_nullName() { derived(null, PeriodField.of(EQUIV1, BASIC)); } @Test(expectedExceptions=NullPointerException.class) public void test_factory_derived_nullPeriod() { derived("TestFactoryDerived2", null); } @Test(expectedExceptions=IllegalArgumentException.class) public void test_factory_derived_zeroPeriod() { derived("TestFactoryDerived3", PeriodField.of(0, BASIC)); } @Test(expectedExceptions=IllegalArgumentException.class) public void test_factory_derived_negativePeriod() { derived("TestFactoryDerived3", PeriodField.of(-1, BASIC)); } //----------------------------------------------------------------------- // serialization //----------------------------------------------------------------------- static class Basic extends PeriodUnit { static final Basic INSTANCE = new Basic(); private static final long serialVersionUID = 1L; Basic() { super("TestSerializationBasic", Duration.ofSeconds(EQUIV1)); } private Object readResolve() { return INSTANCE; } }; public void test_serialization_basic() throws Exception { PeriodUnit original = Basic.INSTANCE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(original); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); PeriodUnit ser = (PeriodUnit) in.readObject(); assertSame(ser, original); } static class Derived extends PeriodUnit { static final Derived INSTANCE = new Derived(); private static final long serialVersionUID = 1L; Derived() { super("TestSerializationDerived", 40 * EQUIV1, BASIC); } private Object readResolve() { return INSTANCE; } }; public void test_serialization_derived() throws Exception { PeriodUnit original = Derived.INSTANCE; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(original); out.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bais); PeriodUnit ser = (PeriodUnit) in.readObject(); assertSame(ser, original); } //----------------------------------------------------------------------- // getBaseEquivalent() //----------------------------------------------------------------------- public void test_getBaseEquivalent() { assertEquals(BASIC.getBaseEquivalent(), BASIC.field(1)); assertEquals(DERIVED1.getBaseEquivalent(), BASIC.field(EQUIV1)); assertEquals(DERIVED2.getBaseEquivalent(), BASIC.field(EQUIV2 * EQUIV1)); } //----------------------------------------------------------------------- // getBaseUnit() //----------------------------------------------------------------------- public void test_getBaseUnit() { assertEquals(BASIC.getBaseUnit(), BASIC); assertEquals(DERIVED1.getBaseUnit(), BASIC); assertEquals(DERIVED2.getBaseUnit(), BASIC); } //----------------------------------------------------------------------- // getDurationEstimate() //----------------------------------------------------------------------- public void test_getDurationEstimate() { assertEquals(BASIC.getDurationEstimate(), Duration.ofSeconds(1)); assertEquals(DERIVED1.getDurationEstimate(), Duration.ofSeconds(EQUIV1)); } //----------------------------------------------------------------------- // toEquivalent(PeriodUnit) //----------------------------------------------------------------------- public void test_getEquivalentPeriod_unit_basic() { assertEquals(BASIC.toEquivalent(BASIC), 1); assertEquals(BASIC.toEquivalent(DERIVED1), -1); assertEquals(BASIC.toEquivalent(DERIVED2), -1); } public void test_getEquivalentPeriod_unit_derived() { assertEquals(DERIVED2.toEquivalent(BASIC), EQUIV2 * EQUIV1); assertEquals(DERIVED2.toEquivalent(DERIVED1), EQUIV2); assertEquals(DERIVED2.toEquivalent(DERIVED2), 1); assertEquals(DERIVED1.toEquivalent(DERIVED2), -1); } @Test(expectedExceptions=NullPointerException.class) public void test_getEquivalentPeriod_null() { BASIC.toEquivalent((PeriodUnit) null); } //----------------------------------------------------------------------- // convertEquivalent(PeriodField) //----------------------------------------------------------------------- public void test_convertEquivalent_PeriodField_same() { PeriodField field = BASIC.field(3); assertSame(BASIC.convertEquivalent(field), field); field = DERIVED1.field(-5); assertSame(DERIVED1.convertEquivalent(field), field); } public void test_convertEquivalent_PeriodField_convertible() { assertEquals(BASIC.convertEquivalent(DERIVED1.field(4)), BASIC.field(4 * EQUIV1)); assertEquals(BASIC.convertEquivalent(DERIVED2.field(-5)), BASIC.field(-5 * EQUIV2 * EQUIV1)); } public void test_convertEquivalent_PeriodField_notConvertible() { assertEquals(DERIVED1.convertEquivalent(BASIC.field(EQUIV1)), null); assertEquals(DERIVED2.convertEquivalent(BASIC.field(4)), null); assertEquals(UNRELATED.convertEquivalent(BASIC.field(4)), null); assertEquals(BASIC.convertEquivalent(UNRELATED.field(4)), null); } @Test(expectedExceptions=NullPointerException.class) public void test_convertEquivalent_PeriodField_null() { BASIC.convertEquivalent((PeriodField) null); } //----------------------------------------------------------------------- // convertEquivalent(long,PeriodUnit) //----------------------------------------------------------------------- public void test_convertEquivalent_PeriodUnit_same() { assertEquals(BASIC.convertEquivalent(3, BASIC), BASIC.field(3)); assertEquals(DERIVED1.convertEquivalent(-5, DERIVED1), DERIVED1.field(-5)); assertEquals(DERIVED2.convertEquivalent(12, DERIVED2), DERIVED2.field(12)); } public void test_convertEquivalent_PeriodUnit_convertible() { assertEquals(BASIC.convertEquivalent(4, DERIVED1), BASIC.field(4 * EQUIV1)); assertEquals(BASIC.convertEquivalent(-5, DERIVED2), BASIC.field(-5 * EQUIV2 * EQUIV1)); } public void test_convertEquivalent_PeriodUnit_notConvertible() { assertEquals(DERIVED1.convertEquivalent(EQUIV1, BASIC), null); assertEquals(DERIVED2.convertEquivalent(4, BASIC), null); assertEquals(UNRELATED.convertEquivalent(4, BASIC), null); assertEquals(BASIC.convertEquivalent(4, UNRELATED), null); } @Test(expectedExceptions=NullPointerException.class) public void test_convertEquivalent_PeriodUnit_null() { BASIC.convertEquivalent(1, (PeriodUnit) null); } //----------------------------------------------------------------------- // field(long) //----------------------------------------------------------------------- public void test_field() { assertEquals(BASIC.field(2), PeriodField.of(2, BASIC)); assertEquals(DERIVED1.field(-3517369), PeriodField.of(-3517369,DERIVED1)); } //----------------------------------------------------------------------- // compareTo() //----------------------------------------------------------------------- public void test_compareTo_basic() { PeriodUnit test1 = basic("TestCompareTo1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestCompareTo2", Duration.ofSeconds(40)); assertEquals(test1.compareTo(test1), 0); assertEquals(test1.compareTo(test2), -1); assertEquals(test2.compareTo(test1), 1); } public void test_compareTo_durationThenName() { PeriodUnit test1 = basic("TestCompareTo1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestCompareTo2", Duration.ofSeconds(EQUIV1)); PeriodUnit test3 = basic("TestCompareTo0", Duration.ofSeconds(40)); assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test1.compareTo(test3) < 0); assertTrue(test2.compareTo(test1) > 0); assertTrue(test2.compareTo(test3) < 0); assertTrue(test3.compareTo(test1) > 0); assertTrue(test3.compareTo(test2) > 0); } public void test_compareTo_derived() { PeriodUnit test1 = DERIVED1; PeriodUnit test2 = DERIVED2; assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test2.compareTo(test1) > 0); } public void test_compareTo_basicDerived() { PeriodUnit test1 = basic(DERIVED1.getName(), DERIVED1.getDurationEstimate()); PeriodUnit test2 = DERIVED1; assertEquals(test1.compareTo(test1), 0); assertTrue(test1.compareTo(test2) < 0); assertTrue(test2.compareTo(test1) > 0); } @Test(expectedExceptions = {NullPointerException.class}) public void test_compareTo_null() { PeriodUnit test5 = basic("TestCompareToNull", Duration.ofSeconds(EQUIV1)); test5.compareTo(null); } //----------------------------------------------------------------------- public void test_equals_basicDerived() { PeriodUnit test1 = BASIC; PeriodUnit test2 = DERIVED1; PeriodUnit test3 = DERIVED2; PeriodUnit test4 = basic(DERIVED1.getName(), DERIVED1.getDurationEstimate()); assertEquals(test1.equals(test1), true); assertEquals(test1.equals(test2), false); assertEquals(test1.equals(test3), false); assertEquals(test1.equals(test4), false); assertEquals(test2.equals(test1), false); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test3), false); assertEquals(test2.equals(test4), false); assertEquals(test3.equals(test1), false); assertEquals(test3.equals(test2), false); assertEquals(test3.equals(test3), true); assertEquals(test3.equals(test4), false); assertEquals(test4.equals(test1), false); assertEquals(test4.equals(test2), false); assertEquals(test4.equals(test3), false); assertEquals(test4.equals(test4), true); } public void test_equals_nameDuration() { PeriodUnit test1 = basic("TestEquals1", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestEquals2", Duration.ofSeconds(EQUIV1)); PeriodUnit test3 = basic("TestEquals2", Duration.ofSeconds(40)); assertEquals(test1.equals(test1), true); assertEquals(test1.equals(test2), false); assertEquals(test1.equals(test3), false); assertEquals(test2.equals(test1), false); assertEquals(test2.equals(test2), true); assertEquals(test2.equals(test3), false); assertEquals(test3.equals(test1), false); assertEquals(test3.equals(test2), false); assertEquals(test3.equals(test3), true); } public void test_equals_null() { PeriodUnit test = basic("TestEqualsNull", Duration.ofSeconds(EQUIV1)); assertEquals(false, test.equals(null)); } public void test_equals_otherClass() { PeriodUnit test = basic("TestEqualsOther", Duration.ofSeconds(EQUIV1)); assertEquals(false, test.equals("")); } //----------------------------------------------------------------------- public void test_hashCode() { PeriodUnit test1 = basic("TestHashCode", Duration.ofSeconds(EQUIV1)); PeriodUnit test2 = basic("TestHashCode", Duration.ofSeconds(40)); assertEquals(test1.hashCode() == test1.hashCode(), true); assertEquals(test1.hashCode() == test2.hashCode(), false); } //----------------------------------------------------------------------- public void test_toString() { PeriodUnit test = basic("TestToString", Duration.ofSeconds(EQUIV1)); assertEquals(test.toString(), "TestToString"); } //----------------------------------------------------------------------- private static PeriodUnit basic(String name, Duration duration) { return new PeriodUnit(name, duration) { private static final long serialVersionUID = 1L; }; } private static PeriodUnit derived(String name, PeriodField period) { return new PeriodUnit(name, period.getAmount(), period.getUnit()) { private static final long serialVersionUID = 1L; }; } }
annotates TestPeriodUnit
src/test/java/javax/time/calendar/TestPeriodUnit.java
annotates TestPeriodUnit
Java
bsd-3-clause
b7dc478dcfc83217b49d219818b23872c4d4428a
0
martiner/gooddata-java,liry/gooddata-java,standevgd/gooddata-java
/* * Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. */ package com.gooddata; import com.gooddata.account.AccountService; import com.gooddata.dataset.DatasetService; import com.gooddata.gdc.DataStoreService; import com.gooddata.gdc.GdcService; import com.gooddata.http.client.GoodDataHttpClient; import com.gooddata.http.client.LoginSSTRetrievalStrategy; import com.gooddata.http.client.SSTRetrievalStrategy; import com.gooddata.md.MetadataService; import com.gooddata.model.ModelService; import com.gooddata.project.ProjectService; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import static java.util.Collections.singletonMap; /** */ public class GoodData { private static final String PROTOCOL = "https"; private static final int PORT = 443; private static final String HOSTNAME = "secure.gooddata.com"; private final RestTemplate restTemplate; private final HttpClientBuilder httpClientBuilder; private final String login; private final String password; private AccountService accountService; private ProjectService projectService; private MetadataService metadataService; private ModelService modelService; private GdcService gdcService; private DataStoreService dataStoreService; private DatasetService datasetService; public GoodData(String login, String password) { this(login, password, HOSTNAME); } public GoodData(String hostname, String login, String password) { this.login = login; this.password = password; final HttpHost host = new HttpHost(hostname, PORT, PROTOCOL); httpClientBuilder = HttpClientBuilder.create(); final CloseableHttpClient httpClient = httpClientBuilder.build(); final SSTRetrievalStrategy strategy = new LoginSSTRetrievalStrategy(httpClient, host, login, password); final HttpClient client = new GoodDataHttpClient(httpClient, strategy); final UriPrefixingClientHttpRequestFactory factory = new UriPrefixingClientHttpRequestFactory( new HttpComponentsClientHttpRequestFactory(client), hostname, PORT, PROTOCOL); restTemplate = new RestTemplate(factory); restTemplate.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList( new HeaderAddingRequestInterceptor(singletonMap("Accept", MediaType.APPLICATION_JSON_VALUE)))); initServices(); } public void logout() { getAccountService().logout(); } public ProjectService getProjectService() { return projectService; } public AccountService getAccountService() { return accountService; } public MetadataService getMetadataService() { return metadataService; } public ModelService getModelService() { return modelService; } public GdcService getGdcService() { return gdcService; } public DataStoreService getDataStoreService() { return dataStoreService; } public DatasetService getDatasetService() { return datasetService; } private void initServices() { accountService = new AccountService(restTemplate); projectService = new ProjectService(restTemplate, getAccountService()); metadataService = new MetadataService(restTemplate); modelService = new ModelService(restTemplate); gdcService = new GdcService(restTemplate); dataStoreService = new DataStoreService(httpClientBuilder, getGdcService(), login, password); datasetService = new DatasetService(restTemplate, getDataStoreService()); } }
src/main/java/com/gooddata/GoodData.java
/* * Copyright (C) 2007-2014, GoodData(R) Corporation. All rights reserved. */ package com.gooddata; import com.gooddata.account.AccountService; import com.gooddata.dataset.DatasetService; import com.gooddata.gdc.DataStoreService; import com.gooddata.gdc.GdcService; import com.gooddata.http.client.GoodDataHttpClient; import com.gooddata.http.client.LoginSSTRetrievalStrategy; import com.gooddata.http.client.SSTRetrievalStrategy; import com.gooddata.md.MetadataService; import com.gooddata.model.ModelService; import com.gooddata.project.ProjectService; import org.apache.http.HttpHost; import org.apache.http.client.HttpClient; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.http.MediaType; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import static java.util.Collections.singletonMap; /** */ public class GoodData { private static final String PROTOCOL = "https"; private static final int PORT = 443; private static final String HOSTNAME = "secure.gooddata.com"; private final RestTemplate restTemplate; private final HttpClientBuilder httpClientBuilder; private final String login; private final String password; public GoodData(String login, String password) { this(login, password, HOSTNAME); } public GoodData(String hostname, String login, String password) { this.login = login; this.password = password; final HttpHost host = new HttpHost(hostname, PORT, PROTOCOL); httpClientBuilder = HttpClientBuilder.create(); final CloseableHttpClient httpClient = httpClientBuilder.build(); final SSTRetrievalStrategy strategy = new LoginSSTRetrievalStrategy(httpClient, host, login, password); final HttpClient client = new GoodDataHttpClient(httpClient, strategy); final UriPrefixingClientHttpRequestFactory factory = new UriPrefixingClientHttpRequestFactory( new HttpComponentsClientHttpRequestFactory(client), hostname, PORT, PROTOCOL); restTemplate = new RestTemplate(factory); restTemplate.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList( new HeaderAddingRequestInterceptor(singletonMap("Accept", MediaType.APPLICATION_JSON_VALUE)))); } public void logout() { getAccountService().logout(); } public ProjectService getProjectService() { return new ProjectService(restTemplate, getAccountService()); } public AccountService getAccountService() { return new AccountService(restTemplate); } public MetadataService getMetadataService() { return new MetadataService(restTemplate); } public ModelService getModelService() { return new ModelService(restTemplate); } public GdcService getGdcService() { return new GdcService(restTemplate); } public DataStoreService getDataStoreService() { return new DataStoreService(httpClientBuilder, getGdcService(), login, password); } public DatasetService getDatasetService() { return new DatasetService(restTemplate, getDataStoreService()); } }
initialize services only once
src/main/java/com/gooddata/GoodData.java
initialize services only once
Java
mit
67ce31f5e72b8e27948a4efe942012c8f572ecba
0
afzafri/Students-DB-Android-App
package com.afifzafri.studentsdb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Afif on 28/10/2017. */ public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "StudentsDB.db"; public static final String TABLE_NAME = "students"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_IC = "ic"; public static final String COLUMN_DOB = "dob"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_PROGRAM = "program"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_EMAIL = "email"; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table " + TABLE_NAME + " ("+COLUMN_ID+" text primary key, " +COLUMN_NAME+ " text," +COLUMN_IC+" text," +COLUMN_DOB+" text," +COLUMN_ADDRESS+" text," +COLUMN_PROGRAM+" text," +COLUMN_PHONE+" text," +COLUMN_EMAIL+" text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } // function for insert data into db public boolean insertData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); // open db for writing ContentValues contentValues = new ContentValues(); contentValues.put("_id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.insert(TABLE_NAME, null, contentValues); return true; } // function to select data for list public Cursor listAllData () { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("select "+COLUMN_ID+", "+COLUMN_NAME+", "+COLUMN_ID+" from "+TABLE_NAME, null); return cursor; } // function for search data public Cursor searchData (String searchInput) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery( "select * from "+TABLE_NAME+" where _id = '"+searchInput+ "' or name LIKE '%"+searchInput+"%'", null ); return cursor; } // function for update data public boolean updateData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("_id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.update(TABLE_NAME, contentValues, "_id = ? ", new String[] {id} ); return true; } // function for delete data public boolean deleteData (String id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_NAME, "_id = ? ", new String[] {id} ); return true; } }
app/src/main/java/com/afifzafri/studentsdb/DBHelper.java
package com.afifzafri.studentsdb; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Afif on 28/10/2017. */ public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "StudentsDB.db"; public static final String TABLE_NAME = "students"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_IC = "ic"; public static final String COLUMN_DOB = "dob"; public static final String COLUMN_ADDRESS = "address"; public static final String COLUMN_PROGRAM = "program"; public static final String COLUMN_PHONE = "phone"; public static final String COLUMN_EMAIL = "email"; public DBHelper(Context context) { super(context, DATABASE_NAME , null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL( "create table " + TABLE_NAME + " ("+COLUMN_ID+" text primary key, " +COLUMN_NAME+ " text," +COLUMN_IC+" text," +COLUMN_DOB+" text," +COLUMN_ADDRESS+" text," +COLUMN_PROGRAM+" text," +COLUMN_PHONE+" text," +COLUMN_EMAIL+" text)" ); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } // function for insert data into db public boolean insertData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); // open db for writing ContentValues contentValues = new ContentValues(); contentValues.put("id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.insert(TABLE_NAME, null, contentValues); return true; } // function to select data for list public Cursor listAllData () { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("select "+COLUMN_NAME+", "+COLUMN_ID+" from "+TABLE_NAME, null); return cursor; } // function for search data public Cursor searchData (String searchInput) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery( "select * from "+TABLE_NAME+" where id = '"+searchInput+ "' or name LIKE '%"+searchInput+"%'", null ); return cursor; } // function for update data public boolean updateData (String id, String name, String ic, String dob, String address, String program, String phone, String email) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("id", id); contentValues.put("name", name); contentValues.put("ic", ic); contentValues.put("dob", dob); contentValues.put("address", address); contentValues.put("program", program); contentValues.put("phone", phone); contentValues.put("email", email); db.update(TABLE_NAME, contentValues, "id = ? ", new String[] {id} ); return true; } // function for delete data public boolean deleteData (String id) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_NAME, "id = ? ", new String[] {id} ); return true; } }
change id column name, for using Cursor Adapter
app/src/main/java/com/afifzafri/studentsdb/DBHelper.java
change id column name, for using Cursor Adapter
Java
mit
509f6d8c517c77ffaf120495aaf969dafbdef3df
0
Helltar/ANPASIDE,Helltar/ANPASIDE
package com.github.helltar.anpaside; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.Spanned; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.webkit.MimeTypeMap; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import com.github.helltar.anpaside.MainActivity; import com.github.helltar.anpaside.editor.CodeEditor; import com.github.helltar.anpaside.editor.EditorConfig; import com.github.helltar.anpaside.ide.IdeConfig; import com.github.helltar.anpaside.ide.IdeInit; import com.github.helltar.anpaside.logging.Logger; import com.github.helltar.anpaside.project.ProjectBuilder; import com.github.helltar.anpaside.project.ProjectManager; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import static com.github.helltar.anpaside.Consts.*; import static com.github.helltar.anpaside.logging.Logger.*; public class MainActivity extends AppCompatActivity { private CodeEditor editor; private EditorConfig editorConfig; private IdeConfig ideConfig; private ProjectManager pman; private static TextView tvLog; private static ScrollView svLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); editor = new CodeEditor(this, tabHost); tvLog = (TextView) findViewById(R.id.tvLog); svLog = (ScrollView) findViewById(R.id.svLog); ideConfig = new IdeConfig(this); editorConfig = new EditorConfig(this); init(); } private void init() { if (ideConfig.isAssetsInstall()) { Logger.addLog(getString(R.string.app_name) + " " + getAppVersionName()); } else { new Install().execute(); } String lastFilename = editorConfig.getLastFilename(); if (!(lastFilename.isEmpty())) { openFile(lastFilename); } String lastProject = editorConfig.getLastProject(); if (!(lastProject.isEmpty())) { openProject(lastProject); } } public static void addGuiLog(final String msg, final LogMsgType msgType) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { String fontColor = "#aaaaaa"; switch (msgType) { case lmtText: fontColor = "#00aa00"; break; case lmtError: fontColor = "#ee0000"; break; } String currentTime = new SimpleDateFormat("[HH:mm:ss]: ").format(new Date()); Spanned text = Html.fromHtml(currentTime + "<font color='" + fontColor + "'>" + msg.replace("\n", "<br>") + "</font><br>"); tvLog.append(text); svLog.fullScroll(ScrollView.FOCUS_DOWN); } }); } private void showOpenFileDialog() { Intent intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("file/*"); startActivityForResult(intent, 1); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data != null) { openFile(data.getData().getPath()); } } private void createProject(String path, String name) { if (pman.createProject(path, name)) { openProject(path + name + "/" + name + EXT_PROJ); } } private void createModule(String filename) { if (pman.createModule(filename)) { openFile(filename); } } private void openProject(String filename) { if (pman.openProject(filename)) { openFile(pman.getMainModuleFilename()); editorConfig.setLastProject(filename); } } private void openFile(String filename) { // TODO: ! if (FilenameUtils.getExtension(filename).equals(EXT_PROJ.substring(1, EXT_PROJ.length()))) { openProject(filename); } else { editor.openFile(filename); } editorConfig.setLastFilename(filename); } private void showNewProjectDialog() { final EditText edtProjectName = new EditText(this); edtProjectName.setHint(R.string.dlg_hint_project_name); new AlertDialog.Builder(this) .setTitle(R.string.dlg_title_new_project) .setMessage(R.string.dlg_subtitle_new_project) .setView(edtProjectName) .setPositiveButton(R.string.dlg_btn_create, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String projName = edtProjectName.getText().toString(); if (projName.length() < 3) { showAlertMsg("ะะตะฒะตั€ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต", "ะะฐะทะฒะฐะฝะธะต ะฟั€ะพะตะบั‚ะฐ ะดะพะปะถะฝะพ ัะพัั‚ะพัั‚ัŒ ะผะธะฝะธะผัƒะผ ะธะท 3-ั… ัะธะผะฒะพะปะพะฒ"); return; } String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; final String path = sdcardPath + DIR_MAIN; final File projPath = new File(path + projName); if (!(projPath.exists())) { createProject(path, projName); } else { new AlertDialog.Builder(MainActivity.this) .setMessage("ะŸั€ะพะตะบั‚ ัƒะถะต ััƒั‰ะตัั‚ะฒัƒะตั‚") .setPositiveButton("ะŸะตั€ะตะทะฐะฟะธัะฐั‚ัŒ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { FileUtils.deleteDirectory(projPath); createProject(path, projName); } catch (IOException ioe) { Logger.addLog(ioe); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } private void showNewModuleDialog() { final EditText edtModuleName = new EditText(this); edtModuleName.setHint(R.string.dlg_hint_module_name); new AlertDialog.Builder(this) .setTitle(R.string.dlg_title_new_module) .setView(edtModuleName) .setPositiveButton(R.string.dlg_btn_create, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String moduleName = edtModuleName.getText().toString(); if (moduleName.length() < 3) { showAlertMsg("ะะตะฒะตั€ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต", "ะะฐะทะฒะฐะฝะธะต ะผะพะดัƒะปั ะดะพะปะถะฝะพ ัะพัั‚ะพัั‚ัŒ ะผะธะฝะธะผัƒะผ ะธะท 3-ั… ัะธะผะฒะพะปะพะฒ"); return; } // TODO: ะดัƒะฑะปะธั€ะพะฒะฐะฝะธะต, (String) -> File final String filename = pman.getCurrentProjectPath() + DIR_SRC + moduleName + EXT_PAS; final File f = new File(filename); if (!(f.exists())) { createModule(filename); } else { new AlertDialog.Builder(MainActivity.this) .setMessage("ะœะพะดัƒะปัŒ ั ั‚ะฐะบะธะผ ะธะผะตะฝะตะผ ัƒะถะต ััƒั‰ะตัั‚ะฒัƒะตั‚") .setPositiveButton("ะŸะตั€ะตะทะฐะฟะธัะฐั‚ัŒ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (f.delete()) { createModule(filename); } else { Logger.addLog("ะžัˆะธะฑะบะฐ ะฟั€ะธ ัƒะดะฐะปะตะฝะธะธ ัั‚ะฐั€ะพะณะพ ะผะพะดัƒะปั: " + filename); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } private void showAlertMsg(String msg) { showAlertMsg("", msg); } private void showAlertMsg(String title, String msg) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(msg) .setNegativeButton("ะžะš", null) .show(); } private void showToastMsg(String msg) { Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } private String getAppVersionName() { try { return getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { return "null"; } } private void saveCurrentFile() { if (editor.isCurrentFileModified()) { if (editor.saveCurrentFile()) { showToastMsg("ะกะพั…ั€ะฐะฝะตะฝะพ"); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_TAB: EditText e = editor.getCurrentEditor(); e.getText().insert(e.getSelectionStart(), " "); return true; case KeyEvent.KEYCODE_S: if (event.isCtrlPressed()) { saveCurrentFile(); } return true; default: return super.onKeyDown(keyCode, event); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.miCreateModule).setEnabled(pman.isProjectOpen()); menu.findItem(R.id.miFileSave).setEnabled(editor.isCurrentFileModified()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.miRun: if (pman.isProjectOpen()) { if (editor.saveCurrentFile()) { new BuildProj().execute(); } } else { showToastMsg("ะะตั‚ ะพั‚ะบั€ั‹ั‚ะพะณะพ ะฟั€ะพะตะบั‚ะฐ"); } return true; case R.id.miCreateProject: showNewProjectDialog(); return true; case R.id.miCreateModule: showNewModuleDialog(); return true; case R.id.miFileOpen: showOpenFileDialog(); return true; case R.id.miFileSave: saveCurrentFile(); return true; case R.id.miAbout: showAlertMsg(getString(R.string.about_text)); return true; case R.id.miExit: finish(); return true; default: return super.onOptionsItemSelected(item); } } private void startActionViewIntent(String filename) { File file = new File(filename); String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); if (type == null) { type = "*/*"; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), type); startActivity(intent); } private class Install extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); Logger.addLog(getString(R.string.log_ide_msg_install_start)); } @Override protected Boolean doInBackground(Void... params) { return new IdeInit(MainApp.getContext().getAssets()).install(); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { ideConfig.setInstState(true); Logger.addLog(getString(R.string.log_ide_msg_install_ok)); } } } private class BuildProj extends AsyncTask<Void, Void, Void> { private ProjectBuilder builder; @Override protected Void doInBackground(Void... params) { builder = new ProjectBuilder.Builder(DATA_PKG_PATH + ASSET_DIR_BIN + "/" + MP3CC, DATA_PKG_PATH + ASSET_DIR_STUBS, pman.getCurrentProjectPath() + DIR_LIBS, pman.getCurrentProjectPath(), pman.getMainModuleFilename()).create(); if (builder.build()) { startActionViewIntent(builder.getJarFilename()); } return null; } } }
app/src/main/java/com/github/helltar/anpaside/MainActivity.java
package com.github.helltar.anpaside; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.Spanned; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.webkit.MimeTypeMap; import android.widget.EditText; import android.widget.ScrollView; import android.widget.TabHost; import android.widget.TextView; import android.widget.Toast; import com.github.helltar.anpaside.MainActivity; import com.github.helltar.anpaside.R; import com.github.helltar.anpaside.editor.CodeEditor; import com.github.helltar.anpaside.editor.EditorConfig; import com.github.helltar.anpaside.ide.IdeConfig; import com.github.helltar.anpaside.ide.IdeInit; import com.github.helltar.anpaside.logging.Logger; import com.github.helltar.anpaside.project.ProjectBuilder; import com.github.helltar.anpaside.project.ProjectManager; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import static com.github.helltar.anpaside.Consts.*; import static com.github.helltar.anpaside.logging.Logger.*; public class MainActivity extends AppCompatActivity { private CodeEditor editor; private EditorConfig editorConfig; private IdeConfig ideConfig; private ProjectManager pman; private static TextView tvLog; private static ScrollView svLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); tabHost.setup(); editor = new CodeEditor(this, tabHost); tvLog = (TextView) findViewById(R.id.tvLog); svLog = (ScrollView) findViewById(R.id.svLog); ideConfig = new IdeConfig(this); editorConfig = new EditorConfig(this); init(); } private void init() { if (ideConfig.isAssetsInstall()) { Logger.addLog(getString(R.string.app_name) + " " + getAppVersionName()); } else { new Install().execute(); } String lastFilename = editorConfig.getLastFilename(); if (!(lastFilename.isEmpty())) { openFile(lastFilename); } String lastProject = editorConfig.getLastProject(); if (!(lastProject.isEmpty())) { openProject(lastProject); } } public static void addGuiLog(final String msg, final LogMsgType msgType) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { String fontColor = "#aaaaaa"; switch (msgType) { case lmtText: fontColor = "#00aa00"; break; case lmtError: fontColor = "#ee0000"; break; } String currentTime = new SimpleDateFormat("[HH:mm:ss]: ").format(new Date()); Spanned text = Html.fromHtml(currentTime + "<font color='" + fontColor + "'>" + msg.replace("\n", "<br>") + "</font><br>"); tvLog.append(text); svLog.fullScroll(ScrollView.FOCUS_DOWN); } }); } private void showOpenFileDialog() { Intent intent = new Intent(); intent.setAction(Intent.ACTION_GET_CONTENT); intent.setType("file/*"); startActivityForResult(intent, 1); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data != null) { openFile(data.getData().getPath()); } } private void createProject(String path, String name) { if (pman.createProject(path, name)) { openProject(path + name + "/" + name + EXT_PROJ); } } private void createModule(String filename) { if (pman.createModule(filename)) { openFile(filename); } } private void openProject(String filename) { if (pman.openProject(filename)) { openFile(pman.getMainModuleFilename()); editorConfig.setLastProject(filename); } } private void openFile(String filename) { // TODO: ! if (FilenameUtils.getExtension(filename).equals(EXT_PROJ.substring(1, EXT_PROJ.length()))) { openProject(filename); } else { editor.openFile(filename); } editorConfig.setLastFilename(filename); } private void showNewProjectDialog() { final EditText edtProjectName = new EditText(this); edtProjectName.setHint(R.string.dlg_hint_project_name); new AlertDialog.Builder(this) .setTitle(R.string.dlg_title_new_project) .setMessage(R.string.dlg_subtitle_new_project) .setView(edtProjectName) .setPositiveButton(R.string.dlg_btn_create, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String projName = edtProjectName.getText().toString(); if (projName.length() < 3) { showAlertMsg("ะะตะฒะตั€ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต", "ะะฐะทะฒะฐะฝะธะต ะฟั€ะพะตะบั‚ะฐ ะดะพะปะถะฝะพ ัะพัั‚ะพัั‚ัŒ ะผะธะฝะธะผัƒะผ ะธะท 3-ั… ัะธะผะฒะพะปะพะฒ"); return; } String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"; final String path = sdcardPath + DIR_MAIN; final File projPath = new File(path + projName); if (!(projPath.exists())) { createProject(path, projName); } else { new AlertDialog.Builder(MainActivity.this) .setMessage("ะŸั€ะพะตะบั‚ ัƒะถะต ััƒั‰ะตัั‚ะฒัƒะตั‚") .setPositiveButton("ะŸะตั€ะตะทะฐะฟะธัะฐั‚ัŒ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { FileUtils.deleteDirectory(projPath); createProject(path, projName); } catch (IOException ioe) { Logger.addLog(ioe); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } private void showNewModuleDialog() { final EditText edtModuleName = new EditText(this); edtModuleName.setHint(R.string.dlg_hint_module_name); new AlertDialog.Builder(this) .setTitle(R.string.dlg_title_new_module) .setView(edtModuleName) .setPositiveButton(R.string.dlg_btn_create, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String moduleName = edtModuleName.getText().toString(); if (moduleName.length() < 3) { showAlertMsg("ะะตะฒะตั€ะฝะพะต ะทะฝะฐั‡ะตะฝะธะต", "ะะฐะทะฒะฐะฝะธะต ะผะพะดัƒะปั ะดะพะปะถะฝะพ ัะพัั‚ะพัั‚ัŒ ะผะธะฝะธะผัƒะผ ะธะท 3-ั… ัะธะผะฒะพะปะพะฒ"); return; } // TODO: ะดัƒะฑะปะธั€ะพะฒะฐะฝะธะต, (String) -> File final String filename = pman.getCurrentProjectPath() + DIR_SRC + moduleName + EXT_PAS; final File f = new File(filename); if (!(f.exists())) { createModule(filename); } else { new AlertDialog.Builder(MainActivity.this) .setMessage("ะœะพะดัƒะปัŒ ั ั‚ะฐะบะธะผ ะธะผะตะฝะตะผ ัƒะถะต ััƒั‰ะตัั‚ะฒัƒะตั‚") .setPositiveButton("ะŸะตั€ะตะทะฐะฟะธัะฐั‚ัŒ", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (f.delete()) { createModule(filename); } else { Logger.addLog("ะžัˆะธะฑะบะฐ ะฟั€ะธ ัƒะดะฐะปะตะฝะธะธ ัั‚ะฐั€ะพะณะพ ะผะพะดัƒะปั: " + filename); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } } }) .setNegativeButton(R.string.dlg_btn_cancel, null) .show(); } private void showAlertMsg(String msg) { showAlertMsg("", msg); } private void showAlertMsg(String title, String msg) { new AlertDialog.Builder(this) .setTitle(title) .setMessage(msg) .setNegativeButton("ะžะš", null) .show(); } private void showToastMsg(String msg) { Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } private String getAppVersionName() { try { return getPackageManager().getPackageInfo(getPackageName(), 0).versionName; } catch (PackageManager.NameNotFoundException e) { return "null"; } } private void saveCurrentFile() { if (editor.isCurrentFileModified()) { if (editor.saveCurrentFile()) { showToastMsg("ะกะพั…ั€ะฐะฝะตะฝะพ"); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_TAB: EditText e = editor.getCurrentEditor(); e.getText().insert(e.getSelectionStart(), " "); return true; case KeyEvent.KEYCODE_S: if (event.isCtrlPressed()) { saveCurrentFile(); } return true; default: return super.onKeyDown(keyCode, event); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.miCreateModule).setEnabled(pman.isProjectOpen()); menu.findItem(R.id.miFileSave).setEnabled(editor.isCurrentFileModified()); return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.miRun: if (pman.isProjectOpen()) { if (editor.saveCurrentFile()) { ProjectBuilder builder; builder = new ProjectBuilder.Builder(DATA_PKG_PATH + ASSET_DIR_BIN + "/" + MP3CC, DATA_PKG_PATH + ASSET_DIR_STUBS, pman.getCurrentProjectPath() + DIR_LIBS, pman.getCurrentProjectPath(), pman.getMainModuleFilename()).create(); if (builder.build()) { startActionViewIntent(builder.getJarFilename()); } } } else { showToastMsg("ะะตั‚ ะพั‚ะบั€ั‹ั‚ะพะณะพ ะฟั€ะพะตะบั‚ะฐ"); } return true; case R.id.miCreateProject: showNewProjectDialog(); return true; case R.id.miCreateModule: showNewModuleDialog(); return true; case R.id.miFileOpen: showOpenFileDialog(); return true; case R.id.miFileSave: saveCurrentFile(); return true; case R.id.miAbout: showAlertMsg(getString(R.string.about_text)); return true; case R.id.miExit: finish(); return true; default: return super.onOptionsItemSelected(item); } } private void startActionViewIntent(String filename) { File file = new File(filename); String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName()); String type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext); if (type == null) { type = "*/*"; } Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), type); startActivity(intent); } private class Install extends AsyncTask<Void, Void, Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); Logger.addLog(getString(R.string.log_ide_msg_install_start)); } @Override protected Boolean doInBackground(Void... params) { return new IdeInit(MainApp.getContext().getAssets()).install(); } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); if (result) { ideConfig.setInstState(true); Logger.addLog(getString(R.string.log_ide_msg_install_ok)); } } } private class BuildProj extends AsyncTask<Void, Void, Void> { private Exception error; private ProjectBuilder builder; @Override protected Void doInBackground(Void... params) { builder = new ProjectBuilder.Builder(DATA_PKG_PATH + ASSET_DIR_BIN + "/" + MP3CC, DATA_PKG_PATH + ASSET_DIR_STUBS, pman.getCurrentProjectPath() + DIR_LIBS, pman.getCurrentProjectPath(), pman.getMainModuleFilename()).create(); if (builder.build()) { startActionViewIntent(builder.getJarFilename()); } return null; } } }
ะžะน, ั ัะปัƒั‡ะฐะนะฝะพ
app/src/main/java/com/github/helltar/anpaside/MainActivity.java
ะžะน, ั ัะปัƒั‡ะฐะนะฝะพ
Java
mit
3c6f45e24ba5a255a3506ded1a34599b2326032a
0
vtsukur/spring-rest-black-market,vtsukur/spring-rest-black-market,vtsukur/spring-rest-black-market
package org.vtsukur.spring.rest.market.domain.core.user; import org.springframework.data.repository.CrudRepository; /** * @author volodymyr.tsukur */ public interface UserRepository extends CrudRepository<User, Long> { }
src/main/java/org/vtsukur/spring/rest/market/domain/core/user/UserRepository.java
package org.vtsukur.spring.rest.market.domain.core.user; import org.springframework.data.repository.CrudRepository; import org.springframework.data.rest.core.annotation.RestResource; /** * @author volodymyr.tsukur */ @RestResource(exported = false) public interface UserRepository extends CrudRepository<User, Long> { }
Simplifying the job by making user repository exposed for now.
src/main/java/org/vtsukur/spring/rest/market/domain/core/user/UserRepository.java
Simplifying the job by making user repository exposed for now.
Java
mit
37673c02d7a1100776cc08835ff81eb80175006d
0
leomoldo/bunkerwar
package fr.leomoldo.android.bunkerwar.activity; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import fr.leomoldo.android.bunkerwar.BombshellAnimatorAsyncTask; import fr.leomoldo.android.bunkerwar.BombshellPathComputer; import fr.leomoldo.android.bunkerwar.GameSequencer; import fr.leomoldo.android.bunkerwar.R; import fr.leomoldo.android.bunkerwar.drawer.Bunker; import fr.leomoldo.android.bunkerwar.drawer.Landscape; import fr.leomoldo.android.bunkerwar.sdk.Drawer; import fr.leomoldo.android.bunkerwar.sdk.GameView; import fr.leomoldo.android.bunkerwar.sdk.ViewCoordinates; public class TwoPlayerGameActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, BombshellAnimatorAsyncTask.CollisionListener { private final static String LOG_TAG = TwoPlayerGameActivity.class.getSimpleName(); // Model : private GameSequencer mGameSequencer; private Bunker mPlayerOneBunker; private Bunker mPlayerTwoBunker; private Landscape mLandscape; private BombshellAnimatorAsyncTask mBombshellAnimatorAsyncTask; // Views : private GameView mGameView; private TextView mTextViewIndicatorAnglePlayerOne; private TextView mTextViewIndicatorPowerPlayerOne; private TextView mTextViewIndicatorAnglePlayerTwo; private TextView mTextViewIndicatorPowerPlayerTwo; private Button mFireButtonPlayerOne; private Button mFireButtonPlayerTwo; private SeekBar mSeekBarAnglePlayerOne; private SeekBar mSeekBarPowerPlayerOne; private SeekBar mSeekBarAnglePlayerTwo; private SeekBar mSeekBarPowerPlayerTwo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two_player_game); // Retrieve useful views. mTextViewIndicatorAnglePlayerOne = (TextView) findViewById(R.id.textViewIndicatorAnglePlayerOne); mTextViewIndicatorPowerPlayerOne = (TextView) findViewById(R.id.textViewIndicatorPowerPlayerOne); mTextViewIndicatorAnglePlayerTwo = (TextView) findViewById(R.id.textViewIndicatorAnglePlayerTwo); mTextViewIndicatorPowerPlayerTwo = (TextView) findViewById(R.id.textViewIndicatorPowerPlayerTwo); mFireButtonPlayerOne = (Button) findViewById(R.id.buttonFirePlayerOne); mFireButtonPlayerTwo = (Button) findViewById(R.id.buttonFirePlayerTwo); mSeekBarAnglePlayerOne = (SeekBar) findViewById(R.id.seekBarAnglePlayerOne); mSeekBarPowerPlayerOne = (SeekBar) findViewById(R.id.seekBarPowerPlayerOne); mSeekBarAnglePlayerTwo = (SeekBar) findViewById(R.id.seekBarAnglePlayerTwo); mSeekBarPowerPlayerTwo = (SeekBar) findViewById(R.id.seekBarPowerPlayerTwo); mGameView = (GameView) findViewById(R.id.gameView); mSeekBarAnglePlayerOne.setOnSeekBarChangeListener(this); mSeekBarPowerPlayerOne.setOnSeekBarChangeListener(this); mSeekBarAnglePlayerTwo.setOnSeekBarChangeListener(this); mSeekBarPowerPlayerTwo.setOnSeekBarChangeListener(this); // TODO Change UI visibility handling. mFireButtonPlayerOne.setVisibility(View.VISIBLE); mFireButtonPlayerTwo.setVisibility(View.VISIBLE); final View rootView = getWindow().getDecorView().getRootView(); rootView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Only useful for now? (with "reload game" debug button). /* mGameView.unregisterDrawer(mLandscape); mGameView.unregisterDrawer(mPlayerOneBunker); mGameView.unregisterDrawer(mPlayerTwoBunker); */ // Initialize game model. mGameSequencer = new GameSequencer(); mLandscape = new Landscape(getResources().getColor(R.color.green_land_slice)); mPlayerOneBunker = new Bunker(true, Color.RED, getBunkerOneCoordinates()); mPlayerTwoBunker = new Bunker(false, Color.YELLOW, getBunkerTwoCoordinates()); // Initialize GameView. mGameView.registerDrawer(mPlayerOneBunker); mGameView.registerDrawer(mPlayerTwoBunker); mGameView.registerDrawer(mLandscape); mGameView.invalidate(); if (Build.VERSION.SDK_INT < 16) { rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } }); } @Override protected void onDestroy() { if (mBombshellAnimatorAsyncTask != null) { mBombshellAnimatorAsyncTask.cancel(true); } super.onDestroy(); } @Override public void onBackPressed() { // TODO Implement AlertDialog to confirm call to super.onBackPressed. super.onBackPressed(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Integer value = progress; switch (seekBar.getId()) { case R.id.seekBarAnglePlayerOne: mPlayerOneBunker.setAbsoluteCanonAngle(progress); mGameView.invalidate(); mTextViewIndicatorAnglePlayerOne.setText(value.toString()); break; case R.id.seekBarPowerPlayerOne: mPlayerOneBunker.setCanonPower(progress); mTextViewIndicatorPowerPlayerOne.setText(value.toString()); break; case R.id.seekBarAnglePlayerTwo: mPlayerTwoBunker.setAbsoluteCanonAngle(progress); mGameView.invalidate(); mTextViewIndicatorAnglePlayerTwo.setText(value.toString()); break; case R.id.seekBarPowerPlayerTwo: mPlayerTwoBunker.setCanonPower(progress); mTextViewIndicatorPowerPlayerTwo.setText(value.toString()); break; } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } public void onButtonClickedFire(View view) { if (mBombshellAnimatorAsyncTask != null) { Log.d(LOG_TAG, "There is a Bombshell flying already"); return; } // Check which player has clicked the button. Boolean didPlayerOneFire = false; if (view.getId() == R.id.buttonFirePlayerOne) { didPlayerOneFire = true; } // Update GameSequencer. mGameSequencer.fireButtonPressed(didPlayerOneFire); BombshellPathComputer bombshellPathComputer; ArrayList<Drawer> collidableDrawers = new ArrayList<Drawer>(); collidableDrawers.add(mLandscape); // Update UI. if (didPlayerOneFire) { mFireButtonPlayerOne.setVisibility(View.GONE); mFireButtonPlayerTwo.setVisibility(View.GONE); bombshellPathComputer = new BombshellPathComputer(mPlayerOneBunker.getCanonPower(), mPlayerOneBunker.getGeometricalCanonAngleRadian(), mPlayerOneBunker.getViewCoordinates()); collidableDrawers.add(mPlayerTwoBunker); } else { mFireButtonPlayerTwo.setVisibility(View.GONE); mFireButtonPlayerOne.setVisibility(View.GONE); bombshellPathComputer = new BombshellPathComputer(mPlayerTwoBunker.getCanonPower(), mPlayerTwoBunker.getGeometricalCanonAngleRadian(), mPlayerTwoBunker.getViewCoordinates()); collidableDrawers.add(mPlayerOneBunker); } mBombshellAnimatorAsyncTask = new BombshellAnimatorAsyncTask(mGameView, collidableDrawers, this); mBombshellAnimatorAsyncTask.execute(bombshellPathComputer); } @Override public void onDrawerHit(Drawer drawer) { mBombshellAnimatorAsyncTask = null; // TODO Update GameSequencer. // TODO Replace by AlertDialog displaying rounds count. if (drawer == null || drawer.equals(mLandscape)) { Toast.makeText(this, R.string.target_missed, Toast.LENGTH_SHORT).show(); mFireButtonPlayerOne.setVisibility(View.VISIBLE); mFireButtonPlayerTwo.setVisibility(View.VISIBLE); } else if (drawer.equals(mPlayerTwoBunker)) { Toast.makeText(this, R.string.player_one_won, Toast.LENGTH_LONG).show(); mGameView.unregisterDrawer(mPlayerTwoBunker); } else if (drawer.equals(mPlayerOneBunker)) { Toast.makeText(this, R.string.player_two_won, Toast.LENGTH_LONG).show(); mGameView.unregisterDrawer(mPlayerOneBunker); } } private ViewCoordinates getBunkerOneCoordinates() { float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices(); return new ViewCoordinates(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth, mGameView.getHeight() - mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - Bunker.BUNKER_RADIUS); } private ViewCoordinates getBunkerTwoCoordinates() { float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices(); return new ViewCoordinates(mGameView.getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER, mGameView.getHeight() - mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - Bunker.BUNKER_RADIUS); } }
app/src/main/java/fr/leomoldo/android/bunkerwar/activity/TwoPlayerGameActivity.java
package fr.leomoldo.android.bunkerwar.activity; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewTreeObserver; import android.widget.Button; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import fr.leomoldo.android.bunkerwar.BombshellAnimatorAsyncTask; import fr.leomoldo.android.bunkerwar.BombshellPathComputer; import fr.leomoldo.android.bunkerwar.GameSequencer; import fr.leomoldo.android.bunkerwar.R; import fr.leomoldo.android.bunkerwar.drawer.Bunker; import fr.leomoldo.android.bunkerwar.drawer.Landscape; import fr.leomoldo.android.bunkerwar.sdk.Drawer; import fr.leomoldo.android.bunkerwar.sdk.GameView; import fr.leomoldo.android.bunkerwar.sdk.ViewCoordinates; public class TwoPlayerGameActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, BombshellAnimatorAsyncTask.CollisionListener { private final static String LOG_TAG = TwoPlayerGameActivity.class.getSimpleName(); // Model : private GameSequencer mGameSequencer; private Bunker mPlayerOneBunker; private Bunker mPlayerTwoBunker; private Landscape mLandscape; private BombshellAnimatorAsyncTask mBombshellAnimatorAsyncTask; // Views : private GameView mGameView; private TextView mTextViewIndicatorAnglePlayerOne; private TextView mTextViewIndicatorPowerPlayerOne; private TextView mTextViewIndicatorAnglePlayerTwo; private TextView mTextViewIndicatorPowerPlayerTwo; private Button mFireButtonPlayerOne; private Button mFireButtonPlayerTwo; private SeekBar mSeekBarAnglePlayerOne; private SeekBar mSeekBarPowerPlayerOne; private SeekBar mSeekBarAnglePlayerTwo; private SeekBar mSeekBarPowerPlayerTwo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_two_player_game); // Retrieve useful views. mTextViewIndicatorAnglePlayerOne = (TextView) findViewById(R.id.textViewIndicatorAnglePlayerOne); mTextViewIndicatorPowerPlayerOne = (TextView) findViewById(R.id.textViewIndicatorPowerPlayerOne); mTextViewIndicatorAnglePlayerTwo = (TextView) findViewById(R.id.textViewIndicatorAnglePlayerTwo); mTextViewIndicatorPowerPlayerTwo = (TextView) findViewById(R.id.textViewIndicatorPowerPlayerTwo); mFireButtonPlayerOne = (Button) findViewById(R.id.buttonFirePlayerOne); mFireButtonPlayerTwo = (Button) findViewById(R.id.buttonFirePlayerTwo); mSeekBarAnglePlayerOne = (SeekBar) findViewById(R.id.seekBarAnglePlayerOne); mSeekBarPowerPlayerOne = (SeekBar) findViewById(R.id.seekBarPowerPlayerOne); mSeekBarAnglePlayerTwo = (SeekBar) findViewById(R.id.seekBarAnglePlayerTwo); mSeekBarPowerPlayerTwo = (SeekBar) findViewById(R.id.seekBarPowerPlayerTwo); mGameView = (GameView) findViewById(R.id.gameView); mSeekBarAnglePlayerOne.setOnSeekBarChangeListener(this); mSeekBarPowerPlayerOne.setOnSeekBarChangeListener(this); mSeekBarAnglePlayerTwo.setOnSeekBarChangeListener(this); mSeekBarPowerPlayerTwo.setOnSeekBarChangeListener(this); // TODO Change UI visibility handling. mFireButtonPlayerOne.setVisibility(View.VISIBLE); mFireButtonPlayerTwo.setVisibility(View.VISIBLE); // Initialize game model. mGameSequencer = new GameSequencer(); mLandscape = new Landscape(getResources().getColor(R.color.green_land_slice)); mPlayerOneBunker = new Bunker(true, Color.RED, getBunkerOneCoordinates()); mPlayerTwoBunker = new Bunker(false, Color.YELLOW, getBunkerTwoCoordinates()); final View rootView = getWindow().getDecorView().getRootView(); rootView.getViewTreeObserver().addOnGlobalLayoutListener( new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // Initialize GameView. mGameView.registerDrawer(mPlayerOneBunker); mGameView.registerDrawer(mPlayerTwoBunker); mGameView.registerDrawer(mLandscape); mGameView.invalidate(); if (Build.VERSION.SDK_INT < 16) { rootView.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this); } } }); } @Override protected void onDestroy() { if (mBombshellAnimatorAsyncTask != null) { mBombshellAnimatorAsyncTask.cancel(true); } super.onDestroy(); } @Override public void onBackPressed() { // TODO Implement AlertDialog to confirm call to super.onBackPressed. super.onBackPressed(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Integer value = progress; switch (seekBar.getId()) { case R.id.seekBarAnglePlayerOne: mPlayerOneBunker.setAbsoluteCanonAngle(progress); mGameView.invalidate(); mTextViewIndicatorAnglePlayerOne.setText(value.toString()); break; case R.id.seekBarPowerPlayerOne: mPlayerOneBunker.setCanonPower(progress); mTextViewIndicatorPowerPlayerOne.setText(value.toString()); break; case R.id.seekBarAnglePlayerTwo: mPlayerTwoBunker.setAbsoluteCanonAngle(progress); mGameView.invalidate(); mTextViewIndicatorAnglePlayerTwo.setText(value.toString()); break; case R.id.seekBarPowerPlayerTwo: mPlayerTwoBunker.setCanonPower(progress); mTextViewIndicatorPowerPlayerTwo.setText(value.toString()); break; } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } public void onButtonClickedFire(View view) { if (mBombshellAnimatorAsyncTask != null) { Log.d(LOG_TAG, "There is a Bombshell flying already"); return; } // Check which player has clicked the button. Boolean didPlayerOneFire = false; if (view.getId() == R.id.buttonFirePlayerOne) { didPlayerOneFire = true; } // Update GameSequencer. mGameSequencer.fireButtonPressed(didPlayerOneFire); BombshellPathComputer bombshellPathComputer; ArrayList<Drawer> collidableDrawers = new ArrayList<Drawer>(); collidableDrawers.add(mLandscape); // Update UI. if (didPlayerOneFire) { mFireButtonPlayerOne.setVisibility(View.GONE); mFireButtonPlayerTwo.setVisibility(View.GONE); bombshellPathComputer = new BombshellPathComputer(mPlayerOneBunker.getCanonPower(), mPlayerOneBunker.getGeometricalCanonAngleRadian(), mPlayerOneBunker.getViewCoordinates()); collidableDrawers.add(mPlayerTwoBunker); } else { mFireButtonPlayerTwo.setVisibility(View.GONE); mFireButtonPlayerOne.setVisibility(View.GONE); bombshellPathComputer = new BombshellPathComputer(mPlayerTwoBunker.getCanonPower(), mPlayerTwoBunker.getGeometricalCanonAngleRadian(), mPlayerTwoBunker.getViewCoordinates()); collidableDrawers.add(mPlayerOneBunker); } mBombshellAnimatorAsyncTask = new BombshellAnimatorAsyncTask(mGameView, collidableDrawers, this); mBombshellAnimatorAsyncTask.execute(bombshellPathComputer); } @Override public void onDrawerHit(Drawer drawer) { mBombshellAnimatorAsyncTask = null; // TODO Update GameSequencer. // TODO Replace by AlertDialog displaying rounds count. if (drawer == null || drawer.equals(mLandscape)) { Toast.makeText(this, R.string.target_missed, Toast.LENGTH_SHORT).show(); mFireButtonPlayerOne.setVisibility(View.VISIBLE); mFireButtonPlayerTwo.setVisibility(View.VISIBLE); } else if (drawer.equals(mPlayerTwoBunker)) { Toast.makeText(this, R.string.player_one_won, Toast.LENGTH_LONG).show(); mGameView.unregisterDrawer(mPlayerTwoBunker); } else if (drawer.equals(mPlayerOneBunker)) { Toast.makeText(this, R.string.player_two_won, Toast.LENGTH_LONG).show(); mGameView.unregisterDrawer(mPlayerOneBunker); } } // TODO Remove. private void initializeGame() { // Only useful for now? (with "reload game" debug button). /* mGameView.unregisterDrawer(mLandscape); mGameView.unregisterDrawer(mPlayerOneBunker); mGameView.unregisterDrawer(mPlayerTwoBunker); */ } private ViewCoordinates getBunkerOneCoordinates() { float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices(); return new ViewCoordinates(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER * landSliceWidth, mGameView.getHeight() - mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - Bunker.BUNKER_RADIUS); } private ViewCoordinates getBunkerTwoCoordinates() { float landSliceWidth = mGameView.getWidth() / mLandscape.getNumberOfLandscapeSlices(); return new ViewCoordinates(mGameView.getWidth() - landSliceWidth * Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER, mGameView.getHeight() - mGameView.getHeight() * Landscape.MAX_HEIGHT_RATIO_FOR_LANDSCAPE * mLandscape.getLandscapeHeightPercentage(mLandscape.getNumberOfLandscapeSlices() - 1 - Landscape.BUNKER_POSITION_FROM_SCREEN_BORDER) - Bunker.BUNKER_RADIUS); } }
Bug fix.
app/src/main/java/fr/leomoldo/android/bunkerwar/activity/TwoPlayerGameActivity.java
Bug fix.
Java
mit
3f7e2b1fca5371c6b68f6570efdc3768f61f0ca8
0
sazzad16/jedis,sazzad16/jedis
package redis.clients.jedis; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import redis.clients.jedis.commands.ProtocolCommand; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.IOUtils; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; import redis.clients.util.SafeEncoder; public class Connection implements Closeable { private static final byte[][] EMPTY_ARGS = new byte[0][]; private String host = Protocol.DEFAULT_HOST; private int port = Protocol.DEFAULT_PORT; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; private int connectionTimeout = Protocol.DEFAULT_TIMEOUT; private int soTimeout = Protocol.DEFAULT_TIMEOUT; private boolean broken = false; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; public Connection() { } public Connection(final String host) { this.host = host; } public Connection(final String host, final int port) { this.host = host; this.port = port; } public Connection(final String host, final int port, final boolean ssl) { this.host = host; this.port = port; this.ssl = ssl; } public Connection(final String host, final int port, final boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { this.host = host; this.port = port; this.ssl = ssl; this.sslSocketFactory = sslSocketFactory; this.sslParameters = sslParameters; this.hostnameVerifier = hostnameVerifier; } public Socket getSocket() { return socket; } public int getConnectionTimeout() { return connectionTimeout; } public int getSoTimeout() { return soTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public void setTimeoutInfinite() { try { if (!isConnected()) { connect(); } socket.setSoTimeout(0); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); } } public void rollbackTimeout() { try { socket.setSoTimeout(soTimeout); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); } } public Connection sendCommand(final ProtocolCommand cmd, final String... args) { final byte[][] bargs = new byte[args.length][]; for (int i = 0; i < args.length; i++) { bargs[i] = SafeEncoder.encode(args[i]); } return sendCommand(cmd, bargs); } public Connection sendCommand(final ProtocolCommand cmd) { return sendCommand(cmd, EMPTY_ARGS); } public Connection sendCommand(final ProtocolCommand cmd, final byte[]... args) { try { connect(); Protocol.sendCommand(outputStream, cmd, args); return this; } catch (JedisConnectionException ex) { /* * When client send request which formed by invalid protocol, Redis send back error message * before close connection. We try to read it to provide reason of failure. */ try { String errorMessage = Protocol.readErrorLineIfPossible(inputStream); if (errorMessage != null && errorMessage.length() > 0) { ex = new JedisConnectionException(errorMessage, ex.getCause()); } } catch (Exception e) { /* * Catch any IOException or JedisConnectionException occurred from InputStream#read and just * ignore. This approach is safe because reading error message is optional and connection * will eventually be closed. */ } // Any other exceptions related to connection? broken = true; throw ex; } } public String getHost() { return host; } public void setHost(final String host) { this.host = host; } public int getPort() { return port; } public void setPort(final int port) { this.port = port; } public void connect() { if (!isConnected()) { try { socket = new Socket(); // ->@wjw_add socket.setReuseAddress(true); socket.setKeepAlive(true); // Will monitor the TCP connection is // valid socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to // ensure timely delivery of data socket.setSoLinger(true, 0); // Control calls close () method, // the underlying socket is closed // immediately // <-@wjw_add socket.connect(new InetSocketAddress(host, port), connectionTimeout); socket.setSoTimeout(soTimeout); if (ssl) { if (null == sslSocketFactory) { sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); } socket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true); if (null != sslParameters) { ((SSLSocket) socket).setSSLParameters(sslParameters); } if ((null != hostnameVerifier) && (!hostnameVerifier.verify(host, ((SSLSocket) socket).getSession()))) { String message = String.format( "The connection to '%s' failed ssl/tls hostname verification.", host); throw new JedisConnectionException(message); } } outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream(socket.getInputStream()); } catch (IOException ex) { broken = true; throw new JedisConnectionException("Failed connecting to host " + host + ":" + port, ex); } } } @Override public void close() { disconnect(); } public void disconnect() { if (isConnected()) { try { outputStream.flush(); socket.close(); } catch (IOException ex) { broken = true; throw new JedisConnectionException(ex); } finally { IOUtils.closeQuietly(socket); } } } public boolean isConnected() { return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } public String getStatusCodeReply() { return getBulkReply(); } public String getBulkReply() { final byte[] result = getBinaryBulkReply(); return (null != result) ? SafeEncoder.encode(result) : null; } public byte[] getBinaryBulkReply() { flush(); return (byte[]) readProtocolWithCheckingBroken(); } public Long getIntegerReply() { flush(); return (Long) readProtocolWithCheckingBroken(); } public List<String> getMultiBulkReply() { return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply()); } @SuppressWarnings("unchecked") public List<byte[]> getBinaryMultiBulkReply() { flush(); return (List<byte[]>) readProtocolWithCheckingBroken(); } @SuppressWarnings("unchecked") public List<Object> getRawObjectMultiBulkReply() { flush(); return (List<Object>) readProtocolWithCheckingBroken(); } public List<Object> getObjectMultiBulkReply() { return getRawObjectMultiBulkReply(); } @SuppressWarnings("unchecked") public List<Long> getIntegerMultiBulkReply() { flush(); return (List<Long>) readProtocolWithCheckingBroken(); } public Object getOne() { flush(); return readProtocolWithCheckingBroken(); } public boolean isBroken() { return broken; } protected void flush() { try { outputStream.flush(); } catch (IOException ex) { broken = true; throw new JedisConnectionException(ex); } } protected Object readProtocolWithCheckingBroken() { try { return Protocol.read(inputStream); } catch (JedisConnectionException exc) { broken = true; throw exc; } } public List<Object> getMany(final int count) { flush(); final List<Object> responses = new ArrayList<Object>(count); for (int i = 0; i < count; i++) { try { responses.add(readProtocolWithCheckingBroken()); } catch (JedisDataException e) { responses.add(e); } } return responses; } }
src/main/java/redis/clients/jedis/Connection.java
package redis.clients.jedis; import java.io.Closeable; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; import java.util.ArrayList; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import redis.clients.jedis.commands.ProtocolCommand; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.util.IOUtils; import redis.clients.util.RedisInputStream; import redis.clients.util.RedisOutputStream; import redis.clients.util.SafeEncoder; public class Connection implements Closeable { private static final byte[][] EMPTY_ARGS = new byte[0][]; private String host = Protocol.DEFAULT_HOST; private int port = Protocol.DEFAULT_PORT; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; private int connectionTimeout = Protocol.DEFAULT_TIMEOUT; private int soTimeout = Protocol.DEFAULT_TIMEOUT; private boolean broken = false; private boolean ssl; private SSLSocketFactory sslSocketFactory; private SSLParameters sslParameters; private HostnameVerifier hostnameVerifier; public Connection() { } public Connection(final String host) { this.host = host; } public Connection(final String host, final int port) { this.host = host; this.port = port; } public Connection(final String host, final int port, final boolean ssl) { this.host = host; this.port = port; this.ssl = ssl; } public Connection(final String host, final int port, final boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { this.host = host; this.port = port; this.ssl = ssl; this.sslSocketFactory = sslSocketFactory; this.sslParameters = sslParameters; this.hostnameVerifier = hostnameVerifier; } public Socket getSocket() { return socket; } public int getConnectionTimeout() { return connectionTimeout; } public int getSoTimeout() { return soTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public void setSoTimeout(int soTimeout) { this.soTimeout = soTimeout; } public void setTimeoutInfinite() { try { if (!isConnected()) { connect(); } socket.setSoTimeout(0); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); } } public void rollbackTimeout() { try { socket.setSoTimeout(soTimeout); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); } } public Connection sendCommand(final ProtocolCommand cmd, final String... args) { final byte[][] bargs = new byte[args.length][]; for (int i = 0; i < args.length; i++) { bargs[i] = SafeEncoder.encode(args[i]); } return sendCommand(cmd, bargs); } public Connection sendCommand(final ProtocolCommand cmd) { return sendCommand(cmd, EMPTY_ARGS); } public Connection sendCommand(final ProtocolCommand cmd, final byte[]... args) { try { connect(); Protocol.sendCommand(outputStream, cmd, args); return this; } catch (JedisConnectionException ex) { /* * When client send request which formed by invalid protocol, Redis send back error message * before close connection. We try to read it to provide reason of failure. */ try { String errorMessage = Protocol.readErrorLineIfPossible(inputStream); if (errorMessage != null && errorMessage.length() > 0) { ex = new JedisConnectionException(errorMessage, ex.getCause()); } } catch (Exception e) { /* * Catch any IOException or JedisConnectionException occurred from InputStream#read and just * ignore. This approach is safe because reading error message is optional and connection * will eventually be closed. */ } // Any other exceptions related to connection? broken = true; throw ex; } } public String getHost() { return host; } public void setHost(final String host) { this.host = host; } public int getPort() { return port; } public void setPort(final int port) { this.port = port; } public void connect() { if (!isConnected()) { try { socket = new Socket(); // ->@wjw_add socket.setReuseAddress(true); socket.setKeepAlive(true); // Will monitor the TCP connection is // valid socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to // ensure timely delivery of data socket.setSoLinger(true, 0); // Control calls close () method, // the underlying socket is closed // immediately // <-@wjw_add socket.connect(new InetSocketAddress(host, port), connectionTimeout); socket.setSoTimeout(soTimeout); if (ssl) { if (null == sslSocketFactory) { sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault(); } socket = (SSLSocket) sslSocketFactory.createSocket(socket, host, port, true); if (null != sslParameters) { ((SSLSocket) socket).setSSLParameters(sslParameters); } if ((null != hostnameVerifier) && (!hostnameVerifier.verify(host, ((SSLSocket) socket).getSession()))) { String message = String.format( "The connection to '%s' failed ssl/tls hostname verification.", host); throw new JedisConnectionException(message); } } outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream(socket.getInputStream()); } catch (IOException ex) { broken = true; throw new JedisConnectionException("Failed connecting to host " + host + ":" + port, ex); } } } @Override public void close() { disconnect(); } public void disconnect() { if (isConnected()) { try { outputStream.flush(); socket.close(); } catch (IOException ex) { broken = true; throw new JedisConnectionException(ex); } finally { IOUtils.closeQuietly(socket); } } } public boolean isConnected() { return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } public String getStatusCodeReply() { flush(); final byte[] resp = (byte[]) readProtocolWithCheckingBroken(); if (null == resp) { return null; } else { return SafeEncoder.encode(resp); } } public String getBulkReply() { final byte[] result = getBinaryBulkReply(); if (null != result) { return SafeEncoder.encode(result); } else { return null; } } public byte[] getBinaryBulkReply() { flush(); return (byte[]) readProtocolWithCheckingBroken(); } public Long getIntegerReply() { flush(); return (Long) readProtocolWithCheckingBroken(); } public List<String> getMultiBulkReply() { return BuilderFactory.STRING_LIST.build(getBinaryMultiBulkReply()); } @SuppressWarnings("unchecked") public List<byte[]> getBinaryMultiBulkReply() { flush(); return (List<byte[]>) readProtocolWithCheckingBroken(); } @SuppressWarnings("unchecked") public List<Object> getRawObjectMultiBulkReply() { return (List<Object>) readProtocolWithCheckingBroken(); } public List<Object> getObjectMultiBulkReply() { flush(); return getRawObjectMultiBulkReply(); } @SuppressWarnings("unchecked") public List<Long> getIntegerMultiBulkReply() { flush(); return (List<Long>) readProtocolWithCheckingBroken(); } public Object getOne() { flush(); return readProtocolWithCheckingBroken(); } public boolean isBroken() { return broken; } protected void flush() { try { outputStream.flush(); } catch (IOException ex) { broken = true; throw new JedisConnectionException(ex); } } protected Object readProtocolWithCheckingBroken() { try { return Protocol.read(inputStream); } catch (JedisConnectionException exc) { broken = true; throw exc; } } public List<Object> getMany(final int count) { flush(); final List<Object> responses = new ArrayList<Object>(count); for (int i = 0; i < count; i++) { try { responses.add(readProtocolWithCheckingBroken()); } catch (JedisDataException e) { responses.add(e); } } return responses; } }
Modified Connection class (#22) * Re-used code for getStatusCodeReply. * Added 'missing' flush in getRawObjectMultiBulkReply. Removed flush from getObjectMultiBulkReply because it just calls getRawObjectMultiBulkReply and flush is added there.
src/main/java/redis/clients/jedis/Connection.java
Modified Connection class (#22)
Java
mit
28cf764fe1fd9a207b54af5eff38a27865944323
0
willsalz/ttyl,willsalz/ttyl,willsalz/ttyl
package co.willsalz.ttyl.application; import co.willsalz.ttyl.configuration.TTYLConfiguration; import co.willsalz.ttyl.healthchecks.TwilioHealthCheck; import co.willsalz.ttyl.resources.IndexResource; import co.willsalz.ttyl.resources.v1.CallResource; import co.willsalz.ttyl.resources.v1.ConnectCallResource; import co.willsalz.ttyl.serialization.TwimlMessageBodyWriter; import co.willsalz.ttyl.service.PhoneService; import com.twilio.http.TwilioRestClient; import io.dropwizard.Application; import io.dropwizard.configuration.EnvironmentVariableSubstitutor; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.dropwizard.views.ViewBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TTYLApplication extends Application<TTYLConfiguration> { private static final Logger logger = LoggerFactory.getLogger(TTYLApplication.class); public static void main(final String[] args) throws Exception { new TTYLApplication().run(args); } @Override public String getName() { return "ttyl"; } @Override public void initialize(final Bootstrap<TTYLConfiguration> bootstrap) { super.initialize(bootstrap); // Allow Environment Variables to be used in YAML bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider( bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(true) ) ); // Views bootstrap.addBundle(new ViewBundle<>()); } public void run(final TTYLConfiguration cfg, final Environment env) throws Exception { // Register Middleware env.jersey().register(new TwimlMessageBodyWriter()); // Services final TwilioRestClient twilio = cfg.getTwilioConfiguration().build(env); final PhoneService phoneService = new PhoneService( twilio, cfg.getTwilioConfiguration().getPhoneNumber() ); // Register Resources env.jersey().register(new IndexResource()); env.jersey().register(new CallResource(phoneService)); env.jersey().register(new ConnectCallResource()); // Register Healthchecks env.healthChecks().register("twilio", new TwilioHealthCheck(twilio)); } }
src/main/java/co/willsalz/ttyl/application/TTYLApplication.java
package co.willsalz.ttyl.application; import co.willsalz.ttyl.configuration.TTYLConfiguration; import co.willsalz.ttyl.healthchecks.TwilioHealthCheck; import co.willsalz.ttyl.resources.IndexResource; import co.willsalz.ttyl.resources.v1.CallResource; import co.willsalz.ttyl.resources.v1.ConnectCallResource; import co.willsalz.ttyl.serialization.TwimlMessageBodyWriter; import co.willsalz.ttyl.service.PhoneService; import com.twilio.http.TwilioRestClient; import io.dropwizard.Application; import io.dropwizard.configuration.EnvironmentVariableSubstitutor; import io.dropwizard.configuration.SubstitutingSourceProvider; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import io.dropwizard.views.ViewBundle; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TTYLApplication extends Application<TTYLConfiguration> { private static final Logger logger = LoggerFactory.getLogger(TTYLApplication.class); public static void main(final String[] args) throws Exception { new TTYLApplication().run(args); } @Override public String getName() { return "ttyl"; } @Override public void initialize(final Bootstrap<TTYLConfiguration> bootstrap) { super.initialize(bootstrap); // Allow Environment Variables to be used in YAML bootstrap.setConfigurationSourceProvider( new SubstitutingSourceProvider( bootstrap.getConfigurationSourceProvider(), new EnvironmentVariableSubstitutor(true) ) ); // Views bootstrap.addBundle(new ViewBundle<>()); } public void run(final TTYLConfiguration cfg, final Environment env) throws Exception { // Register Middleware env.jersey().register(new TwimlMessageBodyWriter()); // Services final TwilioRestClient twilio = cfg.getTwilioConfiguration().build(env); final PhoneService phoneService = new PhoneService( twilio, cfg.getTwilioConfiguration().getPhoneNumber() ); // Register Resources env.jersey().register(new IndexResource()); env.jersey().register(new CallResource(phoneService)); env.jersey().register(new ConnectCallResource()); // Register Endpoints env.healthChecks().register("twilio", new TwilioHealthCheck(twilio)); } }
Fix dox
src/main/java/co/willsalz/ttyl/application/TTYLApplication.java
Fix dox
Java
mit
03b5f7d8f9cc67e52cba08531429cb2ef791e6e9
0
ShaneMcC/DMDirc-Client,greboid/DMDirc,csmith/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,csmith/DMDirc,DMDirc/DMDirc,csmith/DMDirc,greboid/DMDirc,DMDirc/DMDirc,csmith/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,greboid/DMDirc
/* * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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.dmdirc.config; import com.dmdirc.Main; import com.dmdirc.Precondition; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.updater.Version; import com.dmdirc.util.ConfigFile; import com.dmdirc.util.InvalidConfigFileException; import com.dmdirc.util.WeakList; import com.dmdirc.util.resourcemanager.ResourceManager; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The identity manager manages all known identities, providing easy methods * to access them. * * @author chris */ public final class IdentityManager { /** The identities that have been loaded into this manager. */ private final static List<Identity> identities = new ArrayList<Identity>(); /** The config managers that have registered with this manager. */ private final static List<ConfigManager> managers = new WeakList<ConfigManager>(); /** The identity file used for the global config. */ private static Identity config; /** The identity file used for addon defaults. */ private static Identity addonConfig; /** The identity file bundled with the client containing version info. */ private static Identity versionConfig; /** The config manager used for global settings. */ private static ConfigManager globalconfig; /** Creates a new instance of IdentityManager. */ private IdentityManager() { } /** Loads all identity files. */ public static void load() { identities.clear(); managers.clear(); if (globalconfig != null) { // May have been created earlier managers.add(globalconfig); } loadVersion(); loadDefaults(); loadUser(); loadConfig(); if (getProfiles().size() == 0) { try { Identity.buildProfile("Default Profile"); } catch (IOException ex) { Logger.userError(ErrorLevel.FATAL, "Unable to write default profile", ex); } } // Set up the identity used for the addons defaults final ConfigTarget target = new ConfigTarget(); target.setGlobalDefault(); target.setOrder(500000); final ConfigFile addonConfigFile = new ConfigFile((File) null); final Map<String, String> addonSettings = new HashMap<String, String>(); addonSettings.put("name", "Addon defaults"); addonConfigFile.addDomain("identity", addonSettings); addonConfig = new Identity(addonConfigFile, target); IdentityManager.addIdentity(addonConfig); if (!getGlobalConfig().hasOptionString("identity", "defaultsversion")) { Logger.userError(ErrorLevel.FATAL, "Default settings " + "could not be loaded"); } } /** Loads the default (built in) identities. */ private static void loadDefaults() { final String[] targets = {"default", "modealiases"}; final String dir = getDirectory(); for (String target : targets) { final File file = new File(dir + target); if (!file.exists() || file.listFiles() == null || file.listFiles().length == 0) { file.mkdirs(); extractIdentities(target); } loadUser(file); } // If the bundled defaults are newer than the ones the user is // currently using, extract them. if (getGlobalConfig().hasOptionString("identity", "defaultsversion") && getGlobalConfig().hasOptionString("updater", "bundleddefaultsversion")) { final Version installedVersion = new Version(getGlobalConfig() .getOption("identity", "defaultsversion")); final Version bundledVersion = new Version(getGlobalConfig() .getOption("updater", "bundleddefaultsversion")); if (bundledVersion.compareTo(installedVersion) > 0) { extractIdentities("default"); loadUser(new File(dir, "default")); } } } /** * Extracts the specific set of default identities to the user's identity * folder. * * @param target The target to be extracted */ private static void extractIdentities(final String target) { try { ResourceManager.getResourceManager().extractResources( "com/dmdirc/config/defaults/" + target, getDirectory() + target, false); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to extract default " + "identities: " + ex.getMessage()); } } /** * Retrieves the directory used to store identities in. * * @return The identity directory path */ public static String getDirectory() { return Main.getConfigDir() + "identities" + System.getProperty("file.separator"); } /** Loads user-defined identity files. */ public static void loadUser() { final File dir = new File(getDirectory()); if (!dir.exists()) { try { dir.mkdirs(); dir.createNewFile(); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to create identity dir"); } } loadUser(dir); } /** * Recursively loads files from the specified directory. * * @param dir The directory to be loaded */ @Precondition({ "The specified File is not null", "The specified File is a directory" }) private static void loadUser(final File dir) { Logger.assertTrue(dir != null); Logger.assertTrue(dir.isDirectory()); if (dir.listFiles() == null) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load user identity files from " + dir.getAbsolutePath()); } else { for (File file : dir.listFiles()) { if (file.isDirectory()) { loadUser(file); } else { loadIdentity(file); } } } } /** * Loads an identity from the specified file. If the identity already * exists, it is told to reload instead. * * @param file The file to load the identity from. */ @SuppressWarnings("deprecation") private static void loadIdentity(final File file) { synchronized (identities) { for (Identity identity : identities) { if (file.equals(identity.getFile().getFile())) { try { identity.reload(); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "I/O error when reloading identity file: " + file.getAbsolutePath() + " (" + ex.getMessage() + ")"); } catch (InvalidConfigFileException ex) { // Do nothing } return; } } } try { addIdentity(new Identity(file, false)); } catch (InvalidIdentityFileException ex) { Logger.userError(ErrorLevel.MEDIUM, "Invalid identity file: " + file.getAbsolutePath() + " (" + ex.getMessage() + ")"); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "I/O error when reading identity file: " + file.getAbsolutePath()); } } /** Loads the version information. */ public static void loadVersion() { try { versionConfig = new Identity(Main.class.getResourceAsStream("version.config"), false); addIdentity(versionConfig); } catch (IOException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to load version information", ex); } catch (InvalidIdentityFileException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to load version information", ex); } } /** Loads the config identity. */ private static void loadConfig() { try { final File file = new File(Main.getConfigDir() + "dmdirc.config"); if (!file.exists()) { file.createNewFile(); } config = new Identity(file, true); config.setOption("identity", "name", "Global config"); addIdentity(config); } catch (InvalidIdentityFileException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to load global config", ex); } catch (IOException ex) { Logger.userError(ErrorLevel.FATAL, "I/O error when loading global config: " + ex.getMessage(), ex); } } /** * Retrieves the identity used for the global config. * * @return The global config identity */ public static Identity getConfigIdentity() { return config; } /** * Retrieves the identity used for addons defaults. * * @return The addons defaults identity */ public static Identity getAddonIdentity() { return addonConfig; } /** * Retrieves the identity bundled with the DMDirc client containing * version information. * * @return The version identity * @since 0.6.3m2 */ public static Identity getVersionIdentity() { return versionConfig; } /** * Saves all modified identity files to disk. */ public static void save() { synchronized (identities) { for (Identity identity : identities) { identity.save(); } } } /** * Adds the specific identity to this manager. * @param identity The identity to be added */ @Precondition("The specified Identity is not null") public static void addIdentity(final Identity identity) { Logger.assertTrue(identity != null); if (identities.contains(identity)) { removeIdentity(identity); } synchronized (identities) { identities.add(identity); } synchronized (managers) { for (ConfigManager manager : managers) { manager.checkIdentity(identity); } } } /** * Removes an identity from this manager. * @param identity The identity to be removed */ @Precondition({ "The specified Identity is not null", "The specified Identity has previously been added and not removed" }) public static void removeIdentity(final Identity identity) { Logger.assertTrue(identity != null); Logger.assertTrue(identities.contains(identity)); synchronized (identities) { identities.remove(identity); } synchronized (managers) { for (ConfigManager manager : managers) { manager.removeIdentity(identity); } } } /** * Adds a config manager to this manager. * @param manager The ConfigManager to add */ @Precondition("The specified ConfigManager is not null") public static void addConfigManager(final ConfigManager manager) { Logger.assertTrue(manager != null); synchronized (managers) { managers.add(manager); } } /** * Retrieves a list of identities that serve as profiles. * @return A list of profiles */ public static List<Identity> getProfiles() { final List<Identity> profiles = new ArrayList<Identity>(); synchronized (identities) { for (Identity identity : identities) { if (identity.isProfile()) { profiles.add(identity); } } } return profiles; } /** * Retrieves a list of all config sources that should be applied to the * specified config manager. * * @param manager The manager requesting sources * @return A list of all matching config sources */ public static List<Identity> getSources(final ConfigManager manager) { final List<Identity> sources = new ArrayList<Identity>(); synchronized (identities) { for (Identity identity : identities) { if (manager.identityApplies(identity)) { sources.add(identity); } } } Collections.sort(sources); return sources; } /** * Retrieves the global config manager. * * @return The global config manager */ public static synchronized ConfigManager getGlobalConfig() { if (globalconfig == null) { globalconfig = new ConfigManager("", "", ""); } return globalconfig; } /** * Retrieves the config for the specified channel@network. The config is * created if it doesn't exist. * * @param network The name of the network * @param channel The name of the channel * @return A config source for the channel */ @Precondition({ "The specified network is non-null and not empty", "The specified channel is non-null and not empty" }) public static Identity getChannelConfig(final String network, final String channel) { if (network == null || network.isEmpty()) { throw new IllegalArgumentException("getChannelConfig called " + "with null or empty network\n\nNetwork: " + network); } if (channel == null || channel.isEmpty()) { throw new IllegalArgumentException("getChannelConfig called " + "with null or empty channel\n\nChannel: " + channel); } final String myTarget = (channel + "@" + network).toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.CHANNEL && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setChannel(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create channel identity", ex); return null; } } /** * Retrieves the config for the specified network. The config is * created if it doesn't exist. * * @param network The name of the network * @return A config source for the network */ @Precondition("The specified network is non-null and not empty") public static Identity getNetworkConfig(final String network) { if (network == null || network.isEmpty()) { throw new IllegalArgumentException("getNetworkConfig called " + "with null or empty network\n\nNetwork:" + network); } final String myTarget = network.toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.NETWORK && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setNetwork(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create network identity", ex); return null; } } /** * Retrieves the config for the specified server. The config is * created if it doesn't exist. * * @param server The name of the server * @return A config source for the server */ @Precondition("The specified server is non-null and not empty") public static Identity getServerConfig(final String server) { if (server == null || server.isEmpty()) { throw new IllegalArgumentException("getServerConfig called " + "with null or empty server\n\nServer: " + server); } final String myTarget = server.toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.SERVER && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setServer(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create network identity", ex); return null; } } }
src/com/dmdirc/config/IdentityManager.java
/* * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes * * 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.dmdirc.config; import com.dmdirc.Main; import com.dmdirc.Precondition; import com.dmdirc.logger.ErrorLevel; import com.dmdirc.logger.Logger; import com.dmdirc.updater.Version; import com.dmdirc.util.ConfigFile; import com.dmdirc.util.InvalidConfigFileException; import com.dmdirc.util.WeakList; import com.dmdirc.util.resourcemanager.ResourceManager; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The identity manager manages all known identities, providing easy methods * to access them. * * @author chris */ public final class IdentityManager { /** The identities that have been loaded into this manager. */ private final static List<Identity> identities = new ArrayList<Identity>(); /** The config managers that have registered with this manager. */ private final static List<ConfigManager> managers = new WeakList<ConfigManager>(); /** The identity file used for the global config. */ private static Identity config; /** The identity file used for addon defaults. */ private static Identity addonConfig; /** The identity file bundled with the client containing version info. */ private static Identity versionConfig; /** The config manager used for global settings. */ private static ConfigManager globalconfig; /** Creates a new instance of IdentityManager. */ private IdentityManager() { } /** Loads all identity files. */ public static void load() { identities.clear(); managers.clear(); if (globalconfig != null) { // May have been created earlier managers.add(globalconfig); } loadVersion(); loadDefaults(); loadUser(); loadConfig(); if (getProfiles().size() == 0) { try { Identity.buildProfile("Default Profile"); } catch (IOException ex) { Logger.userError(ErrorLevel.FATAL, "Unable to write default profile", ex); } } // Set up the identity used for the addons defaults final ConfigTarget target = new ConfigTarget(); target.setGlobalDefault(); target.setOrder(500000); final ConfigFile addonConfigFile = new ConfigFile((File) null); final Map<String, String> addonSettings = new HashMap<String, String>(); addonSettings.put("name", "Addon defaults"); addonConfigFile.addDomain("identity", addonSettings); addonConfig = new Identity(addonConfigFile, target); IdentityManager.addIdentity(addonConfig); if (!getGlobalConfig().hasOptionString("identity", "defaultsversion")) { Logger.userError(ErrorLevel.FATAL, "Default settings " + "could not be loaded"); } } /** Loads the default (built in) identities. */ private static void loadDefaults() { final String[] targets = {"default", "modealiases"}; final String dir = getDirectory(); for (String target : targets) { final File file = new File(dir + target); if (!file.exists() || file.listFiles() == null || file.listFiles().length == 0) { file.mkdirs(); extractIdentities(target); } loadUser(file); } // If the bundled defaults are newer than the ones the user is // currently using, extract them. if (getGlobalConfig().hasOptionString("identity", "defaultsversion") && getGlobalConfig().hasOptionString("updater", "bundleddefaultsversion")) { final Version installedVersion = new Version(getGlobalConfig() .getOption("identity", "defaultsversion")); final Version bundledVersion = new Version(getGlobalConfig() .getOption("updater", "bundleddefaultsversion")); if (bundledVersion.compareTo(installedVersion) > 0) { extractIdentities("default"); loadUser(new File(dir, "default")); } } } /** * Extracts the specific set of default identities to the user's identity * folder. * * @param target The target to be extracted */ private static void extractIdentities(final String target) { try { ResourceManager.getResourceManager().extractResources( "com/dmdirc/config/defaults/" + target, getDirectory() + target, false); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to extract default " + "identities: " + ex.getMessage()); } } /** * Retrieves the directory used to store identities in. * * @return The identity directory path */ public static String getDirectory() { return Main.getConfigDir() + "identities" + System.getProperty("file.separator"); } /** Loads user-defined identity files. */ public static void loadUser() { final File dir = new File(getDirectory()); if (!dir.exists()) { try { dir.mkdirs(); dir.createNewFile(); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "Unable to create identity dir"); } } loadUser(dir); } /** * Recursively loads files from the specified directory. * * @param dir The directory to be loaded */ @Precondition({ "The specified File is not null", "The specified File is a directory" }) private static void loadUser(final File dir) { Logger.assertTrue(dir != null); Logger.assertTrue(dir.isDirectory()); if (dir.listFiles() == null) { Logger.userError(ErrorLevel.MEDIUM, "Unable to load user identity files from " + dir.getAbsolutePath()); } else { for (File file : dir.listFiles()) { if (file.isDirectory()) { loadUser(file); } else { loadIdentity(file); } } } } /** * Loads an identity from the specified file. If the identity already * exists, it is told to reload instead. * * @param file The file to load the identity from. */ @SuppressWarnings("deprecation") private static void loadIdentity(final File file) { synchronized (identities) { for (Identity identity : identities) { if (file.equals(identity.getFile().getFile())) { try { identity.reload(); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "I/O error when reloading identity file: " + file.getAbsolutePath() + " (" + ex.getMessage() + ")"); } catch (InvalidConfigFileException ex) { // Do nothing } return; } } } try { addIdentity(new Identity(file, false)); } catch (InvalidIdentityFileException ex) { Logger.userError(ErrorLevel.MEDIUM, "Invalid identity file: " + file.getAbsolutePath() + " (" + ex.getMessage() + ")"); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "I/O error when reading identity file: " + file.getAbsolutePath()); } } /** Loads the version information. */ public static void loadVersion() { try { versionConfig = new Identity(Main.class.getResourceAsStream("version.config"), false); addIdentity(versionConfig); } catch (IOException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to load version information", ex); } catch (InvalidIdentityFileException ex) { Logger.appError(ErrorLevel.FATAL, "Unable to load version information", ex); } } /** Loads the config identity. */ private static void loadConfig() { try { final File file = new File(Main.getConfigDir() + "dmdirc.config"); if (!file.exists()) { file.createNewFile(); } config = new Identity(file, true); config.setOption("identity", "name", "Global config"); addIdentity(config); } catch (InvalidIdentityFileException ex) { // This shouldn't happen as we're forcing it to global Logger.appError(ErrorLevel.HIGH, "Unable to load global config", ex); } catch (IOException ex) { Logger.userError(ErrorLevel.MEDIUM, "I/O error when loading file: " + ex.getMessage()); } } /** * Retrieves the identity used for the global config. * * @return The global config identity */ public static Identity getConfigIdentity() { return config; } /** * Retrieves the identity used for addons defaults. * * @return The addons defaults identity */ public static Identity getAddonIdentity() { return addonConfig; } /** * Retrieves the identity bundled with the DMDirc client containing * version information. * * @return The version identity * @since 0.6.3m2 */ public static Identity getVersionIdentity() { return versionConfig; } /** * Saves all modified identity files to disk. */ public static void save() { synchronized (identities) { for (Identity identity : identities) { identity.save(); } } } /** * Adds the specific identity to this manager. * @param identity The identity to be added */ @Precondition("The specified Identity is not null") public static void addIdentity(final Identity identity) { Logger.assertTrue(identity != null); if (identities.contains(identity)) { removeIdentity(identity); } synchronized (identities) { identities.add(identity); } synchronized (managers) { for (ConfigManager manager : managers) { manager.checkIdentity(identity); } } } /** * Removes an identity from this manager. * @param identity The identity to be removed */ @Precondition({ "The specified Identity is not null", "The specified Identity has previously been added and not removed" }) public static void removeIdentity(final Identity identity) { Logger.assertTrue(identity != null); Logger.assertTrue(identities.contains(identity)); synchronized (identities) { identities.remove(identity); } synchronized (managers) { for (ConfigManager manager : managers) { manager.removeIdentity(identity); } } } /** * Adds a config manager to this manager. * @param manager The ConfigManager to add */ @Precondition("The specified ConfigManager is not null") public static void addConfigManager(final ConfigManager manager) { Logger.assertTrue(manager != null); synchronized (managers) { managers.add(manager); } } /** * Retrieves a list of identities that serve as profiles. * @return A list of profiles */ public static List<Identity> getProfiles() { final List<Identity> profiles = new ArrayList<Identity>(); synchronized (identities) { for (Identity identity : identities) { if (identity.isProfile()) { profiles.add(identity); } } } return profiles; } /** * Retrieves a list of all config sources that should be applied to the * specified config manager. * * @param manager The manager requesting sources * @return A list of all matching config sources */ public static List<Identity> getSources(final ConfigManager manager) { final List<Identity> sources = new ArrayList<Identity>(); synchronized (identities) { for (Identity identity : identities) { if (manager.identityApplies(identity)) { sources.add(identity); } } } Collections.sort(sources); return sources; } /** * Retrieves the global config manager. * * @return The global config manager */ public static synchronized ConfigManager getGlobalConfig() { if (globalconfig == null) { globalconfig = new ConfigManager("", "", ""); } return globalconfig; } /** * Retrieves the config for the specified channel@network. The config is * created if it doesn't exist. * * @param network The name of the network * @param channel The name of the channel * @return A config source for the channel */ @Precondition({ "The specified network is non-null and not empty", "The specified channel is non-null and not empty" }) public static Identity getChannelConfig(final String network, final String channel) { if (network == null || network.isEmpty()) { throw new IllegalArgumentException("getChannelConfig called " + "with null or empty network\n\nNetwork: " + network); } if (channel == null || channel.isEmpty()) { throw new IllegalArgumentException("getChannelConfig called " + "with null or empty channel\n\nChannel: " + channel); } final String myTarget = (channel + "@" + network).toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.CHANNEL && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setChannel(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create channel identity", ex); return null; } } /** * Retrieves the config for the specified network. The config is * created if it doesn't exist. * * @param network The name of the network * @return A config source for the network */ @Precondition("The specified network is non-null and not empty") public static Identity getNetworkConfig(final String network) { if (network == null || network.isEmpty()) { throw new IllegalArgumentException("getNetworkConfig called " + "with null or empty network\n\nNetwork:" + network); } final String myTarget = network.toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.NETWORK && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setNetwork(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create network identity", ex); return null; } } /** * Retrieves the config for the specified server. The config is * created if it doesn't exist. * * @param server The name of the server * @return A config source for the server */ @Precondition("The specified server is non-null and not empty") public static Identity getServerConfig(final String server) { if (server == null || server.isEmpty()) { throw new IllegalArgumentException("getServerConfig called " + "with null or empty server\n\nServer: " + server); } final String myTarget = server.toLowerCase(); synchronized (identities) { for (Identity identity : identities) { if (identity.getTarget().getType() == ConfigTarget.TYPE.SERVER && identity.getTarget().getData().equalsIgnoreCase(myTarget)) { return identity; } } } // We need to create one final ConfigTarget target = new ConfigTarget(); target.setServer(myTarget); try { return Identity.buildIdentity(target); } catch (IOException ex) { Logger.userError(ErrorLevel.HIGH, "Unable to create network identity", ex); return null; } } }
The global config not loading is now a fatal error Fixes issue 3085 Change-Id: Id88b8c70f461012ac8aad40f3484cd5648e685c9 Reviewed-on: http://gerrit.dmdirc.com/54 Reviewed-by: Shane Mc Cormack <[email protected]> Tested-by: Hudson <[email protected]>
src/com/dmdirc/config/IdentityManager.java
The global config not loading is now a fatal error
Java
mit
3ffb16be2ed543899c51b439a1d1c6d895321da5
0
godotgildor/igv,igvteam/igv,amwenger/igv,godotgildor/igv,itenente/igv,godotgildor/igv,amwenger/igv,itenente/igv,godotgildor/igv,amwenger/igv,igvteam/igv,igvteam/igv,itenente/igv,godotgildor/igv,itenente/igv,igvteam/igv,itenente/igv,igvteam/igv,amwenger/igv,amwenger/igv
/* * Copyright (c) 2007-2011 by The Broad Institute, Inc. and the Massachusetts Institute of * Technology. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.track; import org.apache.log4j.Logger; import org.broad.igv.PreferenceManager; import org.broad.igv.das.DASFeatureSource; import org.broad.igv.data.*; import org.broad.igv.data.expression.GCTDataset; import org.broad.igv.data.expression.GCTDatasetParser; import org.broad.igv.data.rnai.RNAIDataSource; import org.broad.igv.data.rnai.RNAIGCTDatasetParser; import org.broad.igv.data.rnai.RNAIGeneScoreParser; import org.broad.igv.data.rnai.RNAIHairpinParser; import org.broad.igv.data.seg.FreqData; import org.broad.igv.data.seg.SegmentedAsciiDataSet; import org.broad.igv.data.seg.SegmentedBinaryDataSet; import org.broad.igv.data.seg.SegmentedDataSource; import org.broad.igv.exceptions.DataLoadException; import org.broad.igv.feature.*; import org.broad.igv.feature.dranger.DRangerParser; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.tribble.FeatureFileHeader; import org.broad.igv.goby.GobyAlignmentQueryReader; import org.broad.igv.goby.GobyCountArchiveDataSource; import org.broad.igv.gwas.GWASData; import org.broad.igv.gwas.GWASParser; import org.broad.igv.gwas.GWASTrack; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.lists.VariantListManager; import org.broad.igv.maf.MAFTrack; import org.broad.igv.maf.conservation.OmegaDataSource; import org.broad.igv.maf.conservation.OmegaTrack; import org.broad.igv.peaks.PeakTrack; import org.broad.igv.renderer.*; import org.broad.igv.sam.*; import org.broad.igv.sam.reader.IndexNotFoundException; import org.broad.igv.synteny.BlastMapping; import org.broad.igv.synteny.BlastParser; import org.broad.igv.tdf.TDFDataSource; import org.broad.igv.tdf.TDFReader; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.ConfirmDialog; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.IGVHttpUtils; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.vcf.PedigreeUtils; import org.broad.igv.vcf.VCFTrack; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * User: jrobinso * Date: Feb 14, 2010 */ public class TrackLoader { private static Logger log = Logger.getLogger(TrackLoader.class); private IGV igv; /** * Switches on various attributes of locator (mainly locator path extension and whether the locator is indexed) * to call the appropriate loading method. * * @param locator * @return */ public List<Track> load(ResourceLocator locator, IGV igv) { this.igv = igv; Genome genome = igv.getGenomeManager().getCurrentGenome(); final String path = locator.getPath(); try { String typeString = locator.getType(); if (typeString == null) { // Genome space hack if ((path.contains("?dataFormat") || path.contains("%3Fdataformat")) && (path.contains("dataformat/gct") || path.contains("dataformat%2Fgct"))) { typeString = ".gct"; } else { typeString = path.toLowerCase(); if (!typeString.endsWith("_sorted.txt") && (typeString.endsWith(".txt") || typeString.endsWith( ".xls") || typeString.endsWith(".gz"))) { typeString = typeString.substring(0, typeString.lastIndexOf(".")); } } } typeString = typeString.toLowerCase(); if (typeString.endsWith(".tbi")) { MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" + " load the associated gzipped file, which should have an extension of '.gz'"); } //TODO Why is this not inside of isIndexed? //dhmay seconding this question -- this appears to be taken care of already in isIndexed() // Check for index boolean hasIndex = false; if (locator.isLocal()) { File indexFile = new File(path + ".sai"); hasIndex = indexFile.exists(); } //This list will hold all new tracks created for this locator List<Track> newTracks = new ArrayList<Track>(); if (typeString.endsWith(".gmt")) { loadGMT(locator); } else if (typeString.equals("das")) { loadDASResource(locator, newTracks); } else if (isIndexed(path)) { loadIndexed(locator, newTracks, genome); } else if (typeString.endsWith(".vcf") || typeString.endsWith(".vcf4")) { // TODO This is a hack, vcf files must be indexed. Fix in next release. throw new IndexNotFoundException(path); } else if (typeString.endsWith(".trio")) { loadTrioData(locator); } else if (typeString.endsWith("varlist")) { VariantListManager.loadVariants(locator); } else if (typeString.endsWith("samplepathmap")) { VariantListManager.loadSamplePathMap(locator); } else if (typeString.endsWith("h5") || typeString.endsWith("hbin")) { loadH5File(locator, newTracks, genome); } else if (typeString.endsWith(".rnai.gct")) { loadRnaiGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) { loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") || typeString.endsWith(".igv") || typeString.endsWith(".loh")) { loadIGVFile(locator, newTracks, genome); } else if (typeString.endsWith(".mut")) { loadMutFile(locator, newTracks, genome); } else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") || typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls")) { loadSegFile(locator, newTracks, genome); } else if (typeString.endsWith(".seg.zip")) { loadBinarySegFile(locator, newTracks, genome); } else if (typeString.endsWith(".gistic")) { loadGisticFile(locator, newTracks); } else if (typeString.endsWith(".gs")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome); } else if (typeString.endsWith(".riger")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome); } else if (typeString.endsWith(".hp")) { loadRNAiHPScoreFile(locator); } else if (typeString.endsWith("gene")) { loadGeneFile(locator, newTracks, genome); } else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) { loadSyntentyMapping(locator, newTracks); } else if (typeString.endsWith(".sam") || typeString.endsWith(".bam") || typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") || typeString.endsWith("_sorted.txt") || typeString.endsWith(".aligned") || typeString.endsWith(".sai") || typeString.endsWith(".bai")) { loadAlignmentsTrack(locator, newTracks, genome); } else if (typeString.endsWith(".bedz") || (typeString.endsWith(".bed") && hasIndex)) { loadIndexdBedFile(locator, newTracks, genome); } else if (typeString.endsWith(".omega")) { loadOmegaTrack(locator, newTracks, genome); } else if (typeString.endsWith(".wig") || (typeString.endsWith(".bedgraph")) || typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) { loadWigFile(locator, newTracks, genome); } else if (typeString.endsWith(".list")) { loadListFile(locator, newTracks, genome); } else if (typeString.contains(".dranger")) { loadDRangerFile(locator, newTracks, genome); } else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) { loadEwigIBFFile(locator, newTracks, genome); } else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) { loadTDFFile(locator, newTracks, genome); } else if (typeString.endsWith(".counts")) { loadGobyCountsArchive(locator, newTracks, genome); } else if (typeString.endsWith(".psl") || typeString.endsWith(".psl.gz") || typeString.endsWith(".pslx") || typeString.endsWith(".pslx.gz")) { loadPslFile(locator, newTracks, genome); //AbstractFeatureParser.getInstanceFor() is called twice. Wasteful } else if (AbstractFeatureParser.getInstanceFor(locator, genome) != null) { loadFeatureFile(locator, newTracks, genome); } else if (MutationParser.isMutationAnnotationFile(locator)) { this.loadMutFile(locator, newTracks, genome); } else if (WiggleParser.isWiggle(locator)) { loadWigFile(locator, newTracks, genome); } else if (path.toLowerCase().contains(".maf")) { loadMAFTrack(locator, newTracks); } else if (path.toLowerCase().contains(".peak.cfg")) { loadPeakTrack(locator, newTracks, genome); } else if ("mage-tab".equals(locator.getType()) || GCTDatasetParser.parsableMAGE_TAB(locator)) { locator.setDescription("MAGE_TAB"); loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".logistic") || typeString.endsWith(".linear") || typeString.endsWith(".assoc") || typeString.endsWith(".qassoc") || typeString.endsWith(".gwas")) { loadGWASFile(locator, newTracks); } else if (GCTDatasetParser.isGCT(path)) { loadGctFile(locator, newTracks, genome); } else if (GobyAlignmentQueryReader.supportsFileType(path)) { loadAlignmentsTrack(locator, newTracks, genome); } else if (AttributeManager.isSampleInfoFile(locator)) { // This might be a sample information file. AttributeManager.getInstance().loadSampleInfo(locator); } else { MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extenstion"); } // Track line TrackProperties tp = null; String trackLine = locator.getTrackLine(); if (trackLine != null) { tp = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, tp); } for (Track track : newTracks) { if (locator.getUrl() != null) { track.setUrl(locator.getUrl()); } if (tp != null) { track.setProperties(tp); } if (locator.getColor() != null) { track.setColor(locator.getColor()); } if (locator.getSampleId() != null) { track.setSampleId(locator.getSampleId()); } } return newTracks; } catch (DataLoadException dle) { throw dle; } catch (Exception e) { log.error(e); throw new DataLoadException(e.getMessage(), path); } } private void loadGMT(ResourceLocator locator) throws IOException { List<GeneList> lists = GeneListManager.getInstance().importGMTFile(locator.getPath()); if (lists.size() == 1) { GeneList gl = lists.get(0); IGV.getInstance().setGeneList(gl.getName(), true); } else { MessageUtils.showMessage("Loaded " + lists.size() + " gene lists."); } } private void loadIndexed(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { TribbleFeatureSource src = new TribbleFeatureSource(locator.getPath(), genome); String typeString = locator.getPath(); //Track t; if (typeString.endsWith("vcf") || typeString.endsWith("vcf.gz")) { VCFTrack t = new VCFTrack(locator, src); // VCF tracks handle their own margin t.setMargin(0); newTracks.add(t); } else { // Create feature source and track FeatureTrack t = new FeatureTrack(locator, src); t.setName(locator.getTrackName()); //t.setRendererClass(BasicTribbleRenderer.class); // Set track properties from header Object header = src.getHeader(); if (header != null && header instanceof FeatureFileHeader) { FeatureFileHeader ffh = (FeatureFileHeader) header; if (ffh.getTrackType() != null) { t.setTrackType(ffh.getTrackType()); } if (ffh.getTrackProperties() != null) { t.setProperties(ffh.getTrackProperties()); } if (ffh.getTrackType() == TrackType.REPMASK) { t.setHeight(15); t.setPreferredHeight(15); } } newTracks.add(t); } } /** * Load the input file as a BED or Attribute (Sample Info) file. First assume * it is a BED file, if no features are found load as an attribute file. * * @param locator * @param newTracks */ private void loadGeneFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome); if (featureParser != null) { List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); } } private void loadSyntentyMapping(ResourceLocator locator, List<Track> newTracks) { List<BlastMapping> mappings = (new BlastParser()).parse(locator.getPath()); List<org.broad.tribble.Feature> features = new ArrayList<org.broad.tribble.Feature>(mappings.size()); features.addAll(mappings); Genome genome = igv.getGenomeManager().getCurrentGenome(); FeatureTrack track = new FeatureTrack(locator, new FeatureCollectionSource(features, genome)); track.setName(locator.getTrackName()); // track.setRendererClass(AlignmentBlockRenderer.class); newTracks.add(track); } private void loadDRangerFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { DRangerParser parser = new DRangerParser(); newTracks.addAll(parser.loadTracks(locator, genome)); } /** * Load the input file as a feature, mutation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadPslFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { PSLParser featureParser = new PSLParser(genome); List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); for (FeatureTrack t : tracks) { t.setMinimumHeight(10); t.setHeight(30); t.setPreferredHeight(30); t.setDisplayMode(Track.DisplayMode.EXPANDED); } } /** * Load the input file as a feature, muation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadFeatureFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { if (locator.isLocal() && (locator.getPath().endsWith(".bed") || locator.getPath().endsWith(".bed.txt") || locator.getPath().endsWith(".bed.gz"))) { //checkSize takes care of warning the user if (!checkSize(locator.getPath())) { return; } } FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome); if (featureParser != null) { List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); } else if (MutationParser.isMutationAnnotationFile(locator)) { this.loadMutFile(locator, newTracks, genome); } else if (WiggleParser.isWiggle(locator)) { loadWigFile(locator, newTracks, genome); } else if (locator.getPath().toLowerCase().contains(".maf")) { loadMAFTrack(locator, newTracks); } } /** * Load the input file as a feature, muation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadIndexdBedFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { File featureFile = new File(locator.getPath()); File indexFile = new File(locator.getPath() + ".sai"); FeatureSource src = new IndexedBEDFeatureSource(featureFile, indexFile, genome); Track t = new FeatureTrack(locator, src); newTracks.add(t); } /** * Load GWAS PLINK result file * * @param locator * @param newTracks * @throws IOException */ private void loadGWASFile(ResourceLocator locator, List<Track> newTracks) throws IOException { GWASParser gwasParser = new GWASParser(locator); GWASData gwasData = gwasParser.parse(); GWASTrack gwasTrack = new GWASTrack(locator, locator.getPath(), locator.getFileName(), gwasData, gwasParser); newTracks.add(gwasTrack); } private void loadRnaiGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { RNAIGCTDatasetParser parser = new RNAIGCTDatasetParser(locator, genome); Collection<RNAIDataSource> dataSources = parser.parse(); if (dataSources != null) { String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String trackId = path + "_" + ds.getName(); DataSourceTrack track = new DataSourceTrack(locator, trackId, ds.getName(), ds, genome); // Set attributes. track.setAttributeValue("SCREEN", ds.getScreen()); track.setHeight(80); track.setPreferredHeight(80); newTracks.add(track); } } } private void loadGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } GCTDatasetParser parser = null; GCTDataset ds = null; String fName = locator.getTrackName(); // TODO -- handle remote resource try { parser = new GCTDatasetParser(locator, null, igv.getGenomeManager().getCurrentGenome()); } catch (IOException e) { log.error("Error creating GCT parser.", e); throw new DataLoadException("Error creating GCT parser: " + e, locator.getPath()); } ds = parser.createDataset(); ds.setName(fName); ds.setNormalized(true); ds.setLogValues(true); /* * File outputFile = new File(IGV.DEFAULT_USER_DIRECTORY, file.getName() + ".h5"); * OverlappingProcessor proc = new OverlappingProcessor(ds); * proc.setZoomMax(0); * proc.process(outputFile.getAbsolutePath()); * loadH5File(outputFile, messages, attributeList, group); */ // Counter for generating ID TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); for (String trackName : ds.getTrackNames()) { Genome currentGenome = igv.getGenomeManager().getCurrentGenome(); DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, currentGenome); String trackId = path + "_" + trackName; Track track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setProperties(trackProperties); newTracks.add(track); } } private void loadIGVFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } String dsName = locator.getTrackName(); IGVDataset ds = new IGVDataset(locator, genome, igv); ds.setName(dsName); TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); TrackType type = ds.getType(); for (String trackName : ds.getTrackNames()) { DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, genome); String trackId = path + "_" + trackName; DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); // track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); track.setProperties(trackProperties); if (type == TrackType.ALLELE_FREQUENCY) { track.setRendererClass(ScatterplotRenderer.class); track.setHeight(40); track.setPreferredHeight(40); } newTracks.add(track); } } private boolean checkSize(String file) { if (!PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_SIZE_WARNING)) { return true; } File f = new File(file); String tmp = file; if (f.exists()) { long size = f.length(); if (file.endsWith(".gz")) { size *= 3; tmp = file.substring(0, file.length() - 3); } if (size > 50000000) { String message = ""; if (tmp.endsWith(".bed") || tmp.endsWith(".bed.txt")) { message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " + "that large files be indexed using IGVTools or Tabix. Loading un-indexed " + "ascii fies of this size can lead to poor performance or unresponsiveness (freezing). " + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a command line program. " + "See the user guide for more details.<br><br>Click <b>Continue</b> to continue loading, or <b>Cancel</b>" + " to skip this file."; } else { message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " + "that large files be converted to the binary <i>.tdf</i> format using the IGVTools " + "<b>tile</b> command. Loading unconverted ascii fies of this size can lead to poor " + "performance or unresponsiveness (freezing). " + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a " + "command line program. See the user guide for more details.<br><br>Click <b>Continue</b> " + "to continue loading, or <b>Cancel</b> to skip this file."; } return ConfirmDialog.optionallyShowConfirmDialog(message, PreferenceManager.SHOW_SIZE_WARNING, true); } } return true; } private void loadDOTFile(ResourceLocator locator, List<Track> newTracks) { //GraphTrack gt = new GraphTrack(locator); //gt.setHeight(80); //newTracks.add(gt); } private void loadWigFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } WiggleDataset ds = (new WiggleParser(locator, genome)).parse(); TrackProperties props = ds.getTrackProperties(); // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = props == null ? null : props.getName(); String label = locator.getName(); if (name == null) { name = locator.getFileName(); } else if (label != null) { props.setName(label); // erase name rom track properties } String path = locator.getPath(); boolean multiTrack = ds.getTrackNames().length > 1; for (String heading : ds.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; Genome currentGenome = IGV.getInstance().getGenomeManager().getCurrentGenome(); DatasetDataSource dataSource = new DatasetDataSource(trackId, ds, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); String displayName = (label == null || multiTrack) ? heading : label; track.setName(displayName); track.setProperties(props); track.setTrackType(ds.getType()); if (ds.getType() == TrackType.EXPR) { track.setWindowFunction(WindowFunction.none); } newTracks.add(track); } } private void loadTDFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (log.isDebugEnabled()) { log.debug("Loading TDFFile: " + locator.toString()); } TDFReader reader = TDFReader.getReader(locator.getPath()); TrackType type = reader.getTrackType(); if (log.isDebugEnabled()) { log.debug("Parsing track line "); } TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = locator.getName(); if (name != null && props != null) { props.setName(name); } if (name == null) { name = props == null ? locator.getTrackName() : props.getName(); } int trackNumber = 0; String path = locator.getPath(); boolean multiTrack = reader.getTrackNames().length > 1; for (String heading : reader.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; final DataSource dataSource = locator.getPath().endsWith(".counts") ? new GobyCountArchiveDataSource(locator) : new TDFDataSource(reader, trackNumber, heading, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); String displayName = (name == null || multiTrack) ? heading : name; track.setName(displayName); track.setTrackType(type); if (props != null) { track.setProperties(props); } newTracks.add(track); trackNumber++; } } private void loadGobyCountsArchive(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (log.isDebugEnabled()) { log.debug("Loading Goby counts archive: " + locator.toString()); } String trackId = locator.getSampleId() + " coverage"; String trackName = locator.getFileName(); final DataSource dataSource = new GobyCountArchiveDataSource(locator); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); newTracks.add(track); } private void loadEwigIBFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { TDFReader reader = TDFReader.getReader(locator.getPath()); TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } EWigTrack track = new EWigTrack(locator, genome); if (props != null) { track.setProperties(props); } track.setName(locator.getTrackName()); newTracks.add(track); } private void loadListFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { try { FeatureSource source = new FeatureDirSource(locator, genome); FeatureTrack track = new FeatureTrack(locator, source); track.setName(locator.getTrackName()); track.setVisibilityWindow(0); newTracks.add(track); } catch (IOException ex) { throw new RuntimeException(ex); } } private void loadGisticFile(ResourceLocator locator, List<Track> newTracks) { GisticTrack track = GisticFileParser.loadData(locator); track.setName(locator.getTrackName()); newTracks.add(track); } /** * Load a rnai gene score file and create a datasource and track. * <p/> * // TODO -- change parser to use resource locator rather than path. * * @param locator * @param newTracks */ private void loadRNAiGeneScoreFile(ResourceLocator locator, List<Track> newTracks, RNAIGeneScoreParser.Type type, Genome genome) { RNAIGeneScoreParser parser = new RNAIGeneScoreParser(locator.getPath(), type, genome); Collection<RNAIDataSource> dataSources = parser.parse(); String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String name = ds.getName(); String trackId = path + "_" + name; DataSourceTrack track = new DataSourceTrack(locator, trackId, name, ds, genome); // Set attributes. This "hack" is neccessary to register these attributes with the // attribute manager to get displayed. track.setAttributeValue("SCREEN", ds.getScreen()); if ((ds.getCondition() != null) && (ds.getCondition().length() > 0)) { track.setAttributeValue("CONDITION", ds.getCondition()); } track.setHeight(80); track.setPreferredHeight(80); //track.setDataRange(new DataRange(-3, 0, 3)); newTracks.add(track); } } /** * Load a RNAi haripin score file. The results of this action are hairpin scores * added to the RNAIDataManager. Currently no tracks are created for hairpin * scores, although this could change. * * @param locator */ private void loadRNAiHPScoreFile(ResourceLocator locator) { (new RNAIHairpinParser(locator.getPath())).parse(); } private void loadMAFTrack(ResourceLocator locator, List<Track> newTracks) { MAFTrack t = new MAFTrack(locator); t.setName("Multiple Alignments"); newTracks.add(t); } private void loadPeakTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { PeakTrack t = new PeakTrack(locator, genome); newTracks.add(t); } private void loadOmegaTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) { OmegaDataSource ds = new OmegaDataSource(genome); OmegaTrack track = new OmegaTrack(locator, ds, genome); track.setName("Conservation (Omega)"); track.setHeight(40); track.setPreferredHeight(40); newTracks.add(track); } /** * Load a rnai gene score file and create a datasource and track. * * @param locator * @param newTracks */ private void loadAlignmentsTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { try { String dsName = locator.getTrackName(); String fn = locator.getPath().toLowerCase(); boolean isBed = fn.endsWith(".bedz") || fn.endsWith(".bed") || fn.endsWith(".bed.gz"); // If the user tried to load the index, look for the file (this is a common mistake) if (locator.getPath().endsWith(".sai") || locator.getPath().endsWith(".bai")) { MessageUtils.showMessage("<html><b>ERROR:</b> Loading SAM/BAM index files are not supported: " + locator.getPath() + "<br>Load the SAM or BAM file directly. "); return; } AlignmentDataManager dataManager = new AlignmentDataManager(locator); if (locator.getPath().toLowerCase().endsWith(".bam")) { if (!dataManager.hasIndex()) { MessageUtils.showMessage("<html>Could not load index file for: " + locator.getPath() + "<br> An index file is required for SAM & BAM files."); return; } } AlignmentTrack alignmentTrack = new AlignmentTrack(locator, dataManager, genome); // parser.loadTrack(locator, dsName); alignmentTrack.setName(dsName); if (isBed) { alignmentTrack.setRenderer(new BedRenderer()); alignmentTrack.setPreferredHeight(40); alignmentTrack.setHeight(40); } // Create coverage track CoverageTrack covTrack = new CoverageTrack(locator.getPath() + "_coverage", alignmentTrack.getName() + " Coverage", genome); covTrack.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_COV_TRACK)); newTracks.add(covTrack); alignmentTrack.setCoverageTrack(covTrack); if (!isBed) { covTrack.setDataManager(dataManager); dataManager.setCoverageTrack(covTrack); } // Search for precalculated coverage data String covPath = locator.getCoverage(); if (covPath == null) { String path = locator.getPath(); covPath = path + ".tdf"; } if (covPath != null) { try { if ((new File(covPath)).exists() || (IGVHttpUtils.isURL(covPath) && IGVHttpUtils.resourceAvailable(new URL(covPath)))) { TDFReader reader = TDFReader.getReader(covPath); TDFDataSource ds = new TDFDataSource(reader, 0, alignmentTrack.getName() + " coverage", genome); covTrack.setDataSource(ds); } } catch (MalformedURLException e) { // This is expected if // log.info("Could not loading coverage data: MalformedURL: " + covPath); } } boolean showSpliceJunctionTrack = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK); if (showSpliceJunctionTrack) { SpliceJunctionFinderTrack spliceJunctionTrack = new SpliceJunctionFinderTrack(locator.getPath() + "_junctions", alignmentTrack.getName() + " Junctions", dataManager); // spliceJunctionTrack.setDataManager(dataManager); spliceJunctionTrack.setHeight(60); spliceJunctionTrack.setPreferredHeight(60); spliceJunctionTrack.setVisible(showSpliceJunctionTrack); newTracks.add(spliceJunctionTrack); alignmentTrack.setSpliceJunctionTrack(spliceJunctionTrack); } newTracks.add(alignmentTrack); } catch (IndexNotFoundException e) { MessageUtils.showMessage("<html>Could not find the index file for <br><br>&nbsp;&nbsp;" + e.getSamFile() + "<br><br>Note: The index file can be created using igvtools and must be in the same directory as the .sam file."); } } /** * Load a ".mut" file (muation file) and create tracks. * * @param locator * @param newTracks */ private void loadMutFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { MutationParser parser = new MutationParser(); List<FeatureTrack> mutationTracks = parser.loadMutationTracks(locator, genome); for (FeatureTrack track : mutationTracks) { track.setTrackType(TrackType.MUTATION); track.setRendererClass(MutationRenderer.class); newTracks.add(track); } } private void loadSegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { // TODO - -handle remote resource SegmentedAsciiDataSet ds = new SegmentedAsciiDataSet(locator, genome); String path = locator.getPath(); TrackProperties props = ds.getTrackProperties(); // The "freq" track. TODO - make this optional if (ds.getSampleNames().size() > 1) { FreqData fd = new FreqData(ds, genome); String freqTrackId = path; String freqTrackName = (new File(path)).getName(); CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd); newTracks.add(freqTrack); } for (String trackName : ds.getDataHeadings()) { String trackId = path + "_" + trackName; SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); if (props != null) { track.setProperties(props); } newTracks.add(track); } } private void loadBinarySegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { SegmentedBinaryDataSet ds = new SegmentedBinaryDataSet(locator); String path = locator.getPath(); // The "freq" track. Make this optional? FreqData fd = new FreqData(ds, genome); String freqTrackId = path; String freqTrackName = (new File(path)).getName(); CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd); newTracks.add(freqTrack); for (String trackName : ds.getSampleNames()) { String trackId = path + "_" + trackName; SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); newTracks.add(track); } } /** * Load the data from an HDF5 file and add resulting tracks to the supplied TrackGroup. * Error messages are appended to the MessageCollection * * @param locator */ private void loadH5File(ResourceLocator locator, List<Track> newTracks, Genome genome) { TrackSet trackSet = null; // TODO -- temporary until "name" property is added to locator // TODO -- "label" has been added, how does that affect this? String fName = locator.getTrackName(); HDFDataManager dataManager = HDFDataManagerFactory.getDataManager(locator); TrackProperties trackProperties = dataManager.getTrackProperties(); String[] trackNames = dataManager.getTrackNames(); List<Track> tracks = new ArrayList(); for (int trackNumber = 0; trackNumber < trackNames.length; trackNumber++) { String name = trackNames.length == 1 ? fName : trackNames[trackNumber]; Track track = null; try { track = new HDFDataTrack(dataManager, locator, name, trackNumber, genome); } catch (FileNotFoundException fe) { throw new RuntimeException(fe); } if (trackProperties != null) { track.setProperties(trackProperties); } tracks.add(track); } trackSet = new TrackSet(tracks); if (trackSet.isEmpty()) { throw new RuntimeException("No data found in file"); } newTracks.addAll(trackSet.getTracks()); } private void loadDASResource(ResourceLocator locator, List<Track> currentTracks) { //TODO Connect and get all the attributes of the DAS server, and run the appropriate load statements //TODO Currently we are only going to be doing features // TODO -- move the source creation to a factory DASFeatureSource featureSource = null; try { featureSource = new DASFeatureSource(locator); } catch (MalformedURLException e) { log.error("Malformed URL", e); throw new DataLoadException("Error: Malformed URL ", locator.getPath()); } FeatureTrack track = new FeatureTrack(locator, featureSource); // Try to create a sensible name from the path String name = locator.getPath(); if (locator.getPath().contains("genome.ucsc.edu")) { name = featureSource.getType(); } else { name = featureSource.getPath().replace("/das/", "").replace("/features", ""); } track.setName(name); // A hack until we can notate this some other way if (locator.getPath().contains("cosmic")) { track.setRendererClass(CosmicFeatureRenderer.class); track.setMinimumHeight(2); track.setHeight(20); track.setPreferredHeight(20); track.setDisplayMode(Track.DisplayMode.EXPANDED); } else { track.setRendererClass(IGVFeatureRenderer.class); track.setMinimumHeight(35); track.setHeight(45); track.setPreferredHeight(45); } currentTracks.add(track); } private void loadTrioData(ResourceLocator locator) throws IOException { PedigreeUtils.parseTrioFile(locator.getPath()); } public static boolean isIndexed(String path) { // genome space hack -- genome space files are never indexed (at least not yet) if (path.contains("genomespace.org")) { return false; } String indexExtension = path.endsWith("gz") ? ".tbi" : ".idx"; String indexPath = path + indexExtension; try { if (IGVHttpUtils.isURL(path)) { return IGVHttpUtils.resourceAvailable(new URL(indexPath)); } else { File f = new File(path + indexExtension); return f.exists(); } } catch (IOException e) { return false; } } }
src/org/broad/igv/track/TrackLoader.java
/* * Copyright (c) 2007-2011 by The Broad Institute, Inc. and the Massachusetts Institute of * Technology. All Rights Reserved. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. * * THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR * WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER * OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE * TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES * OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES, * ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER * THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT * SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING. */ package org.broad.igv.track; import org.apache.log4j.Logger; import org.broad.igv.PreferenceManager; import org.broad.igv.das.DASFeatureSource; import org.broad.igv.data.*; import org.broad.igv.data.expression.GCTDataset; import org.broad.igv.data.expression.GCTDatasetParser; import org.broad.igv.data.rnai.RNAIDataSource; import org.broad.igv.data.rnai.RNAIGCTDatasetParser; import org.broad.igv.data.rnai.RNAIGeneScoreParser; import org.broad.igv.data.rnai.RNAIHairpinParser; import org.broad.igv.data.seg.FreqData; import org.broad.igv.data.seg.SegmentedAsciiDataSet; import org.broad.igv.data.seg.SegmentedBinaryDataSet; import org.broad.igv.data.seg.SegmentedDataSource; import org.broad.igv.exceptions.DataLoadException; import org.broad.igv.feature.*; import org.broad.igv.feature.dranger.DRangerParser; import org.broad.igv.feature.genome.Genome; import org.broad.igv.feature.tribble.FeatureFileHeader; import org.broad.igv.goby.GobyAlignmentQueryReader; import org.broad.igv.goby.GobyCountArchiveDataSource; import org.broad.igv.gwas.GWASData; import org.broad.igv.gwas.GWASParser; import org.broad.igv.gwas.GWASTrack; import org.broad.igv.lists.GeneList; import org.broad.igv.lists.GeneListManager; import org.broad.igv.lists.VariantListManager; import org.broad.igv.maf.MAFTrack; import org.broad.igv.maf.conservation.OmegaDataSource; import org.broad.igv.maf.conservation.OmegaTrack; import org.broad.igv.peaks.PeakTrack; import org.broad.igv.renderer.*; import org.broad.igv.sam.*; import org.broad.igv.sam.reader.IndexNotFoundException; import org.broad.igv.synteny.BlastMapping; import org.broad.igv.synteny.BlastParser; import org.broad.igv.tdf.TDFDataSource; import org.broad.igv.tdf.TDFReader; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.ConfirmDialog; import org.broad.igv.ui.util.MessageUtils; import org.broad.igv.util.IGVHttpUtils; import org.broad.igv.util.ParsingUtils; import org.broad.igv.util.ResourceLocator; import org.broad.igv.vcf.PedigreeUtils; import org.broad.igv.vcf.VCFTrack; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * User: jrobinso * Date: Feb 14, 2010 */ public class TrackLoader { private static Logger log = Logger.getLogger(TrackLoader.class); private IGV igv; /** * Switches on various attributes of locator (mainly locator path extension and whether the locator is indexed) * to call the appropriate loading method. * * @param locator * @return */ public List<Track> load(ResourceLocator locator, IGV igv) { this.igv = igv; Genome genome = igv.getGenomeManager().getCurrentGenome(); final String path = locator.getPath(); try { String typeString = locator.getType(); if (typeString == null) { // Genome space hack if ((path.contains("?dataFormat") || path.contains("%3Fdataformat")) && (path.contains("dataformat/gct") || path.contains("dataformat%2Fgct"))) { typeString = ".gct"; } else { typeString = path.toLowerCase(); if (!typeString.endsWith("_sorted.txt") && (typeString.endsWith(".txt") || typeString.endsWith( ".xls") || typeString.endsWith(".gz"))) { typeString = typeString.substring(0, typeString.lastIndexOf(".")); } } } typeString = typeString.toLowerCase(); if (typeString.endsWith(".tbi")) { MessageUtils.showMessage("<html><b>Error:</b>File type '.tbi' is not recognized. If this is a 'tabix' index <br>" + " load the associated gzipped file, which should have an extension of '.gz'"); } //TODO Why is this not inside of isIndexed? //dhmay seconding this question -- this appears to be taken care of already in isIndexed() // Check for index boolean hasIndex = false; if (locator.isLocal()) { File indexFile = new File(path + ".sai"); hasIndex = indexFile.exists(); } //This list will hold all new tracks created for this locator List<Track> newTracks = new ArrayList<Track>(); if (typeString.endsWith(".gmt")) { loadGMT(locator); } else if (typeString.equals("das")) { loadDASResource(locator, newTracks); } else if (isIndexed(path)) { loadIndexed(locator, newTracks, genome); } else if (typeString.endsWith(".vcf") || typeString.endsWith(".vcf4")) { // TODO This is a hack, vcf files must be indexed. Fix in next release. throw new IndexNotFoundException(path); } else if (typeString.endsWith(".trio")) { loadTrioData(locator); } else if (typeString.endsWith("varlist")) { VariantListManager.loadVariants(locator); } else if (typeString.endsWith("samplepathmap")) { VariantListManager.loadSamplePathMap(locator); } else if (typeString.endsWith("h5") || typeString.endsWith("hbin")) { loadH5File(locator, newTracks, genome); } else if (typeString.endsWith(".rnai.gct")) { loadRnaiGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".gct") || typeString.endsWith("res") || typeString.endsWith("tab")) { loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".cn") || typeString.endsWith(".xcn") || typeString.endsWith(".snp") || typeString.endsWith(".igv") || typeString.endsWith(".loh")) { loadIGVFile(locator, newTracks, genome); } else if (typeString.endsWith(".mut")) { loadMutFile(locator, newTracks, genome); } else if (typeString.endsWith(".cbs") || typeString.endsWith(".seg") || typeString.endsWith("glad") || typeString.endsWith("birdseye_canary_calls")) { loadSegFile(locator, newTracks, genome); } else if (typeString.endsWith(".seg.zip")) { loadBinarySegFile(locator, newTracks, genome); } else if (typeString.endsWith(".gistic")) { loadGisticFile(locator, newTracks); } else if (typeString.endsWith(".gs")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.GENE_SCORE, genome); } else if (typeString.endsWith(".riger")) { loadRNAiGeneScoreFile(locator, newTracks, RNAIGeneScoreParser.Type.POOLED, genome); } else if (typeString.endsWith(".hp")) { loadRNAiHPScoreFile(locator); } else if (typeString.endsWith("gene")) { loadGeneFile(locator, newTracks, genome); } else if (typeString.contains(".tabblastn") || typeString.endsWith(".orthologs")) { loadSyntentyMapping(locator, newTracks); } else if (typeString.endsWith(".sam") || typeString.endsWith(".bam") || typeString.endsWith(".sam.list") || typeString.endsWith(".bam.list") || typeString.endsWith("_sorted.txt") || typeString.endsWith(".aligned") || typeString.endsWith(".sai") || typeString.endsWith(".bai")) { loadAlignmentsTrack(locator, newTracks, genome); } else if (typeString.endsWith(".bedz") || (typeString.endsWith(".bed") && hasIndex)) { loadIndexdBedFile(locator, newTracks, genome); } else if (typeString.endsWith(".omega")) { loadOmegaTrack(locator, newTracks, genome); } else if (typeString.endsWith(".wig") || (typeString.endsWith(".bedgraph")) || typeString.endsWith("cpg.txt") || typeString.endsWith(".expr")) { loadWigFile(locator, newTracks, genome); } else if (typeString.endsWith(".list")) { loadListFile(locator, newTracks, genome); } else if (typeString.contains(".dranger")) { loadDRangerFile(locator, newTracks, genome); } else if (typeString.endsWith(".ewig.tdf") || (typeString.endsWith(".ewig.ibf"))) { loadEwigIBFFile(locator, newTracks, genome); } else if (typeString.endsWith(".ibf") || typeString.endsWith(".tdf")) { loadTDFFile(locator, newTracks, genome); } else if (typeString.endsWith(".counts")) { loadGobyCountsArchive(locator, newTracks, genome); } else if (typeString.endsWith(".psl") || typeString.endsWith(".psl.gz") || typeString.endsWith(".pslx") || typeString.endsWith(".pslx.gz")) { loadPslFile(locator, newTracks, genome); //AbstractFeatureParser.getInstanceFor() is called twice. Wasteful } else if (AbstractFeatureParser.getInstanceFor(locator, genome) != null) { loadFeatureFile(locator, newTracks, genome); } else if (MutationParser.isMutationAnnotationFile(locator)) { this.loadMutFile(locator, newTracks, genome); } else if (WiggleParser.isWiggle(locator)) { loadWigFile(locator, newTracks, genome); } else if (path.toLowerCase().contains(".maf")) { loadMAFTrack(locator, newTracks); } else if (path.toLowerCase().contains(".peak.cfg")) { loadPeakTrack(locator, newTracks, genome); } else if ("mage-tab".equals(locator.getType()) || GCTDatasetParser.parsableMAGE_TAB(locator)) { locator.setDescription("MAGE_TAB"); loadGctFile(locator, newTracks, genome); } else if (typeString.endsWith(".logistic") || typeString.endsWith(".linear") || typeString.endsWith(".assoc") || typeString.endsWith(".qassoc") || typeString.endsWith(".gwas")) { loadGWASFile(locator, newTracks); } else if (GCTDatasetParser.isGCT(path)) { loadGctFile(locator, newTracks, genome); } else if (GobyAlignmentQueryReader.supportsFileType(path)) { loadAlignmentsTrack(locator, newTracks, genome); } else if (AttributeManager.isSampleInfoFile(locator)) { // This might be a sample information file. AttributeManager.getInstance().loadSampleInfo(locator); } else { MessageUtils.showMessage("<html>Unknown file type: " + path + "<br>Check file extenstion"); } // Track line TrackProperties tp = null; String trackLine = locator.getTrackLine(); if (trackLine != null) { tp = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, tp); } for (Track track : newTracks) { if (locator.getUrl() != null) { track.setUrl(locator.getUrl()); } if (tp != null) { track.setProperties(tp); } if (locator.getColor() != null) { track.setColor(locator.getColor()); } if (locator.getSampleId() != null) { track.setSampleId(locator.getSampleId()); } } return newTracks; } catch (DataLoadException dle) { throw dle; } catch (Exception e) { log.error(e); throw new DataLoadException(e.getMessage(), path); } } private void loadGMT(ResourceLocator locator) throws IOException { List<GeneList> lists = GeneListManager.getInstance().importGMTFile(locator.getPath()); if (lists.size() == 1) { GeneList gl = lists.get(0); IGV.getInstance().setGeneList(gl.getName(), true); } else { MessageUtils.showMessage("Loaded " + lists.size() + " gene lists."); } } private void loadIndexed(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { TribbleFeatureSource src = new TribbleFeatureSource(locator.getPath(), genome); String typeString = locator.getPath(); //Track t; if (typeString.endsWith("vcf") || typeString.endsWith("vcf.gz")) { VCFTrack t = new VCFTrack(locator, src); // VCF tracks handle their own margin t.setMargin(0); newTracks.add(t); } else { // Create feature source and track FeatureTrack t = new FeatureTrack(locator, src); t.setName(locator.getTrackName()); //t.setRendererClass(BasicTribbleRenderer.class); // Set track properties from header Object header = src.getHeader(); if (header != null && header instanceof FeatureFileHeader) { FeatureFileHeader ffh = (FeatureFileHeader) header; if (ffh.getTrackType() != null) { t.setTrackType(ffh.getTrackType()); } if (ffh.getTrackProperties() != null) { t.setProperties(ffh.getTrackProperties()); } if (ffh.getTrackType() == TrackType.REPMASK) { t.setHeight(15); t.setPreferredHeight(15); } } newTracks.add(t); } } /** * Load the input file as a BED or Attribute (Sample Info) file. First assume * it is a BED file, if no features are found load as an attribute file. * * @param locator * @param newTracks */ private void loadGeneFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome); if (featureParser != null) { List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); } } private void loadSyntentyMapping(ResourceLocator locator, List<Track> newTracks) { List<BlastMapping> mappings = (new BlastParser()).parse(locator.getPath()); List<org.broad.tribble.Feature> features = new ArrayList<org.broad.tribble.Feature>(mappings.size()); features.addAll(mappings); Genome genome = igv.getGenomeManager().getCurrentGenome(); FeatureTrack track = new FeatureTrack(locator, new FeatureCollectionSource(features, genome)); track.setName(locator.getTrackName()); // track.setRendererClass(AlignmentBlockRenderer.class); newTracks.add(track); } private void loadDRangerFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { DRangerParser parser = new DRangerParser(); newTracks.addAll(parser.loadTracks(locator, genome)); } /** * Load the input file as a feature, mutation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadPslFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { PSLParser featureParser = new PSLParser(genome); List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); for (FeatureTrack t : tracks) { t.setMinimumHeight(10); t.setHeight(30); t.setPreferredHeight(30); t.setDisplayMode(Track.DisplayMode.EXPANDED); } } /** * Load the input file as a feature, muation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadFeatureFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { if (locator.isLocal() && (locator.getPath().endsWith(".bed") || locator.getPath().endsWith(".bed.txt") || locator.getPath().endsWith(".bed.gz"))) { //checkSize takes care of warning the user if (!checkSize(locator.getPath())) { return; } } FeatureParser featureParser = AbstractFeatureParser.getInstanceFor(locator, genome); if (featureParser != null) { List<FeatureTrack> tracks = featureParser.loadTracks(locator, genome); newTracks.addAll(tracks); } else if (MutationParser.isMutationAnnotationFile(locator)) { this.loadMutFile(locator, newTracks, genome); } else if (WiggleParser.isWiggle(locator)) { loadWigFile(locator, newTracks, genome); } else if (locator.getPath().toLowerCase().contains(".maf")) { loadMAFTrack(locator, newTracks); } } /** * Load the input file as a feature, muation, or maf (multiple alignment) file. * * @param locator * @param newTracks */ private void loadIndexdBedFile(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { File featureFile = new File(locator.getPath()); File indexFile = new File(locator.getPath() + ".sai"); FeatureSource src = new IndexedBEDFeatureSource(featureFile, indexFile, genome); Track t = new FeatureTrack(locator, src); newTracks.add(t); } /** * Load GWAS PLINK result file * * @param locator * @param newTracks * @throws IOException */ private void loadGWASFile(ResourceLocator locator, List<Track> newTracks) throws IOException { GWASParser gwasParser = new GWASParser(locator); GWASData gwasData = gwasParser.parse(); GWASTrack gwasTrack = new GWASTrack(locator, locator.getPath(), locator.getFileName(), gwasData, gwasParser); newTracks.add(gwasTrack); } private void loadRnaiGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { RNAIGCTDatasetParser parser = new RNAIGCTDatasetParser(locator, genome); Collection<RNAIDataSource> dataSources = parser.parse(); if (dataSources != null) { String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String trackId = path + "_" + ds.getName(); DataSourceTrack track = new DataSourceTrack(locator, trackId, ds.getName(), ds, genome); // Set attributes. track.setAttributeValue("SCREEN", ds.getScreen()); track.setHeight(80); track.setPreferredHeight(80); newTracks.add(track); } } } private void loadGctFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } GCTDatasetParser parser = null; GCTDataset ds = null; String fName = locator.getTrackName(); // TODO -- handle remote resource try { parser = new GCTDatasetParser(locator, null, igv.getGenomeManager().getCurrentGenome()); } catch (IOException e) { log.error("Error creating GCT parser.", e); throw new DataLoadException("Error creating GCT parser: " + e, locator.getPath()); } ds = parser.createDataset(); ds.setName(fName); ds.setNormalized(true); ds.setLogValues(true); /* * File outputFile = new File(IGV.DEFAULT_USER_DIRECTORY, file.getName() + ".h5"); * OverlappingProcessor proc = new OverlappingProcessor(ds); * proc.setZoomMax(0); * proc.process(outputFile.getAbsolutePath()); * loadH5File(outputFile, messages, attributeList, group); */ // Counter for generating ID TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); for (String trackName : ds.getTrackNames()) { Genome currentGenome = igv.getGenomeManager().getCurrentGenome(); DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, currentGenome); String trackId = path + "_" + trackName; Track track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setProperties(trackProperties); newTracks.add(track); } } private void loadIGVFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } String dsName = locator.getTrackName(); IGVDataset ds = new IGVDataset(locator, genome, igv); ds.setName(dsName); TrackProperties trackProperties = ds.getTrackProperties(); String path = locator.getPath(); TrackType type = ds.getType(); for (String trackName : ds.getTrackNames()) { DatasetDataSource dataSource = new DatasetDataSource(trackName, ds, genome); String trackId = path + "_" + trackName; DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); // track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); track.setProperties(trackProperties); if (type == TrackType.ALLELE_FREQUENCY) { track.setRendererClass(ScatterplotRenderer.class); track.setHeight(40); track.setPreferredHeight(40); } newTracks.add(track); } } private boolean checkSize(String file) { if (!PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_SIZE_WARNING)) { return true; } File f = new File(file); String tmp = file; if (f.exists()) { long size = f.length(); if (file.endsWith(".gz")) { size *= 3; tmp = file.substring(0, file.length() - 3); } if (size > 50000000) { String message = ""; if (tmp.endsWith(".bed") || tmp.endsWith(".bed.txt")) { message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " + "that large files be indexed using IGVTools or Tabix. Loading un-indexed " + "ascii fies of this size can lead to poor performance or unresponsiveness (freezing). " + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a command line program. " + "See the user guide for more details.<br><br>Click <b>Continue</b> to continue loading, or <b>Cancel</b>" + " to skip this file."; } else { message = "The file " + file + " is large (" + (size / 1000000) + " mb). It is recommended " + "that large files be converted to the binary <i>.tdf</i> format using the IGVTools " + "<b>tile</b> command. Loading unconverted ascii fies of this size can lead to poor " + "performance or unresponsiveness (freezing). " + "<br><br>IGVTools can be launched from the <b>Tools</b> menu or separately as a " + "command line program. See the user guide for more details.<br><br>Click <b>Continue</b> " + "to continue loading, or <b>Cancel</b> to skip this file."; } return ConfirmDialog.optionallyShowConfirmDialog(message, PreferenceManager.SHOW_SIZE_WARNING, true); } } return true; } private void loadDOTFile(ResourceLocator locator, List<Track> newTracks) { //GraphTrack gt = new GraphTrack(locator); //gt.setHeight(80); //newTracks.add(gt); } private void loadWigFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (locator.isLocal()) { if (!checkSize(locator.getPath())) { return; } } WiggleDataset ds = (new WiggleParser(locator, genome)).parse(); TrackProperties props = ds.getTrackProperties(); // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = props == null ? null : props.getName(); String label = locator.getName(); if (name == null) { name = locator.getFileName(); } else if (label != null) { props.setName(label); // erase name rom track properties } String path = locator.getPath(); boolean multiTrack = ds.getTrackNames().length > 1; for (String heading : ds.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; Genome currentGenome = IGV.getInstance().getGenomeManager().getCurrentGenome(); DatasetDataSource dataSource = new DatasetDataSource(trackId, ds, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); String displayName = (label == null || multiTrack) ? heading : label; track.setName(displayName); track.setProperties(props); track.setTrackType(ds.getType()); if (ds.getType() == TrackType.EXPR) { track.setWindowFunction(WindowFunction.none); } newTracks.add(track); } } private void loadTDFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (log.isDebugEnabled()) { log.debug("Loading TDFFile: " + locator.toString()); } TDFReader reader = TDFReader.getReader(locator.getPath()); TrackType type = reader.getTrackType(); if (log.isDebugEnabled()) { log.debug("Parsing track line "); } TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } // In case of conflict between the resource locator display name and the track properties name, // use the resource locator String name = locator.getName(); if (name != null && props != null) { props.setName(name); } if (name == null) { name = props == null ? locator.getTrackName() : props.getName(); } int trackNumber = 0; String path = locator.getPath(); boolean multiTrack = reader.getTrackNames().length > 1; for (String heading : reader.getTrackNames()) { String trackId = multiTrack ? path + "_" + heading : path; String trackName = multiTrack ? heading : name; final DataSource dataSource = locator.getType().endsWith("counts") ? new GobyCountArchiveDataSource(locator) : new TDFDataSource(reader, trackNumber, heading, genome); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); String displayName = (name == null || multiTrack) ? heading : name; track.setName(displayName); track.setTrackType(type); if (props != null) { track.setProperties(props); } newTracks.add(track); trackNumber++; } } private void loadGobyCountsArchive(ResourceLocator locator, List<Track> newTracks, Genome genome) { if (log.isDebugEnabled()) { log.debug("Loading Goby counts archive: " + locator.toString()); } String trackId = locator.getSampleId() + " coverage"; String trackName = locator.getFileName(); final DataSource dataSource = new GobyCountArchiveDataSource(locator); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); newTracks.add(track); } private void loadEwigIBFFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { TDFReader reader = TDFReader.getReader(locator.getPath()); TrackProperties props = null; String trackLine = reader.getTrackLine(); if (trackLine != null && trackLine.length() > 0) { props = new TrackProperties(); ParsingUtils.parseTrackLine(trackLine, props); } EWigTrack track = new EWigTrack(locator, genome); if (props != null) { track.setProperties(props); } track.setName(locator.getTrackName()); newTracks.add(track); } private void loadListFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { try { FeatureSource source = new FeatureDirSource(locator, genome); FeatureTrack track = new FeatureTrack(locator, source); track.setName(locator.getTrackName()); track.setVisibilityWindow(0); newTracks.add(track); } catch (IOException ex) { throw new RuntimeException(ex); } } private void loadGisticFile(ResourceLocator locator, List<Track> newTracks) { GisticTrack track = GisticFileParser.loadData(locator); track.setName(locator.getTrackName()); newTracks.add(track); } /** * Load a rnai gene score file and create a datasource and track. * <p/> * // TODO -- change parser to use resource locator rather than path. * * @param locator * @param newTracks */ private void loadRNAiGeneScoreFile(ResourceLocator locator, List<Track> newTracks, RNAIGeneScoreParser.Type type, Genome genome) { RNAIGeneScoreParser parser = new RNAIGeneScoreParser(locator.getPath(), type, genome); Collection<RNAIDataSource> dataSources = parser.parse(); String path = locator.getPath(); for (RNAIDataSource ds : dataSources) { String name = ds.getName(); String trackId = path + "_" + name; DataSourceTrack track = new DataSourceTrack(locator, trackId, name, ds, genome); // Set attributes. This "hack" is neccessary to register these attributes with the // attribute manager to get displayed. track.setAttributeValue("SCREEN", ds.getScreen()); if ((ds.getCondition() != null) && (ds.getCondition().length() > 0)) { track.setAttributeValue("CONDITION", ds.getCondition()); } track.setHeight(80); track.setPreferredHeight(80); //track.setDataRange(new DataRange(-3, 0, 3)); newTracks.add(track); } } /** * Load a RNAi haripin score file. The results of this action are hairpin scores * added to the RNAIDataManager. Currently no tracks are created for hairpin * scores, although this could change. * * @param locator */ private void loadRNAiHPScoreFile(ResourceLocator locator) { (new RNAIHairpinParser(locator.getPath())).parse(); } private void loadMAFTrack(ResourceLocator locator, List<Track> newTracks) { MAFTrack t = new MAFTrack(locator); t.setName("Multiple Alignments"); newTracks.add(t); } private void loadPeakTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { PeakTrack t = new PeakTrack(locator, genome); newTracks.add(t); } private void loadOmegaTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) { OmegaDataSource ds = new OmegaDataSource(genome); OmegaTrack track = new OmegaTrack(locator, ds, genome); track.setName("Conservation (Omega)"); track.setHeight(40); track.setPreferredHeight(40); newTracks.add(track); } /** * Load a rnai gene score file and create a datasource and track. * * @param locator * @param newTracks */ private void loadAlignmentsTrack(ResourceLocator locator, List<Track> newTracks, Genome genome) throws IOException { try { String dsName = locator.getTrackName(); String fn = locator.getPath().toLowerCase(); boolean isBed = fn.endsWith(".bedz") || fn.endsWith(".bed") || fn.endsWith(".bed.gz"); // If the user tried to load the index, look for the file (this is a common mistake) if (locator.getPath().endsWith(".sai") || locator.getPath().endsWith(".bai")) { MessageUtils.showMessage("<html><b>ERROR:</b> Loading SAM/BAM index files are not supported: " + locator.getPath() + "<br>Load the SAM or BAM file directly. "); return; } AlignmentDataManager dataManager = new AlignmentDataManager(locator); if (locator.getPath().toLowerCase().endsWith(".bam")) { if (!dataManager.hasIndex()) { MessageUtils.showMessage("<html>Could not load index file for: " + locator.getPath() + "<br> An index file is required for SAM & BAM files."); return; } } AlignmentTrack alignmentTrack = new AlignmentTrack(locator, dataManager, genome); // parser.loadTrack(locator, dsName); alignmentTrack.setName(dsName); if (isBed) { alignmentTrack.setRenderer(new BedRenderer()); alignmentTrack.setPreferredHeight(40); alignmentTrack.setHeight(40); } // Create coverage track CoverageTrack covTrack = new CoverageTrack(locator.getPath() + "_coverage", alignmentTrack.getName() + " Coverage", genome); covTrack.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_COV_TRACK)); newTracks.add(covTrack); alignmentTrack.setCoverageTrack(covTrack); if (!isBed) { covTrack.setDataManager(dataManager); dataManager.setCoverageTrack(covTrack); } // Search for precalculated coverage data String covPath = locator.getCoverage(); if (covPath == null) { String path = locator.getPath(); covPath = path + ".tdf"; } if (covPath != null) { try { if ((new File(covPath)).exists() || (IGVHttpUtils.isURL(covPath) && IGVHttpUtils.resourceAvailable(new URL(covPath)))) { TDFReader reader = TDFReader.getReader(covPath); TDFDataSource ds = new TDFDataSource(reader, 0, alignmentTrack.getName() + " coverage", genome); covTrack.setDataSource(ds); } } catch (MalformedURLException e) { // This is expected if // log.info("Could not loading coverage data: MalformedURL: " + covPath); } } boolean showSpliceJunctionTrack = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SAM_SHOW_JUNCTION_TRACK); if (showSpliceJunctionTrack) { SpliceJunctionFinderTrack spliceJunctionTrack = new SpliceJunctionFinderTrack(locator.getPath() + "_junctions", alignmentTrack.getName() + " Junctions", dataManager); // spliceJunctionTrack.setDataManager(dataManager); spliceJunctionTrack.setHeight(60); spliceJunctionTrack.setPreferredHeight(60); spliceJunctionTrack.setVisible(showSpliceJunctionTrack); newTracks.add(spliceJunctionTrack); alignmentTrack.setSpliceJunctionTrack(spliceJunctionTrack); } newTracks.add(alignmentTrack); } catch (IndexNotFoundException e) { MessageUtils.showMessage("<html>Could not find the index file for <br><br>&nbsp;&nbsp;" + e.getSamFile() + "<br><br>Note: The index file can be created using igvtools and must be in the same directory as the .sam file."); } } /** * Load a ".mut" file (muation file) and create tracks. * * @param locator * @param newTracks */ private void loadMutFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { MutationParser parser = new MutationParser(); List<FeatureTrack> mutationTracks = parser.loadMutationTracks(locator, genome); for (FeatureTrack track : mutationTracks) { track.setTrackType(TrackType.MUTATION); track.setRendererClass(MutationRenderer.class); newTracks.add(track); } } private void loadSegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { // TODO - -handle remote resource SegmentedAsciiDataSet ds = new SegmentedAsciiDataSet(locator, genome); String path = locator.getPath(); TrackProperties props = ds.getTrackProperties(); // The "freq" track. TODO - make this optional if (ds.getSampleNames().size() > 1) { FreqData fd = new FreqData(ds, genome); String freqTrackId = path; String freqTrackName = (new File(path)).getName(); CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd); newTracks.add(freqTrack); } for (String trackName : ds.getDataHeadings()) { String trackId = path + "_" + trackName; SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); if (props != null) { track.setProperties(props); } newTracks.add(track); } } private void loadBinarySegFile(ResourceLocator locator, List<Track> newTracks, Genome genome) { SegmentedBinaryDataSet ds = new SegmentedBinaryDataSet(locator); String path = locator.getPath(); // The "freq" track. Make this optional? FreqData fd = new FreqData(ds, genome); String freqTrackId = path; String freqTrackName = (new File(path)).getName(); CNFreqTrack freqTrack = new CNFreqTrack(locator, freqTrackId, freqTrackName, fd); newTracks.add(freqTrack); for (String trackName : ds.getSampleNames()) { String trackId = path + "_" + trackName; SegmentedDataSource dataSource = new SegmentedDataSource(trackName, ds); DataSourceTrack track = new DataSourceTrack(locator, trackId, trackName, dataSource, genome); track.setRendererClass(HeatmapRenderer.class); track.setTrackType(ds.getType()); newTracks.add(track); } } /** * Load the data from an HDF5 file and add resulting tracks to the supplied TrackGroup. * Error messages are appended to the MessageCollection * * @param locator */ private void loadH5File(ResourceLocator locator, List<Track> newTracks, Genome genome) { TrackSet trackSet = null; // TODO -- temporary until "name" property is added to locator // TODO -- "label" has been added, how does that affect this? String fName = locator.getTrackName(); HDFDataManager dataManager = HDFDataManagerFactory.getDataManager(locator); TrackProperties trackProperties = dataManager.getTrackProperties(); String[] trackNames = dataManager.getTrackNames(); List<Track> tracks = new ArrayList(); for (int trackNumber = 0; trackNumber < trackNames.length; trackNumber++) { String name = trackNames.length == 1 ? fName : trackNames[trackNumber]; Track track = null; try { track = new HDFDataTrack(dataManager, locator, name, trackNumber, genome); } catch (FileNotFoundException fe) { throw new RuntimeException(fe); } if (trackProperties != null) { track.setProperties(trackProperties); } tracks.add(track); } trackSet = new TrackSet(tracks); if (trackSet.isEmpty()) { throw new RuntimeException("No data found in file"); } newTracks.addAll(trackSet.getTracks()); } private void loadDASResource(ResourceLocator locator, List<Track> currentTracks) { //TODO Connect and get all the attributes of the DAS server, and run the appropriate load statements //TODO Currently we are only going to be doing features // TODO -- move the source creation to a factory DASFeatureSource featureSource = null; try { featureSource = new DASFeatureSource(locator); } catch (MalformedURLException e) { log.error("Malformed URL", e); throw new DataLoadException("Error: Malformed URL ", locator.getPath()); } FeatureTrack track = new FeatureTrack(locator, featureSource); // Try to create a sensible name from the path String name = locator.getPath(); if (locator.getPath().contains("genome.ucsc.edu")) { name = featureSource.getType(); } else { name = featureSource.getPath().replace("/das/", "").replace("/features", ""); } track.setName(name); // A hack until we can notate this some other way if (locator.getPath().contains("cosmic")) { track.setRendererClass(CosmicFeatureRenderer.class); track.setMinimumHeight(2); track.setHeight(20); track.setPreferredHeight(20); track.setDisplayMode(Track.DisplayMode.EXPANDED); } else { track.setRendererClass(IGVFeatureRenderer.class); track.setMinimumHeight(35); track.setHeight(45); track.setPreferredHeight(45); } currentTracks.add(track); } private void loadTrioData(ResourceLocator locator) throws IOException { PedigreeUtils.parseTrioFile(locator.getPath()); } public static boolean isIndexed(String path) { // genome space hack -- genome space files are never indexed (at least not yet) if (path.contains("genomespace.org")) { return false; } String indexExtension = path.endsWith("gz") ? ".tbi" : ".idx"; String indexPath = path + indexExtension; try { if (IGVHttpUtils.isURL(path)) { return IGVHttpUtils.resourceAvailable(new URL(indexPath)); } else { File f = new File(path + indexExtension); return f.exists(); } } catch (IOException e) { return false; } } }
Fix for NPE when loading TDF files git-svn-id: b5cf87c434d9ee7c8f18865e4378c9faabe04646@735 17392f64-ead8-4cea-ae29-09b3ab513800
src/org/broad/igv/track/TrackLoader.java
Fix for NPE when loading TDF files
Java
epl-1.0
4cf2120c2fa99524772bb04730326a9c8fd92466
0
gnodet/wikitext
/******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies 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: * Eugene Kuleshov - initial API and implementation * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.workingsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.internal.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.internal.tasks.core.TaskCategory; import org.eclipse.mylyn.internal.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.monitor.ui.MonitorUi; import org.eclipse.mylyn.tasks.core.IRepositoryElement; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetUpdater; import org.eclipse.ui.PlatformUI; /** * @author Eugene Kuleshov * @author Mik Kersten * @author Steffen Pingel */ public class TaskWorkingSetUpdater implements IWorkingSetUpdater, ITaskListChangeListener, IResourceChangeListener { public static String ID_TASK_WORKING_SET = "org.eclipse.mylyn.tasks.ui.workingSet"; //$NON-NLS-1$ private final List<IWorkingSet> workingSets = new CopyOnWriteArrayList<IWorkingSet>(); private static class TaskWorkingSetDelta { private final IWorkingSet workingSet; private final List<Object> elements; private boolean changed; public TaskWorkingSetDelta(IWorkingSet workingSet) { this.workingSet = workingSet; this.elements = new ArrayList<Object>(Arrays.asList(workingSet.getElements())); } public int indexOf(Object element) { return elements.indexOf(element); } public void set(int index, Object element) { elements.set(index, element); changed = true; } public void remove(int index) { if (elements.remove(index) != null) { changed = true; } } public void process() { if (changed) { workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } } } public TaskWorkingSetUpdater() { TasksUiInternal.getTaskList().addChangeListener(this); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } public void dispose() { TasksUiInternal.getTaskList().removeChangeListener(this); } public void add(IWorkingSet workingSet) { checkElementExistence(workingSet); synchronized (workingSets) { workingSets.add(workingSet); } } private void checkElementExistence(IWorkingSet workingSet) { ArrayList<IAdaptable> list = new ArrayList<IAdaptable>(); for (IAdaptable adaptable : workingSet.getElements()) { if (adaptable instanceof AbstractTaskContainer) { String handle = ((AbstractTaskContainer) adaptable).getHandleIdentifier(); for (IRepositoryElement element : TasksUiPlugin.getTaskList().getRootElements()) { if (element != null && element.getHandleIdentifier().equals(handle)) { list.add(adaptable); } } } else if (adaptable instanceof IProject) { IProject project = ResourcesPlugin.getWorkspace() .getRoot() .getProject(((IProject) adaptable).getName()); if (project != null && project.exists()) { list.add(project); } } } workingSet.setElements(list.toArray(new IAdaptable[list.size()])); } public boolean contains(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.contains(workingSet); } } public boolean remove(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.remove(workingSet); } } public void containersChanged(Set<TaskContainerDelta> delta) { for (TaskContainerDelta taskContainerDelta : delta) { if (taskContainerDelta.getElement() instanceof TaskCategory || taskContainerDelta.getElement() instanceof IRepositoryQuery) { synchronized (workingSets) { switch (taskContainerDelta.getKind()) { case REMOVED: // Remove from all for (IWorkingSet workingSet : workingSets) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.remove(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; case ADDED: // Add to the active working set for (IWorkingSet workingSet : TaskWorkingSetUpdater.getEnabledSets()) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.add(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; } } } } } // TODO: consider putting back, but evaluate policy and note bug 197257 // public void taskActivated(AbstractTask task) { // Set<AbstractTaskContainer> taskContainers = new HashSet<AbstractTaskContainer>( // TasksUiPlugin.getTaskList().getQueriesForHandle(task.getHandleIdentifier())); // taskContainers.addAll(task.getParentContainers()); // // Set<AbstractTaskContainer> allActiveWorkingSetContainers = new HashSet<AbstractTaskContainer>(); // for (IWorkingSet workingSet : PlatformUI.getWorkbench() // .getActiveWorkbenchWindow() // .getActivePage() // .getWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // allActiveWorkingSetContainers.add((AbstractTaskContainer) adaptable); // } // } // } // boolean isContained = false; // for (AbstractTaskContainer taskContainer : allActiveWorkingSetContainers) { // if (taskContainers.contains(taskContainer)) { // isContained = true; // break; // } // } // // ; // if (!isContained) { // IWorkingSet matchingWorkingSet = null; // for (IWorkingSet workingSet : PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // if (((AbstractTaskContainer)adaptable).contains(task.getHandleIdentifier())) { // matchingWorkingSet = workingSet; // } // } // } // } // // if (matchingWorkingSet != null) { // new ToggleWorkingSetAction(matchingWorkingSet).run(); // } else { // new ToggleAllWorkingSetsAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow()).run(); // } // } // } public static IWorkingSet[] getEnabledSets() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { return page.getWorkingSets(); } } return new IWorkingSet[0]; } /** * TODO: move */ public static boolean areNoTaskWorkingSetsEnabled() { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets(); for (IWorkingSet workingSet : workingSets) { if (workingSet != null && workingSet.getId().equalsIgnoreCase(ID_TASK_WORKING_SET)) { if (isWorkingSetEnabled(workingSet)) { return false; } } } return true; } public static boolean isWorkingSetEnabled(IWorkingSet set) { IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (IWorkingSet enabledSet : enabledSets) { if (enabledSet.equals(set)) { return true; } } return false; } public static boolean isOnlyTaskWorkingSetEnabled(IWorkingSet set) { if (!TaskWorkingSetUpdater.isWorkingSetEnabled(set)) { return false; } IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (int i = 0; i < enabledSets.length; i++) { if (!enabledSets[i].equals(set) && enabledSets[i].getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { return false; } } return true; } private void processResourceDelta(TaskWorkingSetDelta result, IResourceDelta delta) { IResource resource = delta.getResource(); int type = resource.getType(); int index = result.indexOf(resource); int kind = delta.getKind(); int flags = delta.getFlags(); if (kind == IResourceDelta.CHANGED && type == IResource.PROJECT && index != -1) { if ((flags & IResourceDelta.OPEN) != 0) { result.set(index, resource); } } if (index != -1 && kind == IResourceDelta.REMOVED) { if ((flags & IResourceDelta.MOVED_TO) != 0) { result.set(index, ResourcesPlugin.getWorkspace().getRoot().findMember(delta.getMovedToPath())); } else { result.remove(index); } } // Don't dive into closed or opened projects if (projectGotClosedOrOpened(resource, kind, flags)) { return; } IResourceDelta[] children = delta.getAffectedChildren(); for (IResourceDelta element : children) { processResourceDelta(result, element); } } private boolean projectGotClosedOrOpened(IResource resource, int kind, int flags) { return resource.getType() == IResource.PROJECT && kind == IResourceDelta.CHANGED && (flags & IResourceDelta.OPEN) != 0; } public void resourceChanged(IResourceChangeEvent event) { for (IWorkingSet workingSet : workingSets) { TaskWorkingSetDelta workingSetDelta = new TaskWorkingSetDelta(workingSet); if (event.getDelta() != null) { processResourceDelta(workingSetDelta, event.getDelta()); } workingSetDelta.process(); } } /** * Must be called from the UI thread */ public static void applyWorkingSetsToAllWindows(Collection<IWorkingSet> workingSets) { IWorkingSet[] workingSetArray = workingSets.toArray(new IWorkingSet[workingSets.size()]); for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) { for (IWorkbenchPage page : window.getPages()) { page.setWorkingSets(workingSetArray); } } } public static Set<IWorkingSet> getActiveWorkingSets(IWorkbenchWindow window) { if (window != null && window.getActivePage() != null) { Set<IWorkingSet> allSets = new HashSet<IWorkingSet>(Arrays.asList(window.getActivePage().getWorkingSets())); Set<IWorkingSet> tasksSets = new HashSet<IWorkingSet>(allSets); for (IWorkingSet workingSet : allSets) { if (workingSet.getId() == null || !workingSet.getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { tasksSets.remove(workingSet); } } return tasksSets; } else { return Collections.emptySet(); } } }
org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java
/******************************************************************************* * Copyright (c) 2004, 2008 Tasktop Technologies 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: * Eugene Kuleshov - initial API and implementation * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.workingsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.internal.tasks.core.ITaskListChangeListener; import org.eclipse.mylyn.internal.tasks.core.TaskCategory; import org.eclipse.mylyn.internal.tasks.core.TaskContainerDelta; import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal; import org.eclipse.mylyn.monitor.ui.MonitorUi; import org.eclipse.mylyn.tasks.core.IRepositoryElement; import org.eclipse.mylyn.tasks.core.IRepositoryQuery; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetUpdater; import org.eclipse.ui.PlatformUI; /** * @author Eugene Kuleshov * @author Mik Kersten * @author Steffen Pingel */ public class TaskWorkingSetUpdater implements IWorkingSetUpdater, ITaskListChangeListener, IResourceChangeListener { public static String ID_TASK_WORKING_SET = "org.eclipse.mylyn.tasks.ui.workingSet"; //$NON-NLS-1$ private final List<IWorkingSet> workingSets = new CopyOnWriteArrayList<IWorkingSet>(); private static class TaskWorkingSetDelta { private final IWorkingSet workingSet; private final List<Object> elements; private boolean changed; public TaskWorkingSetDelta(IWorkingSet workingSet) { this.workingSet = workingSet; this.elements = new ArrayList<Object>(Arrays.asList(workingSet.getElements())); } public int indexOf(Object element) { return elements.indexOf(element); } public void set(int index, Object element) { elements.set(index, element); changed = true; } public void remove(int index) { if (elements.remove(index) != null) { changed = true; } } public void process() { if (changed) { workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } } } public TaskWorkingSetUpdater() { TasksUiInternal.getTaskList().addChangeListener(this); ResourcesPlugin.getWorkspace().addResourceChangeListener(this); } public void dispose() { TasksUiInternal.getTaskList().removeChangeListener(this); } public void add(IWorkingSet workingSet) { checkElementExistence(workingSet); synchronized (workingSets) { workingSets.add(workingSet); } } private void checkElementExistence(IWorkingSet workingSet) { ArrayList<IAdaptable> list = new ArrayList<IAdaptable>(); for (IAdaptable adaptable : workingSet.getElements()) { if (adaptable instanceof AbstractTaskContainer) { String handle = ((AbstractTaskContainer) adaptable).getHandleIdentifier(); for (IRepositoryElement element : TasksUiPlugin.getTaskList().getRootElements()) { if (element != null && element.getHandleIdentifier().equals(handle)) { list.add(adaptable); } } } else if (adaptable instanceof IProject) { IProject project = ResourcesPlugin.getWorkspace() .getRoot() .getProject(((IProject) adaptable).getName()); if (project != null && project.exists()) { list.add(project); } } } workingSet.setElements(list.toArray(new IAdaptable[list.size()])); } public boolean contains(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.contains(workingSet); } } public boolean remove(IWorkingSet workingSet) { synchronized (workingSets) { return workingSets.remove(workingSet); } } public void containersChanged(Set<TaskContainerDelta> delta) { for (TaskContainerDelta taskContainerDelta : delta) { if (taskContainerDelta.getElement() instanceof TaskCategory || taskContainerDelta.getElement() instanceof IRepositoryQuery) { synchronized (workingSets) { switch (taskContainerDelta.getKind()) { case REMOVED: // Remove from all for (IWorkingSet workingSet : workingSets) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.remove(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; case ADDED: // Add to the active working set for (IWorkingSet workingSet : TaskWorkingSetUpdater.getEnabledSets()) { ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>( Arrays.asList(workingSet.getElements())); elements.add(taskContainerDelta.getElement()); workingSet.setElements(elements.toArray(new IAdaptable[elements.size()])); } break; } } } } } // TODO: consider putting back, but evaluate policy and note bug 197257 // public void taskActivated(AbstractTask task) { // Set<AbstractTaskContainer> taskContainers = new HashSet<AbstractTaskContainer>( // TasksUiPlugin.getTaskList().getQueriesForHandle(task.getHandleIdentifier())); // taskContainers.addAll(task.getParentContainers()); // // Set<AbstractTaskContainer> allActiveWorkingSetContainers = new HashSet<AbstractTaskContainer>(); // for (IWorkingSet workingSet : PlatformUI.getWorkbench() // .getActiveWorkbenchWindow() // .getActivePage() // .getWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // allActiveWorkingSetContainers.add((AbstractTaskContainer) adaptable); // } // } // } // boolean isContained = false; // for (AbstractTaskContainer taskContainer : allActiveWorkingSetContainers) { // if (taskContainers.contains(taskContainer)) { // isContained = true; // break; // } // } // // ; // if (!isContained) { // IWorkingSet matchingWorkingSet = null; // for (IWorkingSet workingSet : PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets()) { // ArrayList<IAdaptable> elements = new ArrayList<IAdaptable>(Arrays.asList(workingSet.getElements())); // for (IAdaptable adaptable : elements) { // if (adaptable instanceof AbstractTaskContainer) { // if (((AbstractTaskContainer)adaptable).contains(task.getHandleIdentifier())) { // matchingWorkingSet = workingSet; // } // } // } // } // // if (matchingWorkingSet != null) { // new ToggleWorkingSetAction(matchingWorkingSet).run(); // } else { // new ToggleAllWorkingSetsAction(PlatformUI.getWorkbench().getActiveWorkbenchWindow()).run(); // } // } // } public static IWorkingSet[] getEnabledSets() { IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (window != null) { IWorkbenchPage page = window.getActivePage(); if (page != null) { return page.getWorkingSets(); } } return new IWorkingSet[0]; } /** * TODO: move */ public static boolean areNoTaskWorkingSetsEnabled() { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSets(); for (IWorkingSet workingSet : workingSets) { if (workingSet != null && workingSet.getId().equalsIgnoreCase(ID_TASK_WORKING_SET)) { if (isWorkingSetEnabled(workingSet)) { return false; } } } return true; } public static boolean isWorkingSetEnabled(IWorkingSet set) { IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (IWorkingSet enabledSet : enabledSets) { if (enabledSet.equals(set)) { return true; } } return false; } public static boolean isOnlyTaskWorkingSetEnabled(IWorkingSet set) { if (!TaskWorkingSetUpdater.isWorkingSetEnabled(set)) { return false; } IWorkingSet[] enabledSets = TaskWorkingSetUpdater.getEnabledSets(); for (int i = 0; i < enabledSets.length; i++) { if (!enabledSets[i].equals(set) && enabledSets[i].getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { return false; } } return true; } private void processResourceDelta(TaskWorkingSetDelta result, IResourceDelta delta) { IResource resource = delta.getResource(); int type = resource.getType(); int index = result.indexOf(resource); int kind = delta.getKind(); int flags = delta.getFlags(); if (kind == IResourceDelta.CHANGED && type == IResource.PROJECT && index != -1) { if ((flags & IResourceDelta.OPEN) != 0) { result.set(index, resource); } } if (index != -1 && kind == IResourceDelta.REMOVED) { if ((flags & IResourceDelta.MOVED_TO) != 0) { result.set(index, ResourcesPlugin.getWorkspace().getRoot().findMember(delta.getMovedToPath())); } else { result.remove(index); } } // Don't dive into closed or opened projects if (projectGotClosedOrOpened(resource, kind, flags)) { return; } IResourceDelta[] children = delta.getAffectedChildren(); for (IResourceDelta element : children) { processResourceDelta(result, element); } } private boolean projectGotClosedOrOpened(IResource resource, int kind, int flags) { return resource.getType() == IResource.PROJECT && kind == IResourceDelta.CHANGED && (flags & IResourceDelta.OPEN) != 0; } public void resourceChanged(IResourceChangeEvent event) { for (IWorkingSet workingSet : workingSets) { TaskWorkingSetDelta workingSetDelta = new TaskWorkingSetDelta(workingSet); if (event.getDelta() != null) { processResourceDelta(workingSetDelta, event.getDelta()); } workingSetDelta.process(); } } /** * Must be called from the UI thread */ public static void applyWorkingSetsToAllWindows(Collection<IWorkingSet> workingSets) { IWorkingSet[] workingSetArray = workingSets.toArray(new IWorkingSet[workingSets.size()]); for (IWorkbenchWindow window : MonitorUi.getMonitoredWindows()) { for (IWorkbenchPage page : window.getPages()) { page.setWorkingSets(workingSetArray); } } } public static Set<IWorkingSet> getActiveWorkingSets(IWorkbenchWindow window) { if (window != null) { Set<IWorkingSet> allSets = new HashSet<IWorkingSet>(Arrays.asList(window.getActivePage().getWorkingSets())); Set<IWorkingSet> tasksSets = new HashSet<IWorkingSet>(allSets); for (IWorkingSet workingSet : allSets) { if (workingSet.getId() == null || !workingSet.getId().equalsIgnoreCase(TaskWorkingSetUpdater.ID_TASK_WORKING_SET)) { tasksSets.remove(workingSet); } } return tasksSets; } else { return Collections.emptySet(); } } }
NEW - bug 276823: wrong working set displayed in Task List after startup https://bugs.eclipse.org/bugs/show_bug.cgi?id=276823
org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/workingsets/TaskWorkingSetUpdater.java
NEW - bug 276823: wrong working set displayed in Task List after startup https://bugs.eclipse.org/bugs/show_bug.cgi?id=276823
Java
epl-1.0
978c8675dbe5cfe55d6f6484fe895c11885147ec
0
tassadarius/crypto,jcryptool/crypto,tassadarius/crypto,jcryptool/crypto
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2012, 2020 JCrypTool Team and Contributors * * 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 *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.crypto.ui.textloader.ui.wizard.loadtext; import java.io.File; import java.util.List; import java.util.Observable; import java.util.Observer; //import javax.annotation.PreDestroy; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData; import org.jcryptool.core.operations.editors.EditorsManager; import org.jcryptool.core.util.input.AbstractUIInput; import org.jcryptool.crypto.ui.textloader.ui.ControlHatcher; import org.jcryptool.crypto.ui.textmodify.wizard.ModifyWizard; import org.jcryptool.crypto.ui.textsource.TextInputWithSource; import org.jcryptool.crypto.ui.textsource.TextSourceType; public class LoadTextWizardPage extends WizardPage { protected Composite container; private Group grpText; private Composite compTextInputMode; private Composite composite; private Button btnJcteditor; private Combo comboEditorInputSelector; private Button btnDatei; private Composite compFileInputDetails; private Label lblFilenametxt; private Link linkChangeFile; private Button btnZwischenablageeigeneEingabe; private Group grpTextinputCtrls; private Composite textfieldComp; private Text txtInputText; private List<IEditorReference> editorRefs; private Button transformButton; private TransformData currentTransform; private TransformData lastTransform; private org.jcryptool.crypto.ui.textloader.ui.wizard.loadtext.TextonlyInput textOnlyInput; /** * The file that was last using the file selection wizard on press of the * "select text from file" radiobutton */ protected File fileTextInput; private TextInputWithSource initTextObject; private boolean isPageBuilt; private UIInputTextWithSource textInput; private ControlHatcher beforeWizardTextParasiteLabel; private ControlHatcher afterWizardTextParasiteLabel; private GridData text1lData; private Composite compTextshortened; private String lastDisplayedText; private String lastDisplayedFullText; /** * Create the wizard. */ public LoadTextWizardPage() { this(null, null); } @Override public void setVisible(boolean visible) { super.setVisible(visible); txtInputText.setFocus(); } public LoadTextWizardPage(ControlHatcher beforeWizardTextParasiteLabel, ControlHatcher afterWizardTextParasiteLabel) { super(Messages.LoadTextWizardPage_0); this.beforeWizardTextParasiteLabel = beforeWizardTextParasiteLabel; this.afterWizardTextParasiteLabel = afterWizardTextParasiteLabel; setTitle(Messages.LoadTextWizardPage_1); setDescription(Messages.LoadTextWizardPage_2); } /** * Create contents of the wizard. * @param parent */ @Override public void createControl(Composite parent) { container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(1, false)); container.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); if(beforeWizardTextParasiteLabel != null) { Control control = beforeWizardTextParasiteLabel.hatch(container); GridData lData = (GridData) control.getLayoutData(); lData.verticalSpan = 1; // lData.verticalIndent = 1; } { grpText = new Group(container, SWT.NONE); grpText.setText(Messages.TranspTextWizardPage_grpText_text); grpText.setLayout(new GridLayout(2, false)); grpText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); { compTextInputMode = new Composite(grpText, SWT.NONE); compTextInputMode.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); compTextInputMode.setLayout(new GridLayout(1, false)); Label lblLadenDesTextes = new Label(compTextInputMode, SWT.NONE); lblLadenDesTextes.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 1, 1)); lblLadenDesTextes.setBounds(0, 0, 55, 15); lblLadenDesTextes.setText(Messages.TranspTextWizardPage_lblLadenDesTextes_text); { composite = new Composite(compTextInputMode, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); composite.setLayout(new GridLayout(1, false)); { btnJcteditor = new Button(composite, SWT.RADIO); btnJcteditor.setText(Messages.TranspTextWizardPage_btnJcteditor_text); } { comboEditorInputSelector = new Combo(composite, SWT.NONE) { @Override protected void checkSubclass() {}; @Override public org.eclipse.swt.graphics.Point computeSize(int wHint, int hHint, boolean changed) { Point result = super.computeSize(wHint, hHint, changed); return new Point(getAppropriateXValue(result.x, 160), result.y); }; private int getAppropriateXValue(int superXCalc, int maxSize) { return Math.min(superXCalc, maxSize); } }; GridData gd_comboEditorInputSelector = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_comboEditorInputSelector.horizontalIndent = 15; comboEditorInputSelector.setLayoutData(gd_comboEditorInputSelector); } { btnDatei = new Button(composite, SWT.RADIO); btnDatei.setText(Messages.TranspTextWizardPage_btnDatei_text); } { compFileInputDetails = new Composite(composite, SWT.NONE); GridData gd_compFileInputDetails = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_compFileInputDetails.horizontalIndent = 15; compFileInputDetails.setLayoutData(gd_compFileInputDetails); GridLayout gl_compFileInputDetails = new GridLayout(2, false); gl_compFileInputDetails.marginWidth = 0; gl_compFileInputDetails.marginHeight = 0; compFileInputDetails.setLayout(gl_compFileInputDetails); lblFilenametxt = new Label(compFileInputDetails, SWT.NONE); lblFilenametxt.setBounds(0, 0, 55, 15); lblFilenametxt.setText(Messages.TranspTextWizardPage_lblFilenametxt_text); linkChangeFile = new Link(compFileInputDetails, SWT.NONE); linkChangeFile.setText(Messages.TranspTextWizardPage_link_text); } { btnZwischenablageeigeneEingabe = new Button(composite, SWT.RADIO); btnZwischenablageeigeneEingabe .setText(Messages.TranspTextWizardPage_btnZwischenablageeigeneEingabe_text); btnZwischenablageeigeneEingabe.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnZwischenablageeigeneEingabe.getSelection()) { doTxfieldActionPreservingVisibleLines(new Runnable() { @Override public void run() { txtInputText.setSelection(txtInputText.getText().length(), 0); txtInputText.forceFocus(); } }, txtInputText); } } }); } } } { grpTextinputCtrls = new Group(grpText, SWT.NONE); GridLayout group2Layout = new GridLayout(); grpTextinputCtrls.setLayout(group2Layout); GridData group2LData = new GridData(); group2LData.verticalAlignment = SWT.FILL; group2LData.grabExcessHorizontalSpace = true; group2LData.horizontalAlignment = GridData.FILL; grpTextinputCtrls.setLayoutData(group2LData); grpTextinputCtrls.setText(Messages.TranspTextWizardPage_text); { textfieldComp = new Composite(grpTextinputCtrls, SWT.NONE); GridLayout composite2Layout = new GridLayout(); composite2Layout.makeColumnsEqualWidth = true; composite2Layout.marginHeight = 0; composite2Layout.marginWidth = 0; GridData composite2LData = new GridData(); composite2LData.grabExcessHorizontalSpace = true; composite2LData.horizontalAlignment = GridData.FILL; composite2LData.grabExcessVerticalSpace = true; composite2LData.verticalAlignment = GridData.FILL; textfieldComp.setLayoutData(composite2LData); textfieldComp.setLayout(composite2Layout); { txtInputText = new Text(textfieldComp, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER); text1lData = new GridData(); text1lData.grabExcessVerticalSpace = true; text1lData.verticalAlignment = SWT.FILL; text1lData.grabExcessHorizontalSpace = true; text1lData.horizontalAlignment = GridData.FILL; compTextshortened = new Composite(textfieldComp, SWT.NONE); compTextshortened.setLayout(new GridLayout()); compTextshortened.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); Link lblTextshortened = new Link(compTextshortened, SWT.NONE); lblTextshortened.setText("The current text is too big to display in this text field. Click <a>here</a> to try loading it in full length anyways."); lblTextshortened.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { displayText(lastDisplayedFullText, false); } }); GC temp = new GC(txtInputText); int lines = 4; int charHeight = temp.getFontMetrics().getAscent() + 2 * temp.getFontMetrics().getLeading(); int height = lines * charHeight; temp.dispose(); text1lData.widthHint = 200; text1lData.heightHint = height; txtInputText.setLayoutData(text1lData); } } } { Composite textTransformComp = new Composite(grpText, SWT.NONE); textTransformComp.setLayoutData(new GridData(GridData.FILL_BOTH)); textTransformComp.setLayout(new GridLayout()); transformButton = new Button(textTransformComp, SWT.CHECK); transformButton.setText("Text filtern..."); transformButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ModifyWizard transformSelectionWizard = new ModifyWizard(); TransformData preTfData = new TransformData(); TransformData newTransform = null; if (transformButton.getSelection()) { if (lastTransform != null ) { preTfData = lastTransform; } transformSelectionWizard.setPredefinedData(preTfData); WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), transformSelectionWizard); int result = dialog.open(); if (result == 0) { newTransform = transformSelectionWizard.getWizardData(); lastTransform = newTransform; currentTransform = newTransform; textInput.synchronizeWithUserSide(); } else { currentTransform = null; transformButton.setSelection(false); textInput.synchronizeWithUserSide(); } } else { newTransform = null; currentTransform = newTransform; textInput.synchronizeWithUserSide(); } } }); } } if(afterWizardTextParasiteLabel != null) { // new Label(container, SWT.NONE); Control control = afterWizardTextParasiteLabel.hatch(container); GridData lData = (GridData) control.getLayoutData(); lData.verticalSpan = 1; lData.verticalIndent = 10; } initializeTextInput(); getTextInput().addObserver(new Observer() { @Override public void update(Observable o, Object arg) { if(getTextInput().getContent().getSourceType() == TextSourceType.USERINPUT) { grpTextinputCtrls.setText(Messages.LoadTextWizardPage_3); } else { grpTextinputCtrls.setText(Messages.TranspTextWizardPage_text); } } }); setControl(container); setPageComplete(true); isPageBuilt = true; } /** * Runs a runnable, which executes some code. The top visible line number of the text field is * remembered, and after the runnable has finished, the top visible line is restored is set to the remembered number. * * @param runnable */ protected void doTxfieldActionPreservingVisibleLines(final Runnable runnable, Text textfield) { final Display display = textfield.getDisplay(); final int topIndex = textfield.getTopIndex(); runnable.run(); new Thread() { @Override public void run() { try { Thread.sleep(20); } catch (InterruptedException e) { LogUtil.logError(e); } Runnable r = new Runnable() { @Override public void run() { txtInputText.setTopIndex(topIndex); } }; display.syncExec(r); }; }.start(); } private void loadEditorsAndFillEditorChooser() { IEditorReference activeReference = EditorsManager.getInstance().getActiveEditorReference(); for (int i = 0; i < editorRefs.size(); i++) { comboEditorInputSelector.add(editorRefs.get(i).getTitle()); if (activeReference != null && activeReference.equals(editorRefs.get(i))) { comboEditorInputSelector.setText(editorRefs.get(i).getTitle()); comboEditorInputSelector.select(i); } } if (activeReference == null) { if (editorRefs.size() > 0) { comboEditorInputSelector.select(0); } } } private void initializeTextInput() { editorRefs = EditorsManager.getInstance().getEditorReferences(); if (editorRefs.size() > 0) { // TODO: rename method (no loading here!) loadEditorsAndFillEditorChooser(); } textOnlyInput = new TextonlyInput() { @Override public Text getTextfield() { return txtInputText; } }; textInput = new UIInputTextWithSource(editorRefs) { @Override protected Button getFileRadioButton() { return btnDatei; } @Override protected Button getBtnJctEditorOption() { return btnJcteditor; } @Override protected Button getBtnOwninput() { return btnZwischenablageeigeneEingabe; } @Override protected Button getBtnTransformation() { return transformButton; } @Override protected TransformData getTransformData() { return currentTransform; } @Override protected File getSelectedFile() { return fileTextInput; } @Override protected Combo getComboEditors() { return comboEditorInputSelector; } @Override protected Text getTextFieldForTextInput() { return txtInputText; } @Override protected IEditorReference getSelectedEditor() { return getCurrentlySelectedEditor(); } @Override protected void setUIState(TextInputWithSource content, boolean b) { setTextInputUIState(content, b); } @Override protected TextInputWithSource getInitialTextObject() { return initTextObject; } @Override protected List<IEditorReference> getEditorsNotNecessarilyFresh() { return editorRefs; } @Override protected AbstractUIInput<String> getTextOnlyInput() { return textOnlyInput; } }; btnJcteditor.setEnabled(editorRefs.size() > 0); btnDatei.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnDatei.getSelection()) { if (fileTextInput == null) fileTextInput = openFileSelectionDialogue(); textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); btnJcteditor.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnJcteditor.getSelection()) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); btnZwischenablageeigeneEingabe.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnZwischenablageeigeneEingabe.getSelection()) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); comboEditorInputSelector.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } }); linkChangeFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileTextInput = openFileSelectionDialogue(); textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } }); } /** * Assumes that the selection index is not "-1" -> something is actually * selected * * @return */ protected IEditorReference getCurrentlySelectedEditor() { int index = comboEditorInputSelector.getSelectionIndex(); return editorRefs.get(index); } private void setText(TextInputWithSource initFirstTabText) { if (isPageBuilt()) { textInput.writeContent(initFirstTabText); textInput.synchronizeWithUserSide(); } else { initTextObject = initFirstTabText; } } protected void setTextInputUIState(TextInputWithSource text, boolean writeText) { TextSourceType sourceType = text.getSourceType(); String textString = text.getText(); btnDatei.setSelection(sourceType.equals(TextSourceType.FILE)); btnJcteditor.setSelection(sourceType.equals(TextSourceType.JCTEDITOR)); btnZwischenablageeigeneEingabe.setSelection(sourceType.equals(TextSourceType.USERINPUT)); if (writeText) { if (textInput != null) { displayText(textString); textOnlyInput.synchronizeWithUserSide(); } else { displayText(textString); } } showLoadFromEditorComponents(sourceType.equals(TextSourceType.JCTEDITOR)); if (sourceType.equals(TextSourceType.JCTEDITOR)) { //TODO: comboEditorInputSelector.select(editorRefs.indexOf(text.editorReference)); } if (sourceType.equals(TextSourceType.FILE)) { showLoadFromFileComponents(sourceType.equals(TextSourceType.FILE), text.file.getName()); // fileTextInput is somewhat the representation of the file // selection wizard UI, so this fits here fileTextInput = text.file; } else { showLoadFromFileComponents(sourceType.equals(TextSourceType.FILE), ""); //$NON-NLS-1$ } txtInputText.setEditable(sourceType.equals(TextSourceType.USERINPUT)); } private void displayText(String textString, boolean shortenIfNecessary) { // TODO Auto-generated method stub boolean makePreview = shortenIfNecessary && textString.length() > 50000; String previewText = textString; if (makePreview) { previewText = textString.subSequence(0, Math.min(textString.length(), 50000)).toString(); } lastDisplayedText = previewText; lastDisplayedFullText = textString; txtInputText.setText(previewText); toggleTextshortenedDisplay(lastDisplayedText.length() < lastDisplayedFullText.length(), textString); } private void displayText(String textString) { displayText(textString, true); } private void toggleTextshortenedDisplay(boolean b, String textString) { GridData ldata = (GridData) compTextshortened.getLayoutData(); ldata.exclude = !b; compFileInputDetails.setVisible(b); container.layout(new Control[] { compTextshortened }); } /** * Opens a modal dialogue to select a file from the file system. If the file * selection is cancelled, null is returned. * * @return the file, or null at dialogue cancel */ protected File openFileSelectionDialogue() { FileDialog fd = new FileDialog(btnDatei.getShell(), SWT.OPEN); fd.setText(Messages.TranspTextWizardPage_windowsfiledialogtitle); fd.setFilterPath(null); String[] filterExt = { "*.*" }; //$NON-NLS-1$ fd.setFilterExtensions(filterExt); String selected = fd.open(); if (selected == null) return null; return new File(selected); } public boolean isPageBuilt() { return isPageBuilt; } private void showLoadFromFileComponents(boolean b, String fileName) { if (b) { GridData ldata = (GridData) compFileInputDetails.getLayoutData(); ldata.exclude = !b; compFileInputDetails.setVisible(b); lblFilenametxt.setText(fileName); container.layout(new Control[] { lblFilenametxt, linkChangeFile, compFileInputDetails }); } else { GridData ldata = (GridData) compFileInputDetails.getLayoutData(); ldata.exclude = !b; compFileInputDetails.setVisible(b); container.layout(new Control[] { lblFilenametxt, linkChangeFile, compFileInputDetails }); } } private void showLoadFromEditorComponents(boolean b) { if (b) { GridData ldata = (GridData) comboEditorInputSelector.getLayoutData(); ldata.exclude = !b; comboEditorInputSelector.setVisible(b); container.layout(new Control[] { comboEditorInputSelector }); } else { GridData ldata = (GridData) comboEditorInputSelector.getLayoutData(); ldata.exclude = !b; comboEditorInputSelector.setVisible(b); container.layout(new Control[] { comboEditorInputSelector }); } } public void setPageConfiguration(TextInputWithSource config) { setText(config); } public TextInputWithSource getPageConfiguration() { return textInput.getContent(); } public UIInputTextWithSource getTextInput() { return textInput; } }
org.jcryptool.crypto.ui/src/org/jcryptool/crypto/ui/textloader/ui/wizard/loadtext/LoadTextWizardPage.java
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2012, 2020 JCrypTool Team and Contributors * * 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 *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.crypto.ui.textloader.ui.wizard.loadtext; import java.io.File; import java.util.List; import java.util.Observable; import java.util.Observer; //import javax.annotation.PreDestroy; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Link; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.PlatformUI; import org.jcryptool.core.logging.utils.LogUtil; import org.jcryptool.core.operations.algorithm.classic.textmodify.TransformData; import org.jcryptool.core.operations.editors.EditorsManager; import org.jcryptool.core.util.input.AbstractUIInput; import org.jcryptool.crypto.ui.textloader.ui.ControlHatcher; import org.jcryptool.crypto.ui.textmodify.wizard.ModifyWizard; import org.jcryptool.crypto.ui.textsource.TextInputWithSource; import org.jcryptool.crypto.ui.textsource.TextSourceType; public class LoadTextWizardPage extends WizardPage { protected Composite container; private Group grpText; private Composite compTextInputMode; private Composite composite; private Button btnJcteditor; private Combo comboEditorInputSelector; private Button btnDatei; private Composite compFileInputDetails; private Label lblFilenametxt; private Link linkChangeFile; private Button btnZwischenablageeigeneEingabe; private Group grpTextinputCtrls; private Composite textfieldComp; private Text txtInputText; private List<IEditorReference> editorRefs; private Button transformButton; private TransformData currentTransform; private TransformData lastTransform; private org.jcryptool.crypto.ui.textloader.ui.wizard.loadtext.TextonlyInput textOnlyInput; /** * The file that was last using the file selection wizard on press of the * "select text from file" radiobutton */ protected File fileTextInput; private TextInputWithSource initTextObject; private boolean isPageBuilt; private UIInputTextWithSource textInput; private ControlHatcher beforeWizardTextParasiteLabel; private ControlHatcher afterWizardTextParasiteLabel; /** * Create the wizard. */ public LoadTextWizardPage() { this(null, null); } @Override public void setVisible(boolean visible) { super.setVisible(visible); txtInputText.setFocus(); } public LoadTextWizardPage(ControlHatcher beforeWizardTextParasiteLabel, ControlHatcher afterWizardTextParasiteLabel) { super(Messages.LoadTextWizardPage_0); this.beforeWizardTextParasiteLabel = beforeWizardTextParasiteLabel; this.afterWizardTextParasiteLabel = afterWizardTextParasiteLabel; setTitle(Messages.LoadTextWizardPage_1); setDescription(Messages.LoadTextWizardPage_2); } /** * Create contents of the wizard. * @param parent */ @Override public void createControl(Composite parent) { container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout(1, false)); container.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); if(beforeWizardTextParasiteLabel != null) { Control control = beforeWizardTextParasiteLabel.hatch(container); GridData lData = (GridData) control.getLayoutData(); lData.verticalSpan = 1; // lData.verticalIndent = 1; } { grpText = new Group(container, SWT.NONE); grpText.setText(Messages.TranspTextWizardPage_grpText_text); grpText.setLayout(new GridLayout(2, false)); grpText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); { compTextInputMode = new Composite(grpText, SWT.NONE); compTextInputMode.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1)); compTextInputMode.setLayout(new GridLayout(1, false)); Label lblLadenDesTextes = new Label(compTextInputMode, SWT.NONE); lblLadenDesTextes.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 1, 1)); lblLadenDesTextes.setBounds(0, 0, 55, 15); lblLadenDesTextes.setText(Messages.TranspTextWizardPage_lblLadenDesTextes_text); { composite = new Composite(compTextInputMode, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); composite.setLayout(new GridLayout(1, false)); { btnJcteditor = new Button(composite, SWT.RADIO); btnJcteditor.setText(Messages.TranspTextWizardPage_btnJcteditor_text); } { comboEditorInputSelector = new Combo(composite, SWT.NONE) { @Override protected void checkSubclass() {}; @Override public org.eclipse.swt.graphics.Point computeSize(int wHint, int hHint, boolean changed) { Point result = super.computeSize(wHint, hHint, changed); return new Point(getAppropriateXValue(result.x, 160), result.y); }; private int getAppropriateXValue(int superXCalc, int maxSize) { return Math.min(superXCalc, maxSize); } }; GridData gd_comboEditorInputSelector = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1); gd_comboEditorInputSelector.horizontalIndent = 15; comboEditorInputSelector.setLayoutData(gd_comboEditorInputSelector); } { btnDatei = new Button(composite, SWT.RADIO); btnDatei.setText(Messages.TranspTextWizardPage_btnDatei_text); } { compFileInputDetails = new Composite(composite, SWT.NONE); GridData gd_compFileInputDetails = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1); gd_compFileInputDetails.horizontalIndent = 15; compFileInputDetails.setLayoutData(gd_compFileInputDetails); GridLayout gl_compFileInputDetails = new GridLayout(2, false); gl_compFileInputDetails.marginWidth = 0; gl_compFileInputDetails.marginHeight = 0; compFileInputDetails.setLayout(gl_compFileInputDetails); lblFilenametxt = new Label(compFileInputDetails, SWT.NONE); lblFilenametxt.setBounds(0, 0, 55, 15); lblFilenametxt.setText(Messages.TranspTextWizardPage_lblFilenametxt_text); linkChangeFile = new Link(compFileInputDetails, SWT.NONE); linkChangeFile.setText(Messages.TranspTextWizardPage_link_text); } { btnZwischenablageeigeneEingabe = new Button(composite, SWT.RADIO); btnZwischenablageeigeneEingabe .setText(Messages.TranspTextWizardPage_btnZwischenablageeigeneEingabe_text); btnZwischenablageeigeneEingabe.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if(btnZwischenablageeigeneEingabe.getSelection()) { doTxfieldActionPreservingVisibleLines(new Runnable() { @Override public void run() { txtInputText.setSelection(txtInputText.getText().length(), 0); txtInputText.forceFocus(); } }, txtInputText); } } }); } } } { grpTextinputCtrls = new Group(grpText, SWT.NONE); GridLayout group2Layout = new GridLayout(); grpTextinputCtrls.setLayout(group2Layout); GridData group2LData = new GridData(); group2LData.verticalAlignment = SWT.FILL; group2LData.grabExcessHorizontalSpace = true; group2LData.horizontalAlignment = GridData.FILL; grpTextinputCtrls.setLayoutData(group2LData); grpTextinputCtrls.setText(Messages.TranspTextWizardPage_text); { textfieldComp = new Composite(grpTextinputCtrls, SWT.NONE); GridLayout composite2Layout = new GridLayout(); composite2Layout.makeColumnsEqualWidth = true; composite2Layout.marginHeight = 0; composite2Layout.marginWidth = 0; GridData composite2LData = new GridData(); composite2LData.grabExcessHorizontalSpace = true; composite2LData.horizontalAlignment = GridData.FILL; composite2LData.grabExcessVerticalSpace = true; composite2LData.verticalAlignment = GridData.FILL; textfieldComp.setLayoutData(composite2LData); textfieldComp.setLayout(composite2Layout); { txtInputText = new Text(textfieldComp, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER); GridData text1LData = new GridData(); text1LData.grabExcessVerticalSpace = true; text1LData.verticalAlignment = SWT.FILL; text1LData.grabExcessHorizontalSpace = true; text1LData.horizontalAlignment = GridData.FILL; GC temp = new GC(txtInputText); int lines = 4; int charHeight = temp.getFontMetrics().getAscent() + 2 * temp.getFontMetrics().getLeading(); int height = lines * charHeight; temp.dispose(); text1LData.widthHint = 200; text1LData.heightHint = height; txtInputText.setLayoutData(text1LData); } } } { Composite textTransformComp = new Composite(grpText, SWT.NONE); textTransformComp.setLayoutData(new GridData(GridData.FILL_BOTH)); textTransformComp.setLayout(new GridLayout()); transformButton = new Button(textTransformComp, SWT.CHECK); transformButton.setText("Text filtern..."); transformButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { ModifyWizard transformSelectionWizard = new ModifyWizard(); TransformData preTfData = new TransformData(); TransformData newTransform = null; if (transformButton.getSelection()) { if (lastTransform != null ) { preTfData = lastTransform; } transformSelectionWizard.setPredefinedData(preTfData); WizardDialog dialog = new WizardDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), transformSelectionWizard); int result = dialog.open(); if (result == 0) { newTransform = transformSelectionWizard.getWizardData(); lastTransform = newTransform; currentTransform = newTransform; textInput.synchronizeWithUserSide(); } else { currentTransform = null; transformButton.setSelection(false); textInput.synchronizeWithUserSide(); } } else { newTransform = null; currentTransform = newTransform; textInput.synchronizeWithUserSide(); } } }); } } if(afterWizardTextParasiteLabel != null) { // new Label(container, SWT.NONE); Control control = afterWizardTextParasiteLabel.hatch(container); GridData lData = (GridData) control.getLayoutData(); lData.verticalSpan = 1; lData.verticalIndent = 10; } initializeTextInput(); getTextInput().addObserver(new Observer() { @Override public void update(Observable o, Object arg) { if(getTextInput().getContent().getSourceType() == TextSourceType.USERINPUT) { grpTextinputCtrls.setText(Messages.LoadTextWizardPage_3); } else { grpTextinputCtrls.setText(Messages.TranspTextWizardPage_text); } } }); setControl(container); setPageComplete(true); isPageBuilt = true; } /** * Runs a runnable, which executes some code. The top visible line number of the text field is * remembered, and after the runnable has finished, the top visible line is restored is set to the remembered number. * * @param runnable */ protected void doTxfieldActionPreservingVisibleLines(final Runnable runnable, Text textfield) { final Display display = textfield.getDisplay(); final int topIndex = textfield.getTopIndex(); runnable.run(); new Thread() { @Override public void run() { try { Thread.sleep(20); } catch (InterruptedException e) { LogUtil.logError(e); } Runnable r = new Runnable() { @Override public void run() { txtInputText.setTopIndex(topIndex); } }; display.syncExec(r); }; }.start(); } private void loadEditorsAndFillEditorChooser() { IEditorReference activeReference = EditorsManager.getInstance().getActiveEditorReference(); for (int i = 0; i < editorRefs.size(); i++) { comboEditorInputSelector.add(editorRefs.get(i).getTitle()); if (activeReference != null && activeReference.equals(editorRefs.get(i))) { comboEditorInputSelector.setText(editorRefs.get(i).getTitle()); comboEditorInputSelector.select(i); } } if (activeReference == null) { if (editorRefs.size() > 0) { comboEditorInputSelector.select(0); } } } private void initializeTextInput() { editorRefs = EditorsManager.getInstance().getEditorReferences(); if (editorRefs.size() > 0) { // TODO: rename method (no loading here!) loadEditorsAndFillEditorChooser(); } textOnlyInput = new TextonlyInput() { @Override public Text getTextfield() { return txtInputText; } }; textInput = new UIInputTextWithSource(editorRefs) { @Override protected Button getFileRadioButton() { return btnDatei; } @Override protected Button getBtnJctEditorOption() { return btnJcteditor; } @Override protected Button getBtnOwninput() { return btnZwischenablageeigeneEingabe; } @Override protected Button getBtnTransformation() { return transformButton; } @Override protected TransformData getTransformData() { return currentTransform; } @Override protected File getSelectedFile() { return fileTextInput; } @Override protected Combo getComboEditors() { return comboEditorInputSelector; } @Override protected Text getTextFieldForTextInput() { return txtInputText; } @Override protected IEditorReference getSelectedEditor() { return getCurrentlySelectedEditor(); } @Override protected void setUIState(TextInputWithSource content, boolean b) { setTextInputUIState(content, b); } @Override protected TextInputWithSource getInitialTextObject() { return initTextObject; } @Override protected List<IEditorReference> getEditorsNotNecessarilyFresh() { return editorRefs; } @Override protected AbstractUIInput<String> getTextOnlyInput() { return textOnlyInput; } }; btnJcteditor.setEnabled(editorRefs.size() > 0); btnDatei.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnDatei.getSelection()) { if (fileTextInput == null) fileTextInput = openFileSelectionDialogue(); textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); btnJcteditor.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnJcteditor.getSelection()) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); btnZwischenablageeigeneEingabe.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (btnZwischenablageeigeneEingabe.getSelection()) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } } }); comboEditorInputSelector.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } }); linkChangeFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fileTextInput = openFileSelectionDialogue(); textInput.synchronizeWithUserSide(); setTextInputUIState(textInput.getContent(), true); } }); } /** * Assumes that the selection index is not "-1" -> something is actually * selected * * @return */ protected IEditorReference getCurrentlySelectedEditor() { int index = comboEditorInputSelector.getSelectionIndex(); return editorRefs.get(index); } private void setText(TextInputWithSource initFirstTabText) { if (isPageBuilt()) { textInput.writeContent(initFirstTabText); textInput.synchronizeWithUserSide(); } else { initTextObject = initFirstTabText; } } protected void setTextInputUIState(TextInputWithSource text, boolean writeText) { TextSourceType sourceType = text.getSourceType(); String textString = text.getText(); btnDatei.setSelection(sourceType.equals(TextSourceType.FILE)); btnJcteditor.setSelection(sourceType.equals(TextSourceType.JCTEDITOR)); btnZwischenablageeigeneEingabe.setSelection(sourceType.equals(TextSourceType.USERINPUT)); if (writeText) { if (textInput != null) { textOnlyInput.writeContent(textString); textOnlyInput.synchronizeWithUserSide(); } else { txtInputText.setText(textString); } } showLoadFromEditorComponents(sourceType.equals(TextSourceType.JCTEDITOR)); if (sourceType.equals(TextSourceType.JCTEDITOR)) { //TODO: comboEditorInputSelector.select(editorRefs.indexOf(text.editorReference)); } if (sourceType.equals(TextSourceType.FILE)) { showLoadFromFileComponents(sourceType.equals(TextSourceType.FILE), text.file.getName()); // fileTextInput is somewhat the representation of the file // selection wizard UI, so this fits here fileTextInput = text.file; } else { showLoadFromFileComponents(sourceType.equals(TextSourceType.FILE), ""); //$NON-NLS-1$ } txtInputText.setEditable(sourceType.equals(TextSourceType.USERINPUT)); } /** * Opens a modal dialogue to select a file from the file system. If the file * selection is cancelled, null is returned. * * @return the file, or null at dialogue cancel */ protected File openFileSelectionDialogue() { FileDialog fd = new FileDialog(btnDatei.getShell(), SWT.OPEN); fd.setText(Messages.TranspTextWizardPage_windowsfiledialogtitle); fd.setFilterPath(null); String[] filterExt = { "*.*" }; //$NON-NLS-1$ fd.setFilterExtensions(filterExt); String selected = fd.open(); if (selected == null) return null; return new File(selected); } public boolean isPageBuilt() { return isPageBuilt; } private void showLoadFromFileComponents(boolean b, String fileName) { if (b) { GridData ldata = (GridData) compFileInputDetails.getLayoutData(); ldata.exclude = !b; compFileInputDetails.setVisible(b); lblFilenametxt.setText(fileName); container.layout(new Control[] { lblFilenametxt, linkChangeFile, compFileInputDetails }); } else { GridData ldata = (GridData) compFileInputDetails.getLayoutData(); ldata.exclude = !b; compFileInputDetails.setVisible(b); container.layout(new Control[] { lblFilenametxt, linkChangeFile, compFileInputDetails }); } } private void showLoadFromEditorComponents(boolean b) { if (b) { GridData ldata = (GridData) comboEditorInputSelector.getLayoutData(); ldata.exclude = !b; comboEditorInputSelector.setVisible(b); container.layout(new Control[] { comboEditorInputSelector }); } else { GridData ldata = (GridData) comboEditorInputSelector.getLayoutData(); ldata.exclude = !b; comboEditorInputSelector.setVisible(b); container.layout(new Control[] { comboEditorInputSelector }); } } public void setPageConfiguration(TextInputWithSource config) { setText(config); } public TextInputWithSource getPageConfiguration() { return textInput.getContent(); } public UIInputTextWithSource getTextInput() { return textInput; } }
Squashed: Textloader improvements and fix
org.jcryptool.crypto.ui/src/org/jcryptool/crypto/ui/textloader/ui/wizard/loadtext/LoadTextWizardPage.java
Squashed: Textloader improvements and fix
Java
epl-1.0
4ceb9c52c798a3d26b3f820b5b9f9bd2a95b9ca5
0
fabioz/Pydev,RandallDW/Aruba_plugin,RandallDW/Aruba_plugin,fabioz/Pydev,rajul/Pydev,rajul/Pydev,aptana/Pydev,rgom/Pydev,rajul/Pydev,RandallDW/Aruba_plugin,rgom/Pydev,rgom/Pydev,rgom/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev,aptana/Pydev,rgom/Pydev,rgom/Pydev,fabioz/Pydev,akurtakov/Pydev,rajul/Pydev,fabioz/Pydev,aptana/Pydev,akurtakov/Pydev,akurtakov/Pydev,rajul/Pydev,rajul/Pydev,fabioz/Pydev,fabioz/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev,RandallDW/Aruba_plugin,akurtakov/Pydev
package org.python.pydev.debug.ui.actions; import java.util.Set; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IValue; import org.eclipse.debug.core.model.IWatchExpression; import org.eclipse.debug.ui.DebugPopup; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.python.pydev.debug.core.PydevDebugPlugin; /** * The original idea was not to use the <code>org.eclipse.jdt.internal.debug.ui</code> stuff; that's why this does not do things like extending * {@link org.eclipse.jdt.internal.debug.ui.actions.PopupDisplayAction}, etc. But after all was said and done, I didn't feel like finding an alternate way of writing {@link DisplayPopup#persist()}, * so this does result in depending on <code>org.eclipse.jdt.debug.ui</code> just for that - silly me. But then again, the original had dependencies on <code>org.eclipse.jdt</code>, * <code>org.eclipse.jdt.code</code> and <code>org.eclipse.jdt.launching</code>, so what's one extra one? * * @see * * @author "<a href=mailto:[email protected]>Gregory Golberg</A>" */ public class EvalExpressionAction extends AbstractHandler implements IHandler, IEditorActionDelegate { public static final String ACTION_DEFINITION_ID = "org.python.pydev.debug.command.Display"; //$NON-NLS-1$ private ITextSelection fSelection; public void setActiveEditor(IAction action, IEditorPart targetEditor) { } public void run(IAction action) { if (fSelection == null) { return; } String text = fSelection.getText(); eval(text); } public void selectionChanged(IAction action, ISelection selection) { fSelection = null; if (selection instanceof ITextSelection) { fSelection = (ITextSelection) selection; } } /** * This hack just creates a Watch expression, gets result and removes the watch expression. This is simple, since the watch functionality is already there. * * @see WatchExpressionAction#createExpression */ private void eval(final String expr) { final IWatchExpression expression = DebugPlugin.getDefault().getExpressionManager().newWatchExpression(expr); IAdaptable object = DebugUITools.getDebugContext(); IDebugElement context = null; if (object instanceof IDebugElement) { context = (IDebugElement) object; } else if (object instanceof ILaunch) { context = ((ILaunch) object).getDebugTarget(); } expression.setExpressionContext(context); final Shell shell = PydevDebugPlugin.getActiveWorkbenchWindow().getShell(); Display display = PydevDebugPlugin.getDefault().getWorkbench().getDisplay(); final Point point = display.getCursorLocation(); Display.getDefault().asyncExec(new Runnable() { public void run() { expression.evaluate(); while (expression.isPending()) { try { Thread.sleep(50); } catch (InterruptedException e) { continue; } } try { try { Thread.sleep(50); } catch (InterruptedException e) { } IValue value = expression.getValue(); String result = null; if (value != null) { result = expr+"\n"+value.getValueString(); DisplayPopup popup = new DisplayPopup(shell, point, result); popup.open(); } } catch (DebugException e) { e.printStackTrace(); DebugPlugin.log(e); return; } catch (Throwable t) { t.printStackTrace(); DebugPlugin.log(t); } } }); } public Object execute(ExecutionEvent event) throws ExecutionException { try { EvaluationContext evalCtx = (org.eclipse.core.expressions.EvaluationContext) event.getApplicationContext(); Set set = (Set) evalCtx.getDefaultVariable(); TextSelection[] sels = (TextSelection[]) set.toArray(new TextSelection[] {}); String expr = sels[0].getText(); if(expr != null && expr.trim().length() > 0){ eval(expr); } } catch (ClassCastException cce) { DebugPlugin.log(cce); } return null; } /** * @see org.eclipse.jdt.internal.debug.ui.actions.PopupDisplayAction.DisplayPopup */ private class DisplayPopup extends DebugPopup { public DisplayPopup(Shell shell, Point point, String text) { super(shell, point, ACTION_DEFINITION_ID + "2"); this.text = text; } protected String getActionText() { return "Move to Display view"; } protected void persist() { // String displayId = IJavaDebugUIConstants.ID_DISPLAY_VIEW; // IWorkbenchPage page = PydevDebugPlugin.getActiveWorkbenchWindow().getActivePage(); // IViewReference viewRef = page.findViewReference(displayId); // IViewPart view = null; // if (viewRef != null) { // view = viewRef.getView(true); // } else { // try { // view = page.showView(displayId); // } catch (PartInitException e) { // DebugPlugin.log(e); // return; // } // } // page.activate(page.getActivePart()); // IDataDisplay adapter = (IDataDisplay) view.getAdapter(IDataDisplay.class); // adapter.displayExpression(this.text); super.persist(); } private String text; protected Control createDialogArea(Composite parent) { GridData gd = new GridData(GridData.FILL_BOTH); StyledText text = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL); text.setLayoutData(gd); text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); text.setText(this.text); return text; } } }
org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/EvalExpressionAction.java
package org.python.pydev.debug.ui.actions; import java.util.Set; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.core.commands.IHandlerListener; import org.eclipse.core.expressions.EvaluationContext; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IDebugElement; import org.eclipse.debug.core.model.IValue; import org.eclipse.debug.core.model.IWatchExpression; import org.eclipse.debug.ui.DebugPopup; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorActionDelegate; import org.eclipse.ui.IEditorPart; import org.python.pydev.debug.core.PydevDebugPlugin; /** * The original idea was not to use the <code>org.eclipse.jdt.internal.debug.ui</code> stuff; that's why this does not do things like extending * {@link org.eclipse.jdt.internal.debug.ui.actions.PopupDisplayAction}, etc. But after all was said and done, I didn't feel like finding an alternate way of writing {@link DisplayPopup#persist()}, * so this does result in depending on <code>org.eclipse.jdt.debug.ui</code> just for that - silly me. But then again, the original had dependencies on <code>org.eclipse.jdt</code>, * <code>org.eclipse.jdt.code</code> and <code>org.eclipse.jdt.launching</code>, so what's one extra one? * * @see * * @author "<a href=mailto:[email protected]>Gregory Golberg</A>" */ public class EvalExpressionAction extends AbstractHandler implements IHandler, IEditorActionDelegate { public static final String ACTION_DEFINITION_ID = "org.python.pydev.debug.command.Display"; //$NON-NLS-1$ private ITextSelection fSelection; public void setActiveEditor(IAction action, IEditorPart targetEditor) { } public void run(IAction action) { if (fSelection == null) { return; } String text = fSelection.getText(); eval(text); } public void selectionChanged(IAction action, ISelection selection) { fSelection = null; if (selection instanceof ITextSelection) { fSelection = (ITextSelection) selection; } } /** * This hack just creates a Watch expression, gets result and removes the watch expression. This is simple, since the watch functionality is already there. * * @see WatchExpressionAction#createExpression */ private void eval(final String expr) { final IWatchExpression expression = DebugPlugin.getDefault().getExpressionManager().newWatchExpression(expr); IAdaptable object = DebugUITools.getDebugContext(); IDebugElement context = null; if (object instanceof IDebugElement) { context = (IDebugElement) object; } else if (object instanceof ILaunch) { context = ((ILaunch) object).getDebugTarget(); } expression.setExpressionContext(context); final Shell shell = PydevDebugPlugin.getActiveWorkbenchWindow().getShell(); Display display = PydevDebugPlugin.getDefault().getWorkbench().getDisplay(); final Point point = display.getCursorLocation(); Display.getDefault().asyncExec(new Runnable() { public void run() { expression.evaluate(); while (expression.isPending()) { try { Thread.sleep(50); } catch (InterruptedException e) { continue; } } try { try { Thread.sleep(50); } catch (InterruptedException e) { } IValue value = expression.getValue(); String result = null; if (value != null) { result = expr+"\n"+value.getValueString(); DisplayPopup popup = new DisplayPopup(shell, point, result); popup.open(); } } catch (DebugException e) { e.printStackTrace(); DebugPlugin.log(e); return; } catch (Throwable t) { t.printStackTrace(); DebugPlugin.log(t); } } }); } public Object execute(ExecutionEvent event) throws ExecutionException { try { EvaluationContext evalCtx = (org.eclipse.core.expressions.EvaluationContext) event.getApplicationContext(); Set set = (Set) evalCtx.getDefaultVariable(); TextSelection[] sels = (TextSelection[]) set.toArray(new TextSelection[] {}); String expr = sels[0].getText(); if(expr != null && expr.trim().length() > 0){ eval(expr); } } catch (ClassCastException cce) { DebugPlugin.log(cce); } return null; } /** * @see org.eclipse.jdt.internal.debug.ui.actions.PopupDisplayAction.DisplayPopup */ private class DisplayPopup extends DebugPopup { public DisplayPopup(Shell shell, Point point, String text) { super(shell, point, ACTION_DEFINITION_ID + "2"); this.text = text; } protected String getActionText() { return "Move to Display view"; } protected void persist() { // String displayId = IJavaDebugUIConstants.ID_DISPLAY_VIEW; // IWorkbenchPage page = PydevDebugPlugin.getActiveWorkbenchWindow().getActivePage(); // IViewReference viewRef = page.findViewReference(displayId); // IViewPart view = null; // if (viewRef != null) { // view = viewRef.getView(true); // } else { // try { // view = page.showView(displayId); // } catch (PartInitException e) { // DebugPlugin.log(e); // return; // } // } // page.activate(page.getActivePart()); // IDataDisplay adapter = (IDataDisplay) view.getAdapter(IDataDisplay.class); // adapter.displayExpression(this.text); super.persist(); } private String text; protected Control createDialogArea(Composite parent) { GridData gd = new GridData(GridData.FILL_BOTH); StyledText text = new StyledText(parent, SWT.MULTI | SWT.READ_ONLY | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL); text.setLayoutData(gd); text.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); text.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); text.setText(this.text); return text; } } }
*** empty log message *** git-svn-id: cdbd3c3453b226d8644b39c93ea790e37ea3ca1b@1923 7f4d9e04-a92a-ab41-bea9-970b690ef4a7
org.python.pydev.debug/src/org/python/pydev/debug/ui/actions/EvalExpressionAction.java
*** empty log message ***
Java
agpl-3.0
2d58630cd8c1bcee3a20620e7e8c9283423094c8
0
Marine-22/libre,LibrePlan/libreplan,skylow95/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,Marine-22/libre,Marine-22/libre,poum/libreplan,PaulLuchyn/libreplan,poum/libreplan,PaulLuchyn/libreplan,PaulLuchyn/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,LibrePlan/libreplan,poum/libreplan,LibrePlan/libreplan,skylow95/libreplan,skylow95/libreplan,LibrePlan/libreplan,LibrePlan/libreplan,poum/libreplan,poum/libreplan,dgray16/libreplan,PaulLuchyn/libreplan,Marine-22/libre,LibrePlan/libreplan,dgray16/libreplan,poum/libreplan,skylow95/libreplan,Marine-22/libre,skylow95/libreplan,skylow95/libreplan,dgray16/libreplan,Marine-22/libre,dgray16/libreplan,dgray16/libreplan,LibrePlan/libreplan,PaulLuchyn/libreplan
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundaciรณn para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolรณxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.templates.entities; import static org.libreplan.business.i18n.I18nHelper._; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.Validate; import org.hibernate.validator.NotNull; import org.hibernate.validator.Valid; import org.libreplan.business.orders.entities.HoursGroup; import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.orders.entities.OrderLine; import org.libreplan.business.orders.entities.OrderLineGroup; /** * @author ร“scar Gonzรกlez Fernรกndez <[email protected]> * @author Diego Pino Garcia <[email protected]> * */ public class OrderLineTemplate extends OrderElementTemplate { @Valid private Set<HoursGroup> hoursGroups = new HashSet<HoursGroup>(); private Integer lastHoursGroupSequenceCode = 0; public static OrderLineTemplate create(OrderLine orderLine) { OrderLineTemplate beingBuilt = new OrderLineTemplate(); copyHoursGroup(orderLine.getHoursGroups(), beingBuilt); beingBuilt.setBudget(orderLine.getBudget()); return create(beingBuilt, orderLine); } private static void copyHoursGroup( final Collection<HoursGroup> hoursGroups, OrderLineTemplate orderLineTemplate) { for (HoursGroup each: hoursGroups) { orderLineTemplate.addHoursGroup(HoursGroup.copyFrom(each, orderLineTemplate)); } } public static OrderLineTemplate createNew() { return createNew(new OrderLineTemplate()); } private BigDecimal budget = BigDecimal.ZERO.setScale(2); protected <T extends OrderElement> T setupElementParts(T orderElement) { super.setupElementParts(orderElement); setupHoursGroups((OrderLine) orderElement); setupBudget((OrderLine) orderElement); return orderElement; } private void setupHoursGroups(OrderLine orderLine) { Set<HoursGroup> result = new HashSet<HoursGroup>(); for (HoursGroup each: getHoursGroups()) { result.add(HoursGroup.copyFrom(each, orderLine)); } orderLine.setHoursGroups(result); } private void setupBudget(OrderLine orderLine) { orderLine.setBudget(getBudget()); } @Override public List<OrderElementTemplate> getChildrenTemplates() { return Collections.emptyList(); } @Override public OrderElementTemplate toLeaf() { return this; } @Override public OrderLineGroupTemplate toContainer() { OrderLineGroupTemplate result = OrderLineGroupTemplate.createNew(); copyTo(result); return result; } @Override public List<OrderElementTemplate> getChildren() { return new ArrayList<OrderElementTemplate>(); } @Override public boolean isLeaf() { return true; } @Override public OrderElement createElement(OrderLineGroup parent) { OrderLine line = setupSchedulingStateType(setupVersioningInfo(parent, OrderLine.createOrderLineWithUnfixedPercentage(getWorkHours()))); line.initializeTemplate(this); parent.add(line); return setupElementParts(line); } @Override public String getType() { return _("Line"); } public Integer getWorkHours() { return hoursGroupOrderLineTemplateHandler.calculateTotalHours(hoursGroups); } public void incrementLastHoursGroupSequenceCode() { if(lastHoursGroupSequenceCode==null){ lastHoursGroupSequenceCode = 0; } lastHoursGroupSequenceCode++; } @NotNull(message = "last hours group sequence code not specified") public Integer getLastHoursGroupSequenceCode() { return lastHoursGroupSequenceCode; } /** * Operations for manipulating {@link HoursGroup} */ @Override public List<HoursGroup> getHoursGroups() { return new ArrayList<HoursGroup>(hoursGroups); } public Set<HoursGroup> myHoursGroups() { return hoursGroups; } public void setHoursGroups(final Set<HoursGroup> hoursGroups) { this.hoursGroups.clear(); this.hoursGroups.addAll(hoursGroups); } public void addHoursGroup(HoursGroup hoursGroup) { hoursGroup.setOrderLineTemplate(this); hoursGroup.updateMyCriterionRequirements(); doAddHoursGroup(hoursGroup); recalculateHoursGroups(); } public void doAddHoursGroup(HoursGroup hoursGroup) { hoursGroups.add(hoursGroup); } public void deleteHoursGroup(HoursGroup hoursGroup) { hoursGroups.remove(hoursGroup); recalculateHoursGroups(); } private HoursGroupOrderLineTemplateHandler hoursGroupOrderLineTemplateHandler = HoursGroupOrderLineTemplateHandler .getInstance(); public void setWorkHours(Integer workHours) throws IllegalArgumentException { hoursGroupOrderLineTemplateHandler.setWorkHours(this, workHours); } public boolean isTotalHoursValid(Integer total) { return hoursGroupOrderLineTemplateHandler.isTotalHoursValid(total, hoursGroups); } public boolean isPercentageValid() { return hoursGroupOrderLineTemplateHandler.isPercentageValid(hoursGroups); } public void recalculateHoursGroups() { hoursGroupOrderLineTemplateHandler.recalculateHoursGroups(this); } public void setBudget(BigDecimal budget) { Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, "budget cannot be negative"); this.budget = budget.setScale(2); } @Override @NotNull(message = "budget not specified") public BigDecimal getBudget() { return budget; } }
libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundaciรณn para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolรณxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.templates.entities; import static org.libreplan.business.i18n.I18nHelper._; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.lang.Validate; import org.hibernate.validator.NotNull; import org.hibernate.validator.Valid; import org.libreplan.business.orders.entities.HoursGroup; import org.libreplan.business.orders.entities.OrderElement; import org.libreplan.business.orders.entities.OrderLine; import org.libreplan.business.orders.entities.OrderLineGroup; /** * @author ร“scar Gonzรกlez Fernรกndez <[email protected]> * @author Diego Pino Garcia <[email protected]> * */ public class OrderLineTemplate extends OrderElementTemplate { @Valid private Set<HoursGroup> hoursGroups = new HashSet<HoursGroup>(); private Integer lastHoursGroupSequenceCode = 0; public static OrderLineTemplate create(OrderLine orderLine) { OrderLineTemplate beingBuilt = new OrderLineTemplate(); copyHoursGroup(orderLine.getHoursGroups(), beingBuilt); return create(beingBuilt, orderLine); } private static void copyHoursGroup( final Collection<HoursGroup> hoursGroups, OrderLineTemplate orderLineTemplate) { for (HoursGroup each: hoursGroups) { orderLineTemplate.addHoursGroup(HoursGroup.copyFrom(each, orderLineTemplate)); } } public static OrderLineTemplate createNew() { return createNew(new OrderLineTemplate()); } private BigDecimal budget = BigDecimal.ZERO.setScale(2); protected <T extends OrderElement> T setupElementParts(T orderElement) { super.setupElementParts(orderElement); setupHoursGroups((OrderLine) orderElement); return orderElement; } private void setupHoursGroups(OrderLine orderLine) { Set<HoursGroup> result = new HashSet<HoursGroup>(); for (HoursGroup each: getHoursGroups()) { result.add(HoursGroup.copyFrom(each, orderLine)); } orderLine.setHoursGroups(result); } @Override public List<OrderElementTemplate> getChildrenTemplates() { return Collections.emptyList(); } @Override public OrderElementTemplate toLeaf() { return this; } @Override public OrderLineGroupTemplate toContainer() { OrderLineGroupTemplate result = OrderLineGroupTemplate.createNew(); copyTo(result); return result; } @Override public List<OrderElementTemplate> getChildren() { return new ArrayList<OrderElementTemplate>(); } @Override public boolean isLeaf() { return true; } @Override public OrderElement createElement(OrderLineGroup parent) { OrderLine line = setupSchedulingStateType(setupVersioningInfo(parent, OrderLine.createOrderLineWithUnfixedPercentage(getWorkHours()))); line.initializeTemplate(this); parent.add(line); return setupElementParts(line); } @Override public String getType() { return _("Line"); } public Integer getWorkHours() { return hoursGroupOrderLineTemplateHandler.calculateTotalHours(hoursGroups); } public void incrementLastHoursGroupSequenceCode() { if(lastHoursGroupSequenceCode==null){ lastHoursGroupSequenceCode = 0; } lastHoursGroupSequenceCode++; } @NotNull(message = "last hours group sequence code not specified") public Integer getLastHoursGroupSequenceCode() { return lastHoursGroupSequenceCode; } /** * Operations for manipulating {@link HoursGroup} */ @Override public List<HoursGroup> getHoursGroups() { return new ArrayList<HoursGroup>(hoursGroups); } public Set<HoursGroup> myHoursGroups() { return hoursGroups; } public void setHoursGroups(final Set<HoursGroup> hoursGroups) { this.hoursGroups.clear(); this.hoursGroups.addAll(hoursGroups); } public void addHoursGroup(HoursGroup hoursGroup) { hoursGroup.setOrderLineTemplate(this); hoursGroup.updateMyCriterionRequirements(); doAddHoursGroup(hoursGroup); recalculateHoursGroups(); } public void doAddHoursGroup(HoursGroup hoursGroup) { hoursGroups.add(hoursGroup); } public void deleteHoursGroup(HoursGroup hoursGroup) { hoursGroups.remove(hoursGroup); recalculateHoursGroups(); } private HoursGroupOrderLineTemplateHandler hoursGroupOrderLineTemplateHandler = HoursGroupOrderLineTemplateHandler .getInstance(); public void setWorkHours(Integer workHours) throws IllegalArgumentException { hoursGroupOrderLineTemplateHandler.setWorkHours(this, workHours); } public boolean isTotalHoursValid(Integer total) { return hoursGroupOrderLineTemplateHandler.isTotalHoursValid(total, hoursGroups); } public boolean isPercentageValid() { return hoursGroupOrderLineTemplateHandler.isPercentageValid(hoursGroups); } public void recalculateHoursGroups() { hoursGroupOrderLineTemplateHandler.recalculateHoursGroups(this); } public void setBudget(BigDecimal budget) { Validate.isTrue(budget.compareTo(BigDecimal.ZERO) >= 0, "budget cannot be negative"); this.budget = budget.setScale(2); } @Override @NotNull(message = "budget not specified") public BigDecimal getBudget() { return budget; } }
Use budget field when creating a template from a task or vice versa FEA: ItEr76S17MoneyCostMonitoringSystem
libreplan-business/src/main/java/org/libreplan/business/templates/entities/OrderLineTemplate.java
Use budget field when creating a template from a task or vice versa
Java
agpl-3.0
a1c65e3e001fd23cdc85ecfe96ceed7d25478e58
0
CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine
package com.splicemachine.derby.impl.sql.execute; import com.splicemachine.derby.impl.sql.execute.serial.StringSerializer; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.types.*; import javax.swing.*; public class LazyDataValueFactory extends J2SEDataValueFactory{ @Override public StringDataValue getVarcharDataValue(String value) { return new LazyStringDataValueDescriptor(new SQLVarchar(value), new StringSerializer()); } @Override public StringDataValue getVarcharDataValue(String value, StringDataValue previous) throws StandardException { StringDataValue result; if(previous instanceof LazyStringDataValueDescriptor){ previous.setValue(value); result = previous; }else{ if(previous != null){ previous.setValue(value); result = new LazyStringDataValueDescriptor(previous, new StringSerializer()); }else{ result = new LazyStringDataValueDescriptor(new SQLVarchar(value), new StringSerializer()); } } return result; } @Override public StringDataValue getVarcharDataValue(String value, StringDataValue previous, int collationType) throws StandardException { return getVarcharDataValue(value, previous); } public DataValueDescriptor getNull(int formatId, int collationType) throws StandardException { switch (formatId) { /* Wrappers */ case StoredFormatIds.SQL_BIT_ID: return new SQLBit(); case StoredFormatIds.SQL_BOOLEAN_ID: return new SQLBoolean(); case StoredFormatIds.SQL_CHAR_ID: return new LazyStringDataValueDescriptor(new SQLChar(), new StringSerializer()); case StoredFormatIds.SQL_DATE_ID: return new SQLDate(); case StoredFormatIds.SQL_DOUBLE_ID: return new SQLDouble(); case StoredFormatIds.SQL_INTEGER_ID: return new SQLInteger(); case StoredFormatIds.SQL_LONGINT_ID: return new SQLLongint(); case StoredFormatIds.SQL_REAL_ID: return new SQLReal(); case StoredFormatIds.SQL_REF_ID: return new SQLRef(); case StoredFormatIds.SQL_SMALLINT_ID: return new SQLSmallint(); case StoredFormatIds.SQL_TIME_ID: return new SQLTime(); case StoredFormatIds.SQL_TIMESTAMP_ID: return new SQLTimestamp(); case StoredFormatIds.SQL_TINYINT_ID: return new SQLTinyint(); case StoredFormatIds.SQL_VARCHAR_ID: return new LazyStringDataValueDescriptor(new SQLVarchar(), new StringSerializer()); case StoredFormatIds.SQL_LONGVARCHAR_ID: return new LazyStringDataValueDescriptor(new SQLLongvarchar(), new StringSerializer()); case StoredFormatIds.SQL_VARBIT_ID: return new SQLVarbit(); case StoredFormatIds.SQL_LONGVARBIT_ID: return new SQLLongVarbit(); case StoredFormatIds.SQL_USERTYPE_ID_V3: return new UserType(); case StoredFormatIds.SQL_BLOB_ID: return new SQLBlob(); case StoredFormatIds.SQL_CLOB_ID: return new LazyStringDataValueDescriptor(new SQLClob(), new StringSerializer()); case StoredFormatIds.XML_ID: return new LazyDataValueDescriptor(new XML(), new StringSerializer()); default:return null; } } }
structured_derby/src/main/java/com/splicemachine/derby/impl/sql/execute/LazyDataValueFactory.java
package com.splicemachine.derby.impl.sql.execute; import com.splicemachine.derby.impl.sql.execute.serial.StringSerializer; import org.apache.derby.iapi.error.StandardException; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.types.*; import javax.swing.*; public class LazyDataValueFactory extends J2SEDataValueFactory{ @Override public StringDataValue getVarcharDataValue(String value) { return new LazyStringDataValueDescriptor(new SQLVarchar(), new StringSerializer()); } @Override public StringDataValue getVarcharDataValue(String value, StringDataValue previous) throws StandardException { StringDataValue result; if(previous instanceof LazyStringDataValueDescriptor){ previous.setValue(value); result = previous; }else{ if(previous != null){ previous.setValue(value); result = new LazyStringDataValueDescriptor(previous, new StringSerializer()); }else{ SQLVarchar newDvd = new SQLVarchar(); newDvd.setValue(value); result = new LazyStringDataValueDescriptor(newDvd, new StringSerializer()); } } return result; } @Override public StringDataValue getVarcharDataValue(String value, StringDataValue previous, int collationType) throws StandardException { return getVarcharDataValue(value, previous); } public DataValueDescriptor getNull(int formatId, int collationType) throws StandardException { switch (formatId) { /* Wrappers */ case StoredFormatIds.SQL_BIT_ID: return new SQLBit(); case StoredFormatIds.SQL_BOOLEAN_ID: return new SQLBoolean(); case StoredFormatIds.SQL_CHAR_ID: return new LazyStringDataValueDescriptor(new SQLChar(), new StringSerializer()); case StoredFormatIds.SQL_DATE_ID: return new SQLDate(); case StoredFormatIds.SQL_DOUBLE_ID: return new SQLDouble(); case StoredFormatIds.SQL_INTEGER_ID: return new SQLInteger(); case StoredFormatIds.SQL_LONGINT_ID: return new SQLLongint(); case StoredFormatIds.SQL_REAL_ID: return new SQLReal(); case StoredFormatIds.SQL_REF_ID: return new SQLRef(); case StoredFormatIds.SQL_SMALLINT_ID: return new SQLSmallint(); case StoredFormatIds.SQL_TIME_ID: return new SQLTime(); case StoredFormatIds.SQL_TIMESTAMP_ID: return new SQLTimestamp(); case StoredFormatIds.SQL_TINYINT_ID: return new SQLTinyint(); case StoredFormatIds.SQL_VARCHAR_ID: return new LazyStringDataValueDescriptor(new SQLVarchar(), new StringSerializer()); case StoredFormatIds.SQL_LONGVARCHAR_ID: return new LazyStringDataValueDescriptor(new SQLLongvarchar(), new StringSerializer()); case StoredFormatIds.SQL_VARBIT_ID: return new SQLVarbit(); case StoredFormatIds.SQL_LONGVARBIT_ID: return new SQLLongVarbit(); case StoredFormatIds.SQL_USERTYPE_ID_V3: return new UserType(); case StoredFormatIds.SQL_BLOB_ID: return new SQLBlob(); case StoredFormatIds.SQL_CLOB_ID: return new LazyStringDataValueDescriptor(new SQLClob(), new StringSerializer()); case StoredFormatIds.XML_ID: return new LazyDataValueDescriptor(new XML(), new StringSerializer()); default:return null; } } }
forgot to add the value to the SQLVarchar in the DataValueFactory. Doh! Fixes 4 test failures
structured_derby/src/main/java/com/splicemachine/derby/impl/sql/execute/LazyDataValueFactory.java
forgot to add the value to the SQLVarchar in the DataValueFactory. Doh! Fixes 4 test failures
Java
agpl-3.0
9d8dc2642bba0d5190281a4c981e4ec59cda37a4
0
ufosky-server/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,actorapp/actor-platform,actorapp/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,actorapp/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.runtime.android; import java.io.File; import java.util.Random; import im.actor.runtime.FileSystemRuntime; import im.actor.runtime.android.files.AndroidFileSystemReference; import im.actor.runtime.files.FileSystemReference; public class AndroidFileSystemProvider implements FileSystemRuntime { public static final String FILE_SYSTEM_SAFE_RENAME = "\\W+"; private Random random = new Random(); private boolean isFirst = true; private void clearTempDir() { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); if (dest.exists()) { for (File file : dest.listFiles()) file.delete(); } } private void checkTempDirs() { if (isFirst) { isFirst = false; clearTempDir(); } } private String buildTempFile() { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); dest.mkdirs(); return new File(dest, "temp_" + random.nextLong()).getAbsolutePath(); } private String buildResultFile(long fileId, String fileName) { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/files/"); dest.mkdirs(); String baseFileName = fileName; if (fileName.contains(".")) { String prefix = baseFileName.substring(0, baseFileName.lastIndexOf('.')).replaceAll(FILE_SYSTEM_SAFE_RENAME, ""); String ext = baseFileName.substring(prefix.length() + 1); File res = new File(dest, prefix + "_" + fileId + "." + ext); int index = 0; while (res.exists()) { res = new File(dest, prefix + "_" + fileId + "_" + index + "." + ext); index++; } return res.getAbsolutePath(); } else { File res = new File(dest, baseFileName + "_" + fileId); int index = 0; while (res.exists()) { res = new File(dest, baseFileName + "_" + fileId + "_" + index); index++; } return res.getAbsolutePath(); } } @Override public synchronized FileSystemReference createTempFile() { checkTempDirs(); String destFile = buildTempFile(); if (destFile == null) { return null; } return new AndroidFileSystemReference(destFile); } @Override public FileSystemReference commitTempFile(FileSystemReference sourceFile, long fileId, String fileName) { String realFileName = buildResultFile(fileId, fileName); if (realFileName == null) { return null; } if (!new File(sourceFile.getDescriptor()).renameTo(new File(realFileName))) { return null; } AndroidFileSystemReference androidFileSystemReference = new AndroidFileSystemReference(realFileName); return androidFileSystemReference; } @Override public boolean isFsPersistent() { return true; } @Override public synchronized FileSystemReference fileFromDescriptor(String descriptor) { checkTempDirs(); return new AndroidFileSystemReference(descriptor); } }
actor-sdk/sdk-core/runtime/runtime-android/src/main/java/im/actor/runtime/android/AndroidFileSystemProvider.java
/* * Copyright (C) 2015 Actor LLC. <https://actor.im> */ package im.actor.runtime.android; import java.io.File; import java.util.Random; import im.actor.runtime.FileSystemRuntime; import im.actor.runtime.android.files.AndroidFileSystemReference; import im.actor.runtime.files.FileSystemReference; public class AndroidFileSystemProvider implements FileSystemRuntime { private Random random = new Random(); private boolean isFirst = true; private void clearTempDir() { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); if (dest.exists()) { for (File file : dest.listFiles()) file.delete(); } } private void checkTempDirs() { if (isFirst) { isFirst = false; clearTempDir(); } } private String buildTempFile() { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/tmp/"); dest.mkdirs(); return new File(dest, "temp_" + random.nextLong()).getAbsolutePath(); } private String buildResultFile(long fileId, String fileName) { File externalFile = AndroidContext.getContext().getExternalFilesDir(null); if (externalFile == null) { return null; } String externalPath = externalFile.getAbsolutePath(); File dest = new File(externalPath + "/actor/files/"); dest.mkdirs(); String baseFileName = fileName; if (fileName.contains(".")) { String prefix = baseFileName.substring(baseFileName.lastIndexOf('.')); String ext = baseFileName.substring(prefix.length() + 1); File res = new File(dest, prefix + "_" + fileId + "." + ext); int index = 0; while (res.exists()) { res = new File(dest, prefix + "_" + fileId + "_" + index + "." + ext); index++; } return res.getAbsolutePath(); } else { File res = new File(dest, baseFileName + "_" + fileId); int index = 0; while (res.exists()) { res = new File(dest, baseFileName + "_" + fileId + "_" + index); index++; } return res.getAbsolutePath(); } } @Override public synchronized FileSystemReference createTempFile() { checkTempDirs(); String destFile = buildTempFile(); if (destFile == null) { return null; } return new AndroidFileSystemReference(destFile); } @Override public FileSystemReference commitTempFile(FileSystemReference sourceFile, long fileId, String fileName) { String realFileName = buildResultFile(fileId, fileName); if (realFileName == null) { return null; } if (!new File(sourceFile.getDescriptor()).renameTo(new File(realFileName))) { return null; } return new AndroidFileSystemReference(realFileName); } @Override public boolean isFsPersistent() { return true; } @Override public synchronized FileSystemReference fileFromDescriptor(String descriptor) { checkTempDirs(); return new AndroidFileSystemReference(descriptor); } }
fix(android): sanitize downloaded file names
actor-sdk/sdk-core/runtime/runtime-android/src/main/java/im/actor/runtime/android/AndroidFileSystemProvider.java
fix(android): sanitize downloaded file names
Java
lgpl-2.1
f568758dce8f6fd26c22727f21d99234ca167d6f
0
standpoint/poulpe,standpoint/poulpe,jtalks-org/poulpe,jtalks-org/poulpe
/** * Copyright (C) 2011 JTalks.org Team * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.poulpe.web.controller.users; import com.google.common.annotations.VisibleForTesting; import org.jtalks.poulpe.model.entity.PoulpeUser; import org.jtalks.poulpe.service.UserService; import org.jtalks.poulpe.web.controller.ZkHelper; import org.zkoss.bind.annotation.*; import org.zkoss.zk.ui.Component; import org.zkoss.zkplus.databind.BindingListModelList; import org.zkoss.zul.ListModelList; import javax.annotation.Nonnull; /** * ViewModel for users page. * * @author dim42 */ public class UsersVm { private static final String SELECTED_ITEM_PROP = "selectedUser", VIEW_DATA_PROP = "viewData"; public static final String EDIT_USER_URL = "/WEB-INF/pages/users/edit_user.zul"; public static final String EDIT_USER_DIALOG = "#editUserDialog"; private final UserService userService; private final ListModelList<PoulpeUser> users; private String searchString; private PoulpeUser selectedUser; private ZkHelper zkHelper; /** * @param userService the service to get access to users and to store changes to the database */ public UsersVm(@Nonnull UserService userService) { this.userService = userService; this.users = new BindingListModelList<PoulpeUser>(userService.getAll(), true); } /** * Wires users window to this ViewModel. * * @param component users window */ @Init public void init(@ContextParam(ContextType.VIEW) Component component) { zkHelper = new ZkHelper(component); zkHelper.wireComponents(component, this); } /** * Look for the users matching specified pattern from the search textbox. */ @Command public void searchUser() { users.clear(); users.addAll(userService.getUsersByUsernameWord(searchString)); } /** * Opens edit user dialog. * * @param user selected user */ @Command public void editUser(@BindingParam(value = "user") PoulpeUser user) { selectedUser = user; zkHelper.wireToZul(EDIT_USER_URL); } /** * Validates editing user, on success saves him, on failure shows the error message. * * @param user editing user */ @Command @NotifyChange({VIEW_DATA_PROP, SELECTED_ITEM_PROP}) public void saveUser(@BindingParam(value = "user") PoulpeUser user) { userService.updateUser(user); closeEditDialog(); } /** * Closes edit user dialog. */ @Command @NotifyChange({VIEW_DATA_PROP, SELECTED_ITEM_PROP}) public void cancelEdit() { closeEditDialog(); } private void closeEditDialog() { zkHelper.findComponent(EDIT_USER_DIALOG).detach(); users.clear(); users.addAll(userService.getAll()); } public ListModelList<PoulpeUser> getUsers() { users.clear(); users.addAll(userService.getAll()); return users; } /** * Sets the search keyword to find the users by it. Is used by ZK Binder. * * @param searchString search keyword to find the users by it */ public void setSearchString(String searchString) { this.searchString = searchString; } /** * Gets the user selected on the UI. * * @return the user selected on the UI */ public PoulpeUser getSelectedUser() { return selectedUser; } public void setSelectedUser(PoulpeUser selectedUser) { this.selectedUser = selectedUser; } @VisibleForTesting void setZkHelper(ZkHelper zkHelper) { this.zkHelper = zkHelper; } }
poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/users/UsersVm.java
/** * Copyright (C) 2011 JTalks.org Team * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.poulpe.web.controller.users; import com.google.common.annotations.VisibleForTesting; import org.jtalks.poulpe.model.entity.PoulpeUser; import org.jtalks.poulpe.service.UserService; import org.jtalks.poulpe.web.controller.ZkHelper; import org.zkoss.bind.annotation.*; import org.zkoss.zk.ui.Component; import org.zkoss.zkplus.databind.BindingListModelList; import org.zkoss.zul.ListModelList; import javax.annotation.Nonnull; /** * ViewModel for users page. * * @author dim42 */ public class UsersVm { public static final String EDIT_USER_URL = "/WEB-INF/pages/users/edit_user.zul"; public static final String EDIT_USER_DIALOG = "#editUserDialog"; private final UserService userService; private final ListModelList<PoulpeUser> users; private String searchString; private PoulpeUser selectedUser; private ZkHelper zkHelper; /** * @param userService the service to get access to users and to store changes to the database */ public UsersVm(@Nonnull UserService userService) { this.userService = userService; this.users = new BindingListModelList<PoulpeUser>(userService.getAll(), true); } /** * Wires users window to this ViewModel. * * @param component users window */ @Init public void init(@ContextParam(ContextType.VIEW) Component component) { zkHelper = new ZkHelper(component); zkHelper.wireComponents(component, this); } /** * Look for the users matching specified pattern from the search textbox. */ @Command public void searchUser() { users.clear(); users.addAll(userService.getUsersByUsernameWord(searchString)); } /** * Opens edit user dialog. * * @param user selected user */ @Command public void editUser(@BindingParam(value = "user") PoulpeUser user) { selectedUser = user; zkHelper.wireToZul(EDIT_USER_URL); } /** * Validates editing user, on success saves him, on failure shows the error message. * * @param user editing user */ @Command public void saveUser(@BindingParam(value = "user") PoulpeUser user) { userService.updateUser(user); closeEditDialog(); } /** * Closes edit user dialog. */ @Command public void cancelEdit() { closeEditDialog(); } private void closeEditDialog() { zkHelper.findComponent(EDIT_USER_DIALOG).detach(); } public ListModelList<PoulpeUser> getUsers() { users.clear(); users.addAll(userService.getAll()); return users; } /** * Sets the search keyword to find the users by it. Is used by ZK Binder. * * @param searchString search keyword to find the users by it */ public void setSearchString(String searchString) { this.searchString = searchString; } /** * Gets the user selected on the UI. * * @return the user selected on the UI */ public PoulpeUser getSelectedUser() { return selectedUser; } public void setSelectedUser(PoulpeUser selectedUser) { this.selectedUser = selectedUser; } @VisibleForTesting void setZkHelper(ZkHelper zkHelper) { this.zkHelper = zkHelper; } }
#POULPE-272 Validation has been added to the events of the buttons
poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/users/UsersVm.java
#POULPE-272 Validation has been added to the events of the buttons
Java
apache-2.0
41ec6dcd43685e0cf6f452b4bf58362271c72302
0
philliprower/cas,leleuj/cas,apereo/cas,apereo/cas,philliprower/cas,philliprower/cas,leleuj/cas,Jasig/cas,leleuj/cas,leleuj/cas,philliprower/cas,apereo/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,pdrados/cas,rkorn86/cas,pdrados/cas,apereo/cas,Jasig/cas,philliprower/cas,leleuj/cas,pdrados/cas,rkorn86/cas,pdrados/cas,rkorn86/cas,Jasig/cas,pdrados/cas,apereo/cas,rkorn86/cas,apereo/cas,apereo/cas,leleuj/cas,Jasig/cas,pdrados/cas,fogbeam/cas_mirror,philliprower/cas,fogbeam/cas_mirror,fogbeam/cas_mirror,fogbeam/cas_mirror
/* * 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: * * 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.jasig.cas.support.saml.util; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.Status; import org.opensaml.saml2.core.StatusCode; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import java.lang.reflect.Field; /** * This is {@link org.jasig.cas.support.saml.util.GoogleSaml20ObjectBuilder} that * attempts to build the saml response QName based on the spec described here: * https://developers.google.com/google-apps/sso/saml_reference_implementation_web#samlReferenceImplementationWebSetupChangeDomain * @author Misagh Moayyed [email protected] */ public class GoogleSaml20ObjectBuilder extends Saml20ObjectBuilder { @Override public final QName getSamlObjectQName(final Class objectType) throws RuntimeException { try { final Field f = objectType.getField(DEFAULT_ELEMENT_LOCAL_NAME_FIELD); final String name = f.get(null).toString(); if (objectType.equals(Response.class) || objectType.equals(Status.class) || objectType.equals(StatusCode.class)) { return new QName(SAMLConstants.SAML20P_NS, name, "samlp"); } return new QName(SAMLConstants.SAML20_NS, name, XMLConstants.DEFAULT_NS_PREFIX); } catch (final Exception e){ throw new IllegalStateException("Cannot access field " + objectType.getName() + "." + DEFAULT_ELEMENT_LOCAL_NAME_FIELD); } } }
cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/GoogleSaml20ObjectBuilder.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: * * 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.jasig.cas.support.saml.util; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.Status; import org.opensaml.saml2.core.StatusCode; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import java.lang.reflect.Field; /** * This is {@link org.jasig.cas.support.saml.util.GoogleSaml20ObjectBuilder}. * Attempts to build the saml response QName based on the spec described here: * https://developers.google.com/google-apps/sso/saml_reference_implementation_web#samlReferenceImplementationWebSetupChangeDomain * @author Misagh Moayyed [email protected] */ public class GoogleSaml20ObjectBuilder extends Saml20ObjectBuilder { @Override public final QName getSamlObjectQName(final Class objectType) throws RuntimeException { try { final Field f = objectType.getField(DEFAULT_ELEMENT_LOCAL_NAME_FIELD); final String name = f.get(null).toString(); if (objectType.equals(Response.class) || objectType.equals(Status.class) || objectType.equals(StatusCode.class)) { return new QName(SAMLConstants.SAML20P_NS, name, "samlp"); } return new QName(SAMLConstants.SAML20_NS, name, XMLConstants.DEFAULT_NS_PREFIX); } catch (final Exception e){ throw new IllegalStateException("Cannot access field " + objectType.getName() + "." + DEFAULT_ELEMENT_LOCAL_NAME_FIELD); } } }
Fixed javadocs
cas-server-support-saml/src/main/java/org/jasig/cas/support/saml/util/GoogleSaml20ObjectBuilder.java
Fixed javadocs
Java
apache-2.0
4990cb043b7b417a334919224c0ecaf4e960fc84
0
nmcalabroso/appinventor-sources,mit-cml/appinventor-sources,doburaimo/appinventor-sources,mit-cml/appinventor-sources,krishc90/APP-INVENTOR,kpjs4s/AppInventorJavaBridgeCodeGen,jisqyv/appinventor-sources,marksherman/appinventor-sources,cjessica/aifoo,fmntf/appinventor-sources,anseo/friedgerAI24BLE,weihuali0509/web-appinventor,weihuali0509/appinventor-sources,halatmit/appinventor-sources,wadleo/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,GodUseVPN/appinventor-sources,joshaham/latest_app_inventor,kannan-usf/AppInventorJavaBridge,AlanRosenthal/appinventor-sources,wanddy/appinventor-sources,ajcolter/appinventor-sources,Momoumar/appinventor-sources,bxie/appinventor-sources,tvomf/appinventor-mapps,spefley/appinventor-sources,hasi96/appinventor-sources,tiffanyle/appinventor-sources,jcweaver/appinventorTutorial,Momoumar/appinventor-sources,GodUseVPN/appinventor-sources,nickboucart/appinventor-sources,nwtel/appinventor-sources,shilpamagrawal15/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,gitars/appinventor-sources,thilankam/appinventor-sources,Klomi/appinventor-sources,puravidaapps/appinventor-sources,fturbak/appinventor-sources,halatmit/appinventor-sources,barreeeiroo/appinventor-sources,youprofit/appinventor-sources,weihuali0509/web-appinventor,mit-dig/punya,ZachLamb/appinventor-sources,William-Byrne/appinventor-sources,mit-cml/appinventor-sources,fmntf/appinventor-sources,wanddy/appinventor-sources,ewpatton/appinventor-sources,wanddy/ai4cn,wadleo/appinventor-sources,ZachLamb/appinventor-sources,wadleo/appinventor-sources,mit-dig/punya,CoderDojoLX/appinventor-sources,dengxinyue0420/appinventor-sources,marksherman/appinventor-sources,mintingle/appinventor-sources,nickboucart/appinventor-sources,ewpatton/appinventor-sources,aouskaroui/appinventor-sources,JalexChang/appinventor-sources,graceRyu/appinventor-sources,rkipper/AppInventor_RK,gitars/appinventor-sources,DRavnaas/appinventor-clone,emeryotopalik/appinventor-sources,josmas/app-inventor,wanddy/appinventor-sources,barreeeiroo/appinventor-sources,jsheldonmit/appinventor-sources,tiffanyle/appinventor-sources,egiurleo/appinventor-sources,mit-dig/punya,kidebit/https-github.com-wicedfast-appinventor-sources,weihuali0509/appinventor-sources,kidebit/AudioBlurp,ajhalbleib/aicg,FIRST-Tech-Challenge/appinventor-sources,liyucun/appinventor-sources,weihuali0509/web-appinventor,mintingle/appinventor-sources,satgod/appinventor,fturbak/appinventor-sources,ZachLamb/appinventor-sources,toropeza/appinventor-sources,Momoumar/appinventor-sources,CoderDojoLX/appinventor-sources,egiurleo/appinventor-sources,joshaham/latest_app_inventor,thequixotic/appinventor-sources,aouskaroui/appinventor-sources,doburaimo/appinventor-sources,wanddy/ai4all2,puravidaapps/appinventor-sources,Mateopato/appinventor-sources,wanddy/ai4all2,kidebit/AudioBlurp,youprofit/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,awoodworth/appinventor-sources,hasi96/appinventor-sources,Edeleon4/punya,graceRyu/appinventor-sources,mintingle/appinventor-sources,jsheldonmit/appinventor-sources,Mateopato/appinventor-sources,fturbak/appinventor-sources,wanddy/appinventor-sources,spefley/appinventor-sources,Klomi/appinventor-sources,themadrobot/appinventor-sources,Klomi/appinventor-sources,doburaimo/appinventor-sources,dengxinyue0420/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,DRavnaas/appinventor-clone,bitsecure/appinventor1-sources,themadrobot/appinventor-sources,aouskaroui/appinventor-sources,marksherman/appinventor-sources,josmas/app-inventor,fmntf/appinventor-sources,halatmit/appinventor-sources,themadrobot/appinventor-sources,GodUseVPN/appinventor-sources,JalexChang/appinventor-sources,dengxinyue0420/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,afmckinney/appinventor-sources,mit-dig/punya,CoderDojoLX/appinventor-sources,yflou520/appinventor-sources,Klomi/appinventor-sources,wanddy/ai4cn,sujianping/appinventor-sources,nmcalabroso/appinventor-sources,tatuzaumm/app-inventor2-custom,jcweaver/appinventorTutorial,jcweaver/appinventorTutorial,themadrobot/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,frfranca/appinventor-sources,kkashi01/appinventor-sources,bitsecure/appinventor1-sources,fturbak/appinventor-sources,AlanRosenthal/appinventor-sources,dengxinyue0420/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,josmas/app-inventor,weihuali0509/appinventor-sources,puravidaapps/appinventor-sources,jsheldonmit/appinventor-sources,cjessica/aifoo,frfranca/appinventor-sources,wanddy/ai4cn,emeryotopalik/appinventor-sources,William-Byrne/appinventor-sources,ZachLamb/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,spefley/appinventor-sources,AlanRosenthal/appinventor-sources,kannan-usf/AppInventorJavaBridge,wadleo/appinventor-sources,yflou520/appinventor-sources,nwtel/appinventor-sources,GodUseVPN/appinventor-sources,kkashi01/appinventor-sources,mit-dig/punya,RachaelT/appinventor-sources,E-Hon/appinventor-sources,barreeeiroo/appinventor-sources,onyeka/AppInventor-WebApp,mintingle/appinventor-sources,RachaelT/appinventor-sources,wanddy/ai4all2,DRavnaas/appinventor-clone,ram8647/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,ewpatton/appinventor-sources,KeithGalli/appinventor-sources,KeithGalli/appinventor-sources,KeithGalli/appinventor-sources,jsheldonmit/appinventor-sources,mark-friedman/web-appinventor,DRavnaas/appinventor-clone,emeryotopalik/appinventor-sources,jithinbp/appinventor-sources,ajhalbleib/aicg,LaboratoryForPlayfulComputation/appinventor-sources,krishc90/APP-INVENTOR,lizlooney/appinventor-sources,Edeleon4/punya,ajhalbleib/aicg,nwtel/appinventor-sources,thequixotic/appinventor-sources,rkipper/AppInventor_RK,afmckinney/appinventor-sources,afmckinney/appinventor-sources,E-Hon/appinventor-sources,wanddy/appinventor-sources,bxie/appinventor-sources,tiffanyle/appinventor-sources,jisqyv/appinventor-sources,tiffanyle/appinventor-sources,afmckinney/appinventor-sources,ajcolter/appinventor-sources,lizlooney/appinventor-sources,wicedfast/appinventor-sources,fturbak/appinventor-sources,ZachLamb/appinventor-sources,jsheldonmit/appinventor-sources,jisqyv/appinventor-sources,ram8647/appinventor-sources,weihuali0509/appinventor-sources,halatmit/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,rkipper/AppInventor_RK,mit-cml/appinventor-sources,aouskaroui/appinventor-sources,bitsecure/appinventor1-sources,ewpatton/appinventor-sources,ewpatton/appinventor-sources,tatuzaumm/app-inventor2-custom,wanddy/ai4all2,mit-dig/punya,onyeka/AppInventor-WebApp,warren922/appinventor-sources,liyucun/appinventor-sources,shilpamagrawal15/appinventor-sources,Momoumar/appinventor-sources,graceRyu/appinventor-sources,sujianping/appinventor-sources,rkipper/AppInventor_RK,themadrobot/appinventor-sources,satgod/appinventor,Mateopato/appinventor-sources,thequixotic/appinventor-sources,mit-dig/punya,hasi96/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,JalexChang/appinventor-sources,fmntf/appinventor-sources,awoodworth/appinventor-sources,William-Byrne/appinventor-sources,sujianping/appinventor-sources,farxinu/appinventor-sources,GodUseVPN/appinventor-sources,ajcolter/appinventor-sources,wanddy/ai4cn,frfranca/appinventor-sources,tatuzaumm/app-inventor2-custom,puravidaapps/appinventor-sources,marksherman/appinventor-sources,awoodworth/appinventor-sources,kidebit/AudioBlurp,farxinu/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,KeithGalli/appinventor-sources,shilpamagrawal15/appinventor-sources,mark-friedman/web-appinventor,shilpamagrawal15/appinventor-sources,halatmit/appinventor-sources,anseo/friedgerAI24BLE,nwtel/appinventor-sources,jcweaver/appinventorTutorial,LaboratoryForPlayfulComputation/appinventor-sources,nmcalabroso/appinventor-sources,weihuali0509/web-appinventor,toropeza/appinventor-sources,Edeleon4/punya,josmas/app-inventor,RachaelT/appinventor-sources,kkashi01/appinventor-sources,satgod/appinventor,jisqyv/appinventor-sources,awoodworth/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,lizlooney/appinventor-sources,mintingle/appinventor-sources,mit-cml/appinventor-sources,jithinbp/appinventor-sources,nmcalabroso/appinventor-sources,CoderDojoLX/appinventor-sources,josmas/app-inventor,CoderDojoLX/appinventor-sources,egiurleo/appinventor-sources,satgod/appinventor,marksherman/appinventor-sources,fmntf/appinventor-sources,dengxinyue0420/appinventor-sources,aouskaroui/appinventor-sources,ajcolter/appinventor-sources,tvomf/appinventor-mapps,ewpatton/appinventor-sources,youprofit/appinventor-sources,kannan-usf/AppInventorJavaBridge,frfranca/appinventor-sources,RachaelT/appinventor-sources,JalexChang/appinventor-sources,ram8647/appinventor-sources,shilpamagrawal15/appinventor-sources,mark-friedman/web-appinventor,weihuali0509/appinventor-sources,tatuzaumm/app-inventor2-custom,tvomf/appinventor-mapps,jisqyv/appinventor-sources,liyucun/appinventor-sources,bxie/appinventor-sources,puravidaapps/appinventor-sources,josmas/app-inventor,kannan-usf/AppInventorJavaBridge,krishc90/APP-INVENTOR,jisqyv/appinventor-sources,thequixotic/appinventor-sources,satgod/appinventor,emeryotopalik/appinventor-sources,lizlooney/appinventor-sources,tvomf/appinventor-mapps,gitars/appinventor-sources,onyeka/AppInventor-WebApp,wicedfast/appinventor-sources,marksherman/appinventor-sources,tiffanyle/appinventor-sources,jcweaver/appinventorTutorial,toropeza/appinventor-sources,anseo/friedgerAI24BLE,E-Hon/appinventor-sources,egiurleo/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,frfranca/appinventor-sources,kkashi01/appinventor-sources,Mateopato/appinventor-sources,lizlooney/appinventor-sources,AlanRosenthal/appinventor-sources,thilankam/appinventor-sources,cjessica/aifoo,mit-cml/appinventor-sources,JalexChang/appinventor-sources,toropeza/appinventor-sources,anseo/friedgerAI24BLE,wicedfast/appinventor-sources,farxinu/appinventor-sources,wicedfast/appinventor-sources,onyeka/AppInventor-WebApp,wicedfast/appinventor-sources,KeithGalli/appinventor-sources,egiurleo/appinventor-sources,nmcalabroso/appinventor-sources,yflou520/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,ajcolter/appinventor-sources,awoodworth/appinventor-sources,Edeleon4/punya,Klomi/appinventor-sources,spefley/appinventor-sources,Mateopato/appinventor-sources,joshaham/latest_app_inventor,youprofit/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,wanddy/ai4all2,doburaimo/appinventor-sources,mark-friedman/web-appinventor,liyucun/appinventor-sources,Momoumar/appinventor-sources,barreeeiroo/appinventor-sources,joshaham/latest_app_inventor,jithinbp/appinventor-sources,kkashi01/appinventor-sources,warren922/appinventor-sources,tvomf/appinventor-mapps,thequixotic/appinventor-sources,kidebit/AudioBlurp,halatmit/appinventor-sources,E-Hon/appinventor-sources,bxie/appinventor-sources,Edeleon4/punya,AlanRosenthal/appinventor-sources,mintingle/appinventor-sources,spefley/appinventor-sources,toropeza/appinventor-sources,shilpamagrawal15/appinventor-sources,E-Hon/appinventor-sources,thilankam/appinventor-sources,DRavnaas/appinventor-clone,nickboucart/appinventor-sources,warren922/appinventor-sources,warren922/appinventor-sources,gitars/appinventor-sources,youprofit/appinventor-sources,William-Byrne/appinventor-sources,RachaelT/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,krishc90/APP-INVENTOR,kannan-usf/AppInventorJavaBridge,doburaimo/appinventor-sources,krishc90/APP-INVENTOR,bitsecure/appinventor1-sources,nickboucart/appinventor-sources,Edeleon4/punya,thilankam/appinventor-sources,gitars/appinventor-sources,warren922/appinventor-sources,William-Byrne/appinventor-sources,farxinu/appinventor-sources,emeryotopalik/appinventor-sources,nickboucart/appinventor-sources,wanddy/ai4cn,yflou520/appinventor-sources,liyucun/appinventor-sources,kkashi01/appinventor-sources,farxinu/appinventor-sources,graceRyu/appinventor-sources,cjessica/aifoo,graceRyu/appinventor-sources,bitsecure/appinventor1-sources,jithinbp/appinventor-sources,barreeeiroo/appinventor-sources,afmckinney/appinventor-sources,joshaham/latest_app_inventor,wadleo/appinventor-sources,bxie/appinventor-sources,ram8647/appinventor-sources,hasi96/appinventor-sources,yflou520/appinventor-sources,sujianping/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,onyeka/AppInventor-WebApp,cs6510/CS6510-LiveEdit-Onyeka,tatuzaumm/app-inventor2-custom,thilankam/appinventor-sources,nwtel/appinventor-sources,mark-friedman/web-appinventor,weihuali0509/web-appinventor,ram8647/appinventor-sources,jithinbp/appinventor-sources,hasi96/appinventor-sources,sujianping/appinventor-sources
// Copyright 2008 Google Inc. All Rights Reserved. package com.google.appinventor.server; import static com.google.appinventor.shared.rpc.project.youngandroid.NewYoungAndroidProjectParameters.YOUNG_ANDROID_FORM_NAME; import static org.easymock.EasyMock.expect; import com.google.appinventor.common.testutils.TestUtils; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.server.encryption.KeyczarEncryptor; import com.google.appinventor.server.storage.StorageIo; import com.google.appinventor.server.storage.StorageIoInstanceHolder; import com.google.appinventor.shared.rpc.project.FileDescriptor; import com.google.appinventor.shared.rpc.project.FileDescriptorWithContent; import com.google.appinventor.shared.rpc.project.ProjectNode; import com.google.appinventor.shared.rpc.project.ProjectRootNode; import com.google.appinventor.shared.rpc.project.UserProject; import com.google.appinventor.shared.rpc.project.youngandroid.NewYoungAndroidProjectParameters; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.appinventor.shared.storage.StorageUtil; import com.google.appinventor.shared.youngandroid.YoungAndroidSourceAnalyzer; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import static junit.framework.Assert.*; import junitx.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * Tests for {@link ProjectServiceImpl}. * */ @PowerMockIgnore({"javax.crypto.*" }) @RunWith(PowerMockRunner.class) @PrepareForTest({ LocalUser.class }) public class ProjectServiceTest { // If ProjectServiceTest (which uses PowerMock.mockStatic) extends LocalDatastoreTestCase, then // it will fail with Ant version 1.8.2. private final LocalDatastoreTestCase helper = LocalDatastoreTestCase.createHelper(); private static final String USER_ID_ONE = "id1"; private static final String USER_ID_TWO = "id2"; private static final String USER_EMAIL_ONE = "[email protected]"; private static final String USER_EMAIL_TWO = "[email protected]"; private static final String PROJECT1_NAME = "Project1"; private static final String PROJECT2_NAME = "Project2"; private static final String PROJECT3_NAME = "Project3"; private static final String PACKAGE_BASE = "com.domain.noname."; private static final String YOUNG_ANDROID_COMMENT = ";;; Cat In The Hat by Dr. Seuss\n"; private static final String YOUNG_ANDROID_COMMENT1 = ";;; Don't Hop on Pop by Dr. Seuss\n"; private static final String YOUNG_ANDROID_COMMENT2 = ";;; Green Eggs and Ham by Dr. Seuss\n"; private static final int NUMBER_OF_SIMULTANEOUS_NEW_PROJECTS = 50; private static final String YOUNG_ANDROID_PROJECT_SCM_SOURCE = "\n" + "#|\n" + "$JSON\n" + "{\"Source\":\"Form\",\"Properties\":{\"$Name\":\"Screen1\",\"$Type\":\"Form\"," + "\"Uuid\":\"0\",\"Title\":\"Screen1\",\"$Components\":[" + "{\"$Name\":\"Button1\",\"$Type\":\"Button\",\"Uuid\":\"123\",\"Text\":\"Button1\"," + "\"Width\":\"80\"}," + "{\"$Name\":\"Label1\",\"$Type\":\"Label\",\"Uuid\":\"-456\",\"Text\":\"Liz\"}" + "]}}\n" + "|#"; private StorageIo storageIo; private ProjectServiceImpl projectServiceImpl; // for USER_ID_ONE private ProjectServiceImpl projectServiceImpl2; // for USER_ID_TWO private Map<String, ProjectServiceImpl> projectServiceImpls; private LocalUser localUserMock; public static final String KEYSTORE_ROOT_PATH = TestUtils.APP_INVENTOR_ROOT_DIR + "/appengine/build/war/"; // must end with a slash @Before public void setUp() throws Exception { helper.setUp(); storageIo = StorageIoInstanceHolder.INSTANCE; PowerMock.mockStatic(LocalUser.class); localUserMock = PowerMock.createMock(LocalUser.class); expect(LocalUser.getInstance()).andReturn(localUserMock).anyTimes(); KeyczarEncryptor.rootPath.setForTest(KEYSTORE_ROOT_PATH); } void do_init() { storageIo.getUser(USER_ID_ONE, USER_EMAIL_ONE); projectServiceImpl = new ProjectServiceImpl(); storageIo.getUser(USER_ID_TWO, USER_EMAIL_TWO); projectServiceImpl2 = new ProjectServiceImpl(); projectServiceImpls = Maps.newHashMap(); projectServiceImpls.put(USER_ID_ONE, projectServiceImpl); projectServiceImpls.put(USER_ID_TWO, projectServiceImpl2); } @After public void tearDown() throws Exception { helper.tearDown(); PowerMock.resetAll(); } private void checkModificationDateMatchesStored(long oldModificationDate, String userId, long projectId) throws Exception { long modificationDate = storageIo.getProjectDateModified(userId, projectId); assertEquals(oldModificationDate, modificationDate); } @Test public void testProjectService() throws Exception { expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_TWO).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(4); expect(localUserMock.getUserId()).andReturn(USER_ID_TWO).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(11); PowerMock.replayAll(); do_init(); // Create a new young android project NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long user1Project1 = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); long[] user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 1 && user1Projects[0] == user1Project1); // Create another young android project with the same name for another user long user2Project1 = projectServiceImpl2.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); long[] user2Projects = projectServiceImpl2.getProjects(); assertEquals(1, user2Projects.length); assertEquals(user2Project1, user2Projects[0]); // Change the source file in the second users project and make sure only that file // got changed (and not the one of the same name owned by the first user) ProjectRootNode user1Project1Root = projectServiceImpl.getProject(user1Project1); String user1Project1Source1FileId = findFileIdByName(user1Project1Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user1Project1Source1FileId); String user1Project1Source1 = projectServiceImpl.load(user1Project1, user1Project1Source1FileId); long oldModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, user1Project1); long modificationDate = projectServiceImpl.save(user1Project1, user1Project1Source1FileId, YOUNG_ANDROID_COMMENT + user1Project1Source1); assertEquals(YOUNG_ANDROID_COMMENT + user1Project1Source1, projectServiceImpl.load(user1Project1, user1Project1Source1FileId)); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project1); oldModificationDate = modificationDate; ProjectRootNode user2Project1Root = projectServiceImpl2.getProject(user2Project1); String user2Project1Source1FileId = findFileIdByName(user2Project1Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user2Project1Source1FileId); Assert.assertNotEquals(YOUNG_ANDROID_COMMENT, projectServiceImpl2.load(user2Project1, user2Project1Source1FileId)); // Create another new project for user1 params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT2_NAME); long user1Project2 = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT2_NAME, params).getProjectId(); user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 2); ProjectRootNode user1Project2Root = projectServiceImpl.getProject(user1Project2); String user1Project2Source1FileId = findFileIdByName(user1Project2Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user1Project2Source1FileId); // Load and save multiple files String u1p1s1 = projectServiceImpl.load(user1Project1, user1Project1Source1FileId) + YOUNG_ANDROID_COMMENT1; String u1p2s1 = projectServiceImpl.load(user1Project2, user1Project2Source1FileId) + YOUNG_ANDROID_COMMENT2; List<FileDescriptorWithContent> filesWithContent = Lists.newArrayList(); filesWithContent.add(new FileDescriptorWithContent(user1Project1, user1Project1Source1FileId, u1p1s1)); filesWithContent.add(new FileDescriptorWithContent(user1Project2, user1Project2Source1FileId, u1p2s1)); checkModificationDateMatchesStored(oldModificationDate, USER_ID_ONE, user1Project1); modificationDate = projectServiceImpl.save(filesWithContent); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project2); oldModificationDate = modificationDate; List<FileDescriptor> files = Lists.newArrayList(); files.add(new FileDescriptor(user1Project1, user1Project1Source1FileId)); files.add(new FileDescriptor(user1Project2, user1Project2Source1FileId)); filesWithContent = projectServiceImpl.load(files); assertEquals(files.size(), filesWithContent.size()); FileDescriptorWithContent fileWithContent = findFileDescriptorWithContent(filesWithContent, user1Project1, user1Project1Source1FileId); assertNotNull(fileWithContent); assertEquals(u1p1s1, fileWithContent.getContent()); fileWithContent = findFileDescriptorWithContent(filesWithContent, user1Project2, user1Project2Source1FileId); assertNotNull(fileWithContent); assertEquals(u1p2s1, fileWithContent.getContent()); oldModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, user1Project1); modificationDate = projectServiceImpl.deleteFile(user1Project1, user1Project1Source1FileId); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project1); oldModificationDate = modificationDate; // Delete the projects of the first user projectServiceImpl.deleteProject(user1Project1); projectServiceImpl.deleteProject(user1Project2); user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 0); PowerMock.verifyAll(); } @Test public void testNewYoungAndroidProject() throws Exception { // Since only USER_ID_ONE is used, we don't care how many times // getUserId is called expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); PowerMock.replayAll(); do_init(); // First create a Young Android project. NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long yaProject = projectServiceImpl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles = new HashMap<String, String>(); expectedYaFiles.put("src/com/domain/noname/Project1/Screen1.blk", ""); expectedYaFiles.put("youngandroidproject/project.properties", "main=com.domain.noname.Project1.Screen1\n" + "name=Project1\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n"); expectedYaFiles.put("src/com/domain/noname/Project1/Screen1.scm", "#|\n$JSON\n" + "{\"YaVersion\":\"" + YaVersion.YOUNG_ANDROID_VERSION + "\",\"Source\":\"Form\"," + "\"Properties\":{\"$Name\":\"Screen1\",\"$Type\":\"Form\"," + "\"$Version\":\"" + YaVersion.FORM_COMPONENT_VERSION + "\",\"Uuid\":\"0\"," + "\"Title\":\"Screen1\"}}\n|#"); assertEquals(expectedYaFiles, getTextFiles(USER_ID_ONE, yaProject)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject).isEmpty()); checkUserProjects(projectServiceImpl.getProjectInfos(), new UserProject(yaProject, PROJECT1_NAME, YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, System.currentTimeMillis())); PowerMock.verifyAll(); } @Test public void testCopyProject() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); // First create a Young Android project. long yaProject1 = getBuildableYoungAndroidProjectId(USER_ID_ONE, PROJECT1_NAME); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles1 = new HashMap<String, String>(); expectedYaFiles1.put("src/com/domain/noname/Project1/Screen1.blk", ""); expectedYaFiles1.put("youngandroidproject/project.properties", "main=com.domain.noname.Project1.Screen1\n" + "name=Project1\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n"); expectedYaFiles1.put("src/com/domain/noname/Project1/Screen1.scm", YOUNG_ANDROID_PROJECT_SCM_SOURCE); assertEquals(expectedYaFiles1, getTextFiles(USER_ID_ONE, yaProject1)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject1).isEmpty()); // No user files yet (e.g. the keystore) assertTrue(getUserFiles(USER_ID_ONE).isEmpty()); long project1CreationDate = storageIo.getProjectDateCreated(USER_ID_ONE, yaProject1); long project1ModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, yaProject1); assertTrue(project1ModificationDate >= project1CreationDate); // Make a copy of project 1. long yaProject2 = projectServiceImpl.copyProject(yaProject1, PROJECT2_NAME). getProjectId(); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles2 = new HashMap<String, String>(); expectedYaFiles2.put("src/com/domain/noname/Project2/Screen1.blk", ""); expectedYaFiles2.put("youngandroidproject/project.properties", "main=appinventor.ai_noname1.Project2.Screen1\n" + "name=Project2\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n" + "versioncode=1\n" + "versionname=1.0\n"); expectedYaFiles2.put("src/com/domain/noname/Project2/Screen1.scm", YOUNG_ANDROID_PROJECT_SCM_SOURCE); assertEquals(expectedYaFiles2, getTextFiles(USER_ID_ONE, yaProject2)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject2).isEmpty()); assertTrue(getUserFiles(USER_ID_ONE).isEmpty()); long project1CopyCreationDate = storageIo.getProjectDateCreated(USER_ID_ONE, yaProject2); long project1CopyModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, yaProject2); assertTrue(project1CopyCreationDate > project1CreationDate); assertTrue(project1CopyCreationDate > project1ModificationDate); assertTrue(project1CopyModificationDate >= project1CopyCreationDate); PowerMock.verifyAll(); } /** * Creates a new Young Android project with non-empty source * in the test storage instance and returns its project id. * * @param projectName name of the Young Android project. * @return the project id of the Young Android project in the test storage * instance. */ private long getBuildableYoungAndroidProjectId(String userId, String projectName) { NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + projectName); ProjectServiceImpl impl = projectServiceImpls.get(userId); long projectId = impl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, projectName, params).getProjectId(); String scmFileId = "src/com/domain/noname/" + projectName + "/" + YOUNG_ANDROID_FORM_NAME + ".scm"; storageIo.uploadFile(projectId, scmFileId, userId, YOUNG_ANDROID_PROJECT_SCM_SOURCE, StorageUtil.DEFAULT_CHARSET); return projectId; } @Test public void testCreateManyYoungAndroidProjects() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); List<Thread> threads = Lists.newArrayList(); final AtomicInteger ready = new AtomicInteger(); final Object start = new Object(); final AtomicInteger successes = new AtomicInteger(); final AtomicInteger failures = new AtomicInteger(); int numThreads = NUMBER_OF_SIMULTANEOUS_NEW_PROJECTS; for (int i = 0; i < numThreads; i++) { final String projectName = "Project" + i; Thread t = new Thread(new Runnable() { @Override public void run() { // We need to set up the LocalServiceTestHelper here because // otherwise each thread tries to access the real storage. // TODO(user): Does this test still test the right // thing, given that? helper.setUpThread(); // The first thing each thread does is signal that it is ready and then wait for the // start notification. synchronized (start) { ready.incrementAndGet(); try { start.wait(); } catch (InterruptedException e) { // do nothing } } NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + projectName); long projectId = projectServiceImpl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, projectName, params).getProjectId(); if (projectId < 0) { failures.incrementAndGet(); } else { successes.incrementAndGet(); } } }); threads.add(t); t.start(); } // Tell all threads to start. // We can't enter the synchronized (start) block until all the threads have told us they are // ready. Otherwise, a thread could miss the notification and wait forever. while (ready.get() < numThreads) { try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } } synchronized (start) { start.notifyAll(); } // Wait for all threads to finish. for (Thread t : threads) { t.join(); } assertEquals(numThreads, successes.get()); assertEquals(0, failures.get()); PowerMock.verifyAll(); } @Test public void testLoadAndStoreProjectSettings() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long projectId = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); String loadedSettings = projectServiceImpl.loadProjectSettings(projectId); assertEquals( "{\"" + SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS + "\":" + "{\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ICON + "\":\"\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_VERSION_CODE + "\":\"1\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_VERSION_NAME + "\":\"1.0\"}}", loadedSettings); String storedSettings = "{\"" + SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS + "\":" + "{\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ICON + "\":\"KittyIcon.png\"}}"; projectServiceImpl.storeProjectSettings(projectId, storedSettings); loadedSettings = projectServiceImpl.loadProjectSettings(projectId); assertEquals(storedSettings, loadedSettings); PowerMock.verifyAll(); } private Map<String, String> getTextFiles(String userId, long projectId) { Map<String, String> textFiles = new HashMap<String, String>(); for (String fileId : storageIo.getProjectSourceFiles(userId, projectId)) { if (StorageUtil.isTextFile(fileId)) { // TODO(user): We should get rid of DEFAULT_CHARSET and use UTF-8 everywhere. textFiles.put(fileId, storageIo.downloadFile(userId, projectId, fileId, StorageUtil.DEFAULT_CHARSET)); } } return textFiles; } private Map<String, byte[]> getNonTextFiles(String userId, long projectId) { Map<String, byte[]> nonTextFiles = new HashMap<String, byte[]>(); for (String fileId : storageIo.getProjectSourceFiles(userId, projectId)) { if (!StorageUtil.isTextFile(fileId)) { nonTextFiles.put(fileId, storageIo.downloadRawFile(userId, projectId, fileId)); } } return nonTextFiles; } private Map<String, byte[]> getUserFiles(String userId) { Map<String, byte[]> userFiles = new HashMap<String, byte[]>(); for (String fileId : storageIo.getUserFiles(userId)) { userFiles.put(fileId, storageIo.downloadRawUserFile(userId, fileId)); } return userFiles; } private static String findFileIdByName(ProjectNode parent, String name) { if (parent.getName().equals(name)) { return parent.getFileId(); } for (ProjectNode node : parent.getChildren()) { String fileId = findFileIdByName(node, name); if (fileId != null) { return fileId; } } return null; } private static FileDescriptorWithContent findFileDescriptorWithContent( List<FileDescriptorWithContent> filesWithContent, long projectId, String fileId) { for (FileDescriptorWithContent fileWithContent : filesWithContent) { if (fileWithContent.getProjectId() == projectId && fileWithContent.getFileId().equals(fileId)) { return fileWithContent; } } return null; } private void checkUserProjects(List<UserProject> actual, UserProject... expected) throws Exception { if (actual.size() != expected.length) { fail("expected <" + expected.length + "> UserProjects but was:<" + actual.size() + '>'); } // Build a map from project id to UserProject for the actual projects so we won't nested // for loops below. // Also, build a String to describe the actual UserProjects that we can use in failure messages. Map<Long, UserProject> actualByProjectId = Maps.newHashMap(); StringBuilder actualDesc = new StringBuilder(); String delimiter = ""; for (UserProject actualUserProject : actual) { actualByProjectId.put(actualUserProject.getProjectId(), actualUserProject); actualDesc.append(delimiter).append(getUserProjectDesc(actualUserProject)); delimiter = ","; } for (UserProject expectedUserProject : expected) { long projectId = expectedUserProject.getProjectId(); UserProject actualUserProject = actualByProjectId.get(projectId); if (actualUserProject == null) { fail("expected to contain:<" + getUserProjectDesc(expectedUserProject) + "> but was:<" + actualDesc + '>'); } if (!Objects.equal(expectedUserProject.getProjectName(), actualUserProject.getProjectName())) { fail("expected project name:<" + expectedUserProject.getProjectName() + "> but was:<" + actualUserProject.getProjectName() + '>'); } if (!Objects.equal(expectedUserProject.getProjectType(), actualUserProject.getProjectType())) { fail("expected project type:<" + expectedUserProject.getProjectType() + "> but was:<" + actualUserProject.getProjectType() + '>'); } // Expected user project date was created after actual user project if (expectedUserProject.getDateCreated() < actualUserProject.getDateCreated()) { fail("expected date:<" + expectedUserProject.getDateCreated() + "> but was:<" + actualUserProject.getDateCreated() + '>'); } } } private static String getUserProjectDesc(UserProject userProject) { return "UserProject(" + userProject.getProjectId() + ",\"" + userProject.getProjectName() + "\")"; } }
appinventor/appengine/tests/com/google/appinventor/server/ProjectServiceTest.java
// Copyright 2008 Google Inc. All Rights Reserved. package com.google.appinventor.server; import static com.google.appinventor.shared.rpc.project.youngandroid.NewYoungAndroidProjectParameters.YOUNG_ANDROID_FORM_NAME; import static org.easymock.EasyMock.expect; import com.google.appinventor.common.testutils.TestUtils; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.server.encryption.KeyczarEncryptor; import com.google.appinventor.server.storage.StorageIo; import com.google.appinventor.server.storage.StorageIoInstanceHolder; import com.google.appinventor.shared.rpc.project.FileDescriptor; import com.google.appinventor.shared.rpc.project.FileDescriptorWithContent; import com.google.appinventor.shared.rpc.project.ProjectNode; import com.google.appinventor.shared.rpc.project.ProjectRootNode; import com.google.appinventor.shared.rpc.project.UserProject; import com.google.appinventor.shared.rpc.project.youngandroid.NewYoungAndroidProjectParameters; import com.google.appinventor.shared.rpc.project.youngandroid.YoungAndroidProjectNode; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.appinventor.shared.storage.StorageUtil; import com.google.appinventor.shared.youngandroid.YoungAndroidSourceAnalyzer; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import static junit.framework.Assert.*; import junitx.framework.Assert; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.easymock.PowerMock; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * Tests for {@link ProjectServiceImpl}. * */ @PowerMockIgnore({"javax.crypto.*" }) @RunWith(PowerMockRunner.class) @PrepareForTest({ LocalUser.class }) public class ProjectServiceTest { // If ProjectServiceTest (which uses PowerMock.mockStatic) extends LocalDatastoreTestCase, then // it will fail with Ant version 1.8.2. private final LocalDatastoreTestCase helper = LocalDatastoreTestCase.createHelper(); private static final String USER_ID_ONE = "id1"; private static final String USER_ID_TWO = "id2"; private static final String USER_EMAIL_ONE = "[email protected]"; private static final String USER_EMAIL_TWO = "[email protected]"; private static final String PROJECT1_NAME = "Project1"; private static final String PROJECT2_NAME = "Project2"; private static final String PROJECT3_NAME = "Project3"; private static final String PACKAGE_BASE = "com.domain.noname."; private static final String YOUNG_ANDROID_COMMENT = ";;; Cat In The Hat by Dr. Seuss\n"; private static final String YOUNG_ANDROID_COMMENT1 = ";;; Don't Hop on Pop by Dr. Seuss\n"; private static final String YOUNG_ANDROID_COMMENT2 = ";;; Green Eggs and Ham by Dr. Seuss\n"; private static final int NUMBER_OF_SIMULTANEOUS_NEW_PROJECTS = 50; private static final String YOUNG_ANDROID_PROJECT_SCM_SOURCE = "\n" + "#|\n" + "$JSON\n" + "{\"Source\":\"Form\",\"Properties\":{\"$Name\":\"Screen1\",\"$Type\":\"Form\"," + "\"Uuid\":\"0\",\"Title\":\"Screen1\",\"$Components\":[" + "{\"$Name\":\"Button1\",\"$Type\":\"Button\",\"Uuid\":\"123\",\"Text\":\"Button1\"," + "\"Width\":\"80\"}," + "{\"$Name\":\"Label1\",\"$Type\":\"Label\",\"Uuid\":\"-456\",\"Text\":\"Liz\"}" + "]}}\n" + "|#"; private StorageIo storageIo; private ProjectServiceImpl projectServiceImpl; // for USER_ID_ONE private ProjectServiceImpl projectServiceImpl2; // for USER_ID_TWO private Map<String, ProjectServiceImpl> projectServiceImpls; private LocalUser localUserMock; public static final String KEYSTORE_ROOT_PATH = TestUtils.APP_INVENTOR_ROOT_DIR + "/appengine/build/war/"; // must end with a slash @Before public void setUp() throws Exception { helper.setUp(); storageIo = StorageIoInstanceHolder.INSTANCE; PowerMock.mockStatic(LocalUser.class); localUserMock = PowerMock.createMock(LocalUser.class); expect(LocalUser.getInstance()).andReturn(localUserMock).anyTimes(); KeyczarEncryptor.rootPath.setForTest(KEYSTORE_ROOT_PATH); } void do_init() { storageIo.getUser(USER_ID_ONE, USER_EMAIL_ONE); projectServiceImpl = new ProjectServiceImpl(); storageIo.getUser(USER_ID_TWO, USER_EMAIL_TWO); projectServiceImpl2 = new ProjectServiceImpl(); projectServiceImpls = Maps.newHashMap(); projectServiceImpls.put(USER_ID_ONE, projectServiceImpl); projectServiceImpls.put(USER_ID_TWO, projectServiceImpl2); } @After public void tearDown() throws Exception { helper.tearDown(); PowerMock.resetAll(); } private void checkModificationDateMatchesStored(long oldModificationDate, String userId, long projectId) throws Exception { long modificationDate = storageIo.getProjectDateModified(userId, projectId); assertEquals(oldModificationDate, modificationDate); } @Test public void testProjectService() throws Exception { expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_TWO).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(4); expect(localUserMock.getUserId()).andReturn(USER_ID_TWO).times(2); expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).times(11); PowerMock.replayAll(); do_init(); // Create a new young android project NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long user1Project1 = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); long[] user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 1 && user1Projects[0] == user1Project1); // Create another young android project with the same name for another user long user2Project1 = projectServiceImpl2.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); long[] user2Projects = projectServiceImpl2.getProjects(); assertEquals(1, user2Projects.length); assertEquals(user2Project1, user2Projects[0]); // Change the source file in the second users project and make sure only that file // got changed (and not the one of the same name owned by the first user) ProjectRootNode user1Project1Root = projectServiceImpl.getProject(user1Project1); String user1Project1Source1FileId = findFileIdByName(user1Project1Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user1Project1Source1FileId); String user1Project1Source1 = projectServiceImpl.load(user1Project1, user1Project1Source1FileId); long oldModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, user1Project1); long modificationDate = projectServiceImpl.save(user1Project1, user1Project1Source1FileId, YOUNG_ANDROID_COMMENT + user1Project1Source1); assertEquals(YOUNG_ANDROID_COMMENT + user1Project1Source1, projectServiceImpl.load(user1Project1, user1Project1Source1FileId)); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project1); oldModificationDate = modificationDate; ProjectRootNode user2Project1Root = projectServiceImpl2.getProject(user2Project1); String user2Project1Source1FileId = findFileIdByName(user2Project1Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user2Project1Source1FileId); Assert.assertNotEquals(YOUNG_ANDROID_COMMENT, projectServiceImpl2.load(user2Project1, user2Project1Source1FileId)); // Create another new project for user1 params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT2_NAME); long user1Project2 = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT2_NAME, params).getProjectId(); user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 2); ProjectRootNode user1Project2Root = projectServiceImpl.getProject(user1Project2); String user1Project2Source1FileId = findFileIdByName(user1Project2Root, YOUNG_ANDROID_FORM_NAME + YoungAndroidSourceAnalyzer.FORM_PROPERTIES_EXTENSION); assertNotNull(user1Project2Source1FileId); // Load and save multiple files String u1p1s1 = projectServiceImpl.load(user1Project1, user1Project1Source1FileId) + YOUNG_ANDROID_COMMENT1; String u1p2s1 = projectServiceImpl.load(user1Project2, user1Project2Source1FileId) + YOUNG_ANDROID_COMMENT2; List<FileDescriptorWithContent> filesWithContent = Lists.newArrayList(); filesWithContent.add(new FileDescriptorWithContent(user1Project1, user1Project1Source1FileId, u1p1s1)); filesWithContent.add(new FileDescriptorWithContent(user1Project2, user1Project2Source1FileId, u1p2s1)); checkModificationDateMatchesStored(oldModificationDate, USER_ID_ONE, user1Project1); modificationDate = projectServiceImpl.save(filesWithContent); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project2); oldModificationDate = modificationDate; List<FileDescriptor> files = Lists.newArrayList(); files.add(new FileDescriptor(user1Project1, user1Project1Source1FileId)); files.add(new FileDescriptor(user1Project2, user1Project2Source1FileId)); filesWithContent = projectServiceImpl.load(files); assertEquals(files.size(), filesWithContent.size()); FileDescriptorWithContent fileWithContent = findFileDescriptorWithContent(filesWithContent, user1Project1, user1Project1Source1FileId); assertNotNull(fileWithContent); assertEquals(u1p1s1, fileWithContent.getContent()); fileWithContent = findFileDescriptorWithContent(filesWithContent, user1Project2, user1Project2Source1FileId); assertNotNull(fileWithContent); assertEquals(u1p2s1, fileWithContent.getContent()); oldModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, user1Project1); modificationDate = projectServiceImpl.deleteFile(user1Project1, user1Project1Source1FileId); assertTrue(oldModificationDate < modificationDate); checkModificationDateMatchesStored(modificationDate, USER_ID_ONE, user1Project1); oldModificationDate = modificationDate; // Delete the projects of the first user projectServiceImpl.deleteProject(user1Project1); projectServiceImpl.deleteProject(user1Project2); user1Projects = projectServiceImpl.getProjects(); assertTrue(user1Projects.length == 0); PowerMock.verifyAll(); } @Test public void testNewYoungAndroidProject() throws Exception { // Since only USER_ID_ONE is used, we don't care how many times // getUserId is called expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); PowerMock.replayAll(); do_init(); // First create a Young Android project. NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long yaProject = projectServiceImpl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles = new HashMap<String, String>(); expectedYaFiles.put("src/com/domain/noname/Project1/Screen1.blk", ""); expectedYaFiles.put("youngandroidproject/project.properties", "main=com.domain.noname.Project1.Screen1\n" + "name=Project1\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n"); expectedYaFiles.put("src/com/domain/noname/Project1/Screen1.scm", "#|\n$JSON\n" + "{\"YaVersion\":\"" + YaVersion.YOUNG_ANDROID_VERSION + "\",\"Source\":\"Form\"," + "\"Properties\":{\"$Name\":\"Screen1\",\"$Type\":\"Form\"," + "\"$Version\":\"" + YaVersion.FORM_COMPONENT_VERSION + "\",\"Uuid\":\"0\"," + "\"Title\":\"Screen1\"}}\n|#"); assertEquals(expectedYaFiles, getTextFiles(USER_ID_ONE, yaProject)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject).isEmpty()); checkUserProjects(projectServiceImpl.getProjectInfos(), new UserProject(yaProject, PROJECT1_NAME, YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, System.currentTimeMillis())); PowerMock.verifyAll(); } @Test public void testCopyProject() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); // First create a Young Android project. long yaProject1 = getBuildableYoungAndroidProjectId(USER_ID_ONE, PROJECT1_NAME); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles1 = new HashMap<String, String>(); expectedYaFiles1.put("src/com/domain/noname/Project1/Screen1.blk", ""); expectedYaFiles1.put("youngandroidproject/project.properties", "main=com.domain.noname.Project1.Screen1\n" + "name=Project1\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n"); expectedYaFiles1.put("src/com/domain/noname/Project1/Screen1.scm", YOUNG_ANDROID_PROJECT_SCM_SOURCE); assertEquals(expectedYaFiles1, getTextFiles(USER_ID_ONE, yaProject1)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject1).isEmpty()); // No user files yet (e.g. the keystore) assertTrue(getUserFiles(USER_ID_ONE).isEmpty()); long project1CreationDate = storageIo.getProjectDateCreated(USER_ID_ONE, yaProject1); long project1ModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, yaProject1); assertTrue(project1ModificationDate >= project1CreationDate); // Make a copy of project 1. long yaProject2 = projectServiceImpl.copyProject(yaProject1, PROJECT2_NAME). getProjectId(); // Check the contents of each file in the new project. Map<String, String> expectedYaFiles2 = new HashMap<String, String>(); expectedYaFiles2.put("src/com/domain/noname/Project2/Screen1.blk", ""); expectedYaFiles2.put("youngandroidproject/project.properties", "main=appinventor.ai_noname1.Project2.Screen1\n" + "name=Project2\n" + "assets=../assets\n" + "source=../src\n" + "build=../build\n"); expectedYaFiles2.put("src/com/domain/noname/Project2/Screen1.scm", YOUNG_ANDROID_PROJECT_SCM_SOURCE); assertEquals(expectedYaFiles2, getTextFiles(USER_ID_ONE, yaProject2)); assertTrue(getNonTextFiles(USER_ID_ONE, yaProject2).isEmpty()); assertTrue(getUserFiles(USER_ID_ONE).isEmpty()); long project1CopyCreationDate = storageIo.getProjectDateCreated(USER_ID_ONE, yaProject2); long project1CopyModificationDate = storageIo.getProjectDateModified(USER_ID_ONE, yaProject2); assertTrue(project1CopyCreationDate > project1CreationDate); assertTrue(project1CopyCreationDate > project1ModificationDate); assertTrue(project1CopyModificationDate >= project1CopyCreationDate); PowerMock.verifyAll(); } /** * Creates a new Young Android project with non-empty source * in the test storage instance and returns its project id. * * @param projectName name of the Young Android project. * @return the project id of the Young Android project in the test storage * instance. */ private long getBuildableYoungAndroidProjectId(String userId, String projectName) { NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + projectName); ProjectServiceImpl impl = projectServiceImpls.get(userId); long projectId = impl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, projectName, params).getProjectId(); String scmFileId = "src/com/domain/noname/" + projectName + "/" + YOUNG_ANDROID_FORM_NAME + ".scm"; storageIo.uploadFile(projectId, scmFileId, userId, YOUNG_ANDROID_PROJECT_SCM_SOURCE, StorageUtil.DEFAULT_CHARSET); return projectId; } @Test public void testCreateManyYoungAndroidProjects() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); List<Thread> threads = Lists.newArrayList(); final AtomicInteger ready = new AtomicInteger(); final Object start = new Object(); final AtomicInteger successes = new AtomicInteger(); final AtomicInteger failures = new AtomicInteger(); int numThreads = NUMBER_OF_SIMULTANEOUS_NEW_PROJECTS; for (int i = 0; i < numThreads; i++) { final String projectName = "Project" + i; Thread t = new Thread(new Runnable() { @Override public void run() { // We need to set up the LocalServiceTestHelper here because // otherwise each thread tries to access the real storage. // TODO(user): Does this test still test the right // thing, given that? helper.setUpThread(); // The first thing each thread does is signal that it is ready and then wait for the // start notification. synchronized (start) { ready.incrementAndGet(); try { start.wait(); } catch (InterruptedException e) { // do nothing } } NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + projectName); long projectId = projectServiceImpl.newProject(YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, projectName, params).getProjectId(); if (projectId < 0) { failures.incrementAndGet(); } else { successes.incrementAndGet(); } } }); threads.add(t); t.start(); } // Tell all threads to start. // We can't enter the synchronized (start) block until all the threads have told us they are // ready. Otherwise, a thread could miss the notification and wait forever. while (ready.get() < numThreads) { try { Thread.sleep(500); } catch (InterruptedException e) { // do nothing } } synchronized (start) { start.notifyAll(); } // Wait for all threads to finish. for (Thread t : threads) { t.join(); } assertEquals(numThreads, successes.get()); assertEquals(0, failures.get()); PowerMock.verifyAll(); } @Test public void testLoadAndStoreProjectSettings() throws Exception { // Since only USER_ID_ONE is used in this test, we don't care how // many times getUser or getUserId are called; they'll always // return the same result expect(localUserMock.getUserId()).andReturn(USER_ID_ONE).anyTimes(); expect(localUserMock.getUser()).andReturn(storageIo.getUser(USER_ID_ONE)).anyTimes(); PowerMock.replayAll(); do_init(); NewYoungAndroidProjectParameters params = new NewYoungAndroidProjectParameters( PACKAGE_BASE + PROJECT1_NAME); long projectId = projectServiceImpl.newProject( YoungAndroidProjectNode.YOUNG_ANDROID_PROJECT_TYPE, PROJECT1_NAME, params).getProjectId(); String loadedSettings = projectServiceImpl.loadProjectSettings(projectId); assertEquals( "{\"" + SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS + "\":" + "{\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ICON + "\":\"\"}}", loadedSettings); String storedSettings = "{\"" + SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS + "\":" + "{\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ICON + "\":\"KittyIcon.png\"}}"; projectServiceImpl.storeProjectSettings(projectId, storedSettings); loadedSettings = projectServiceImpl.loadProjectSettings(projectId); assertEquals(storedSettings, loadedSettings); PowerMock.verifyAll(); } private Map<String, String> getTextFiles(String userId, long projectId) { Map<String, String> textFiles = new HashMap<String, String>(); for (String fileId : storageIo.getProjectSourceFiles(userId, projectId)) { if (StorageUtil.isTextFile(fileId)) { // TODO(user): We should get rid of DEFAULT_CHARSET and use UTF-8 everywhere. textFiles.put(fileId, storageIo.downloadFile(userId, projectId, fileId, StorageUtil.DEFAULT_CHARSET)); } } return textFiles; } private Map<String, byte[]> getNonTextFiles(String userId, long projectId) { Map<String, byte[]> nonTextFiles = new HashMap<String, byte[]>(); for (String fileId : storageIo.getProjectSourceFiles(userId, projectId)) { if (!StorageUtil.isTextFile(fileId)) { nonTextFiles.put(fileId, storageIo.downloadRawFile(userId, projectId, fileId)); } } return nonTextFiles; } private Map<String, byte[]> getUserFiles(String userId) { Map<String, byte[]> userFiles = new HashMap<String, byte[]>(); for (String fileId : storageIo.getUserFiles(userId)) { userFiles.put(fileId, storageIo.downloadRawUserFile(userId, fileId)); } return userFiles; } private static String findFileIdByName(ProjectNode parent, String name) { if (parent.getName().equals(name)) { return parent.getFileId(); } for (ProjectNode node : parent.getChildren()) { String fileId = findFileIdByName(node, name); if (fileId != null) { return fileId; } } return null; } private static FileDescriptorWithContent findFileDescriptorWithContent( List<FileDescriptorWithContent> filesWithContent, long projectId, String fileId) { for (FileDescriptorWithContent fileWithContent : filesWithContent) { if (fileWithContent.getProjectId() == projectId && fileWithContent.getFileId().equals(fileId)) { return fileWithContent; } } return null; } private void checkUserProjects(List<UserProject> actual, UserProject... expected) throws Exception { if (actual.size() != expected.length) { fail("expected <" + expected.length + "> UserProjects but was:<" + actual.size() + '>'); } // Build a map from project id to UserProject for the actual projects so we won't nested // for loops below. // Also, build a String to describe the actual UserProjects that we can use in failure messages. Map<Long, UserProject> actualByProjectId = Maps.newHashMap(); StringBuilder actualDesc = new StringBuilder(); String delimiter = ""; for (UserProject actualUserProject : actual) { actualByProjectId.put(actualUserProject.getProjectId(), actualUserProject); actualDesc.append(delimiter).append(getUserProjectDesc(actualUserProject)); delimiter = ","; } for (UserProject expectedUserProject : expected) { long projectId = expectedUserProject.getProjectId(); UserProject actualUserProject = actualByProjectId.get(projectId); if (actualUserProject == null) { fail("expected to contain:<" + getUserProjectDesc(expectedUserProject) + "> but was:<" + actualDesc + '>'); } if (!Objects.equal(expectedUserProject.getProjectName(), actualUserProject.getProjectName())) { fail("expected project name:<" + expectedUserProject.getProjectName() + "> but was:<" + actualUserProject.getProjectName() + '>'); } if (!Objects.equal(expectedUserProject.getProjectType(), actualUserProject.getProjectType())) { fail("expected project type:<" + expectedUserProject.getProjectType() + "> but was:<" + actualUserProject.getProjectType() + '>'); } // Expected user project date was created after actual user project if (expectedUserProject.getDateCreated() < actualUserProject.getDateCreated()) { fail("expected date:<" + expectedUserProject.getDateCreated() + "> but was:<" + actualUserProject.getDateCreated() + '>'); } } } private static String getUserProjectDesc(UserProject userProject) { return "UserProject(" + userProject.getProjectId() + ",\"" + userProject.getProjectName() + "\")"; } }
Updated the ProjectServiceTest to add the new properties
appinventor/appengine/tests/com/google/appinventor/server/ProjectServiceTest.java
Updated the ProjectServiceTest to add the new properties
Java
apache-2.0
46ec11ec418df327769174ae90dbf8ca8422e2fe
0
lijihuai/cas,DICE-UNC/cas,CruGlobal/cas,moghaddam/cas,youjava/cas,yisiqi/cas,fengbaicanhe/cas,thomasdarimont/cas,seanrbaker/cas,luneo7/cas,jasonchw/cas,HuangWeiWei1919/cas,openedbox/cas,creamer/cas,youjava/cas,icereval/cas,ssmyka/cas,thomasdarimont/cas,mduszyk/cas,daniel-he/cas,jasonchw/cas,zhangjianTFTC/cas,nader93k/cas,zhangjianTFTC/cas,seanrbaker/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,CruGlobal/cas,seanrbaker/cas,luneo7/cas,zhangjianTFTC/cas,luneo7/cas,vbonamy/cas,rallportctr/cas,thomasdarimont/cas,mabes/cas,creamer/cas,battags/cas,joansmith/cas,PetrGasparik/cas,vbonamy/cas,zion64/cas-private,creamer/cas,dfish3r/cas-x509-crl-ldaptive,icanfly/cas,j-fuentes/cas,zhangwei5095/jasig-cas-server,nestle1998/cas,zhangjianTFTC/cas,fannyfinal/cas,zhangwei5095/jasig-cas-server,fogbeam/fogbeam_cas,kalatestimine/cas,jacklotusho/cas,yisiqi/cas,joansmith/cas,DICE-UNC/cas,zhangwei5095/jasig-cas-server,keshvari/cas,fannyfinal/cas,mabes/cas,openedbox/cas,zhaorui1/cas,zhoffice/cas,lnthai2002/cas,battags/cas,PetrGasparik/cas,lijihuai/cas,austgl/cas,eBaoTech/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,seanrbaker/cas,openedbox/cas,icanfly/cas,j-fuentes/cas,HuangWeiWei1919/cas,keshvari/cas,joansmith/cas,daniel-he/cas,zawn/cas,rallportctr/cas,ssmyka/cas,fogbeam/fogbeam_cas,DICE-UNC/cas,icereval/cas,NicolasMarcotte/cas,mabes/cas,dfish3r/cas-x509-crl-ldaptive,Kuohong/cas,PetrGasparik/cas,zawn/cas,Kuohong/cas,fatherican/cas,Kevin2030/cas,lijihuai/cas,kalatestimine/cas,jacklotusho/cas,NicolasMarcotte/cas,moghaddam/cas,dfish3r/cas-x509-crl-ldaptive,mabes/cas,moghaddam/cas,lijihuai/cas,briandwyer/cas-hudson,joansmith/cas,Kuohong/cas,openedbox/cas,thomasdarimont/cas,icereval/cas,austgl/cas,HuangWeiWei1919/cas,fatherican/cas,Kuohong/cas,austgl/cas,nader93k/cas,rallportctr/cas,zhaorui1/cas,DICE-UNC/cas,lnthai2002/cas,jacklotusho/cas,vbonamy/cas,rallportctr/cas,austgl/cas,jasonchw/cas,fannyfinal/cas,icanfly/cas,UniversityOfPardubice/idp.upce.cz-jasig-cas,zhoffice/cas,fannyfinal/cas,fengbaicanhe/cas,keshvari/cas,ssmyka/cas,fatherican/cas,mduszyk/cas,jasonchw/cas,zhoffice/cas,PetrGasparik/cas,nestle1998/cas,fatherican/cas,NicolasMarcotte/cas,zhoffice/cas,briandwyer/cas-hudson,zawn/cas,fogbeam/fogbeam_cas,nader93k/cas,daniel-he/cas,youjava/cas,zhaorui1/cas,yisiqi/cas,youjava/cas,NicolasMarcotte/cas,mduszyk/cas,luneo7/cas,j-fuentes/cas,dfish3r/cas-x509-crl-ldaptive,kalatestimine/cas,eBaoTech/cas,Kevin2030/cas,eBaoTech/cas,ssmyka/cas,fogbeam/fogbeam_cas,Kevin2030/cas,daniel-he/cas,nestle1998/cas,zion64/cas-private,Kevin2030/cas,icereval/cas,fengbaicanhe/cas,nader93k/cas,zhaorui1/cas,moghaddam/cas,kalatestimine/cas,keshvari/cas,vbonamy/cas,mduszyk/cas,j-fuentes/cas,eBaoTech/cas,jacklotusho/cas,battags/cas,zawn/cas,fengbaicanhe/cas,zion64/cas-private,creamer/cas,icanfly/cas,zhangwei5095/jasig-cas-server,nestle1998/cas,HuangWeiWei1919/cas,battags/cas,yisiqi/cas
/* * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license * distributed with this file and available online at * http://www.ja-sig.org/products/cas/overview/license/ */ package org.jasig.cas.web.flow; import org.springframework.util.StringUtils; import org.springframework.webflow.conversation.*; import org.springframework.webflow.execution.FlowExecution; import org.springframework.webflow.execution.FlowExecutionKey; import org.springframework.webflow.execution.repository.BadlyFormattedFlowExecutionKeyException; import org.springframework.webflow.execution.repository.FlowExecutionRepositoryException; import org.springframework.webflow.execution.repository.impl.DefaultFlowExecutionRepository; import org.springframework.webflow.execution.repository.snapshot.FlowExecutionSnapshotFactory; import org.springframework.webflow.execution.repository.support.CompositeFlowExecutionKey; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.UUID; /** * Extension to the default Spring Web Flow {@link DefaultFlowExecutionRepository}. We override a number of protected methods to * provide our own key which includes a random part. Due to the structure of the super class, we've also had to copy a * number of private methods to the sub class in order to have it actually work. <strong>This is not a good idea.</strong> * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.4.7 */ public final class CasFlowExecutionKeyFactory extends DefaultFlowExecutionRepository { public static final String DEFAULT_ENCRYPTION_ALGORITHM = "AES"; public static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private boolean defaultBehavior = false; @NotNull private final ConversationManager conversationManager; @NotNull private final Key key; @NotNull private final String cipherAlgorithm; private final byte[] initialVector = getRandomSalt(16); private final IvParameterSpec ivs = new IvParameterSpec(this.initialVector); public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { this(conversationManager, snapshotFactory, DEFAULT_CIPHER_ALGORITHM, KeyGenerator.getInstance(DEFAULT_ENCRYPTION_ALGORITHM).generateKey()); } public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory, final String cipherAlgorithm, final Key secretKey) { super(conversationManager, snapshotFactory); this.conversationManager = conversationManager; this.key = secretKey; this.cipherAlgorithm = cipherAlgorithm; } private static byte[] getRandomSalt(final int size) { final SecureRandom secureRandom = new SecureRandom(); final byte[] bytes = new byte[size]; secureRandom.nextBytes(bytes); return bytes; } protected String decrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.DECRYPT_MODE, this.key, this.ivs); return new String(cipher.doFinal(hexStringToByteArray(value))); } catch (final Exception e) { throw new RuntimeException(e); } } protected String encrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, this.key, this.ivs); return byteArrayToHexString(cipher.doFinal(value.getBytes())); } catch (final Exception e) { throw new RuntimeException(e); } } public static String byteArrayToHexString(byte[] b){ StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++){ int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(); } protected static byte[] hexStringToByteArray(final String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++){ int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte)v; } return b; } public FlowExecutionKey getKey(final FlowExecution execution) { if (this.defaultBehavior) { return super.getKey(execution); } final CasFlowExecutionKey key = (CasFlowExecutionKey) execution.getKey(); if (key == null) { final Conversation conversation = beginConversation(execution); final ConversationId executionId = conversation.getId(); final Serializable nextSnapshotId = nextSnapshotId(executionId); final String unencryptedVersion = UUID.randomUUID().toString() + CasFlowExecutionKey.KEY_SEPARATOR + "e" + executionId + "s" + nextSnapshotId; final String encryptedVersion = encrypt(unencryptedVersion); return new CasFlowExecutionKey(executionId, nextSnapshotId, encryptedVersion); } else { if (getAlwaysGenerateNewNextKey()) { final Serializable executionId = key.getExecutionId(); final Serializable snapshotId = nextSnapshotId(key.getExecutionId()); final String unencryptedVersion = UUID.randomUUID().toString() + CasFlowExecutionKey.KEY_SEPARATOR + "e" + executionId + "s" + snapshotId; final String encryptedVersion = encrypt(unencryptedVersion); return new CasFlowExecutionKey(executionId, snapshotId, encryptedVersion); } else { return execution.getKey(); } } } public FlowExecutionKey parseFlowExecutionKey(final String encodedKey) throws FlowExecutionRepositoryException { if (this.defaultBehavior) { return super.parseFlowExecutionKey(encodedKey); } if (!StringUtils.hasText(encodedKey)) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, "The string-encoded flow execution key is required"); } final String unencryptedVersion = decrypt(encodedKey); String[] keyParts = CasFlowExecutionKey.keyParts(unencryptedVersion); Serializable executionId = parseExecutionId(keyParts[0], encodedKey); Serializable snapshotId = parseSnapshotId(keyParts[1], encodedKey); return new CasFlowExecutionKey(executionId, snapshotId, encodedKey); } private ConversationId parseExecutionId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return this.conversationManager.parseConversationId(encodedId); } catch (ConversationException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } private Serializable parseSnapshotId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return Integer.valueOf(encodedId); } catch (NumberFormatException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } /** * Copied from super-class since its marked as private. * @param execution * @return */ private Conversation beginConversation(FlowExecution execution) { ConversationParameters parameters = createConversationParameters(execution); Conversation conversation = this.conversationManager.beginConversation(parameters); return conversation; } public void setDefaultBehavior(final boolean defaultBehavior) { this.defaultBehavior = defaultBehavior; } }
cas-server-3.4.2/cas-server-webapp/src/main/java/org/jasig/cas/web/flow/CasFlowExecutionKeyFactory.java
/* * Copyright 2007 The JA-SIG Collaborative. All rights reserved. See license * distributed with this file and available online at * http://www.ja-sig.org/products/cas/overview/license/ */ package org.jasig.cas.web.flow; import org.springframework.util.StringUtils; import org.springframework.webflow.conversation.*; import org.springframework.webflow.execution.FlowExecution; import org.springframework.webflow.execution.FlowExecutionKey; import org.springframework.webflow.execution.repository.BadlyFormattedFlowExecutionKeyException; import org.springframework.webflow.execution.repository.FlowExecutionRepositoryException; import org.springframework.webflow.execution.repository.impl.DefaultFlowExecutionRepository; import org.springframework.webflow.execution.repository.snapshot.FlowExecutionSnapshotFactory; import org.springframework.webflow.execution.repository.support.CompositeFlowExecutionKey; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.IvParameterSpec; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.UUID; /** * Extension to the default Spring Web Flow {@link DefaultFlowExecutionRepository}. We override a number of protected methods to * provide our own key which includes a random part. Due to the structure of the super class, we've also had to copy a * number of private methods to the sub class in order to have it actually work. <strong>This is not a good idea.</strong> * * @author Scott Battaglia * @version $Revision$ $Date$ * @since 3.4.7 */ public final class CasFlowExecutionKeyFactory extends DefaultFlowExecutionRepository { private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; public static final String DEFAULT_ENCRYPTION_ALGORITHM = "AES"; public static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private boolean defaultBehavior = false; @NotNull private final ConversationManager conversationManager; @NotNull private final Key key; @NotNull private final String cipherAlgorithm; private final byte[] initialVector = getRandomSalt(16); private final IvParameterSpec ivs = new IvParameterSpec(this.initialVector); public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException { this(conversationManager, snapshotFactory, DEFAULT_CIPHER_ALGORITHM, KeyGenerator.getInstance(DEFAULT_ENCRYPTION_ALGORITHM).generateKey()); } public CasFlowExecutionKeyFactory(final ConversationManager conversationManager, final FlowExecutionSnapshotFactory snapshotFactory, final String cipherAlgorithm, final Key secretKey) { super(conversationManager, snapshotFactory); this.conversationManager = conversationManager; this.key = secretKey; this.cipherAlgorithm = cipherAlgorithm; } private static byte[] getRandomSalt(final int size) { final SecureRandom secureRandom = new SecureRandom(); final byte[] bytes = new byte[size]; secureRandom.nextBytes(bytes); return bytes; } protected String decrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.DECRYPT_MODE, this.key, this.ivs); return new String(cipher.doFinal(hexStringToByteArray(value))); } catch (final Exception e) { throw new RuntimeException(e); } } protected String encrypt(final String value) { if (value == null) { return null; } try { final Cipher cipher = Cipher.getInstance(this.cipherAlgorithm); cipher.init(Cipher.ENCRYPT_MODE, this.key, this.ivs); return byteArrayToHexString(cipher.doFinal(value.getBytes())); } catch (final Exception e) { throw new RuntimeException(e); } } public static String byteArrayToHexString(byte[] b){ StringBuffer sb = new StringBuffer(b.length * 2); for (int i = 0; i < b.length; i++){ int v = b[i] & 0xff; if (v < 16) { sb.append('0'); } sb.append(Integer.toHexString(v)); } return sb.toString().toUpperCase(); } protected static byte[] hexStringToByteArray(final String s) { byte[] b = new byte[s.length() / 2]; for (int i = 0; i < b.length; i++){ int index = i * 2; int v = Integer.parseInt(s.substring(index, index + 2), 16); b[i] = (byte)v; } return b; } public FlowExecutionKey getKey(final FlowExecution execution) { if (this.defaultBehavior) { return super.getKey(execution); } final CasFlowExecutionKey key = (CasFlowExecutionKey) execution.getKey(); if (key == null) { final Conversation conversation = beginConversation(execution); final ConversationId executionId = conversation.getId(); final Serializable nextSnapshotId = nextSnapshotId(executionId); final String unencryptedVersion = UUID.randomUUID().toString() + CasFlowExecutionKey.KEY_SEPARATOR + "e" + executionId + "s" + nextSnapshotId; final String encryptedVersion = encrypt(unencryptedVersion); return new CasFlowExecutionKey(executionId, nextSnapshotId, encryptedVersion); } else { if (getAlwaysGenerateNewNextKey()) { return new CompositeFlowExecutionKey(key.getExecutionId(), nextSnapshotId(key.getExecutionId())); } else { return execution.getKey(); } } } public FlowExecutionKey parseFlowExecutionKey(final String encodedKey) throws FlowExecutionRepositoryException { if (this.defaultBehavior) { return super.parseFlowExecutionKey(encodedKey); } if (!StringUtils.hasText(encodedKey)) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, "The string-encoded flow execution key is required"); } final String unencryptedVersion = decrypt(encodedKey); String[] keyParts = CasFlowExecutionKey.keyParts(unencryptedVersion); Serializable executionId = parseExecutionId(keyParts[0], encodedKey); Serializable snapshotId = parseSnapshotId(keyParts[1], encodedKey); return new CompositeFlowExecutionKey(executionId, snapshotId); } private ConversationId parseExecutionId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return this.conversationManager.parseConversationId(encodedId); } catch (ConversationException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } private Serializable parseSnapshotId(final String encodedId, final String encodedKey) throws BadlyFormattedFlowExecutionKeyException { try { return Integer.valueOf(encodedId); } catch (NumberFormatException e) { throw new BadlyFormattedFlowExecutionKeyException(encodedKey, CompositeFlowExecutionKey.getFormat(), e); } } /** * Copied from super-class since its marked as private. * @param execution * @return */ private Conversation beginConversation(FlowExecution execution) { ConversationParameters parameters = createConversationParameters(execution); Conversation conversation = this.conversationManager.beginConversation(parameters); return conversation; } public void setDefaultBehavior(final boolean defaultBehavior) { this.defaultBehavior = defaultBehavior; } }
CAS-958 fixed fact that generating a new key wasn't generating the correct class.
cas-server-3.4.2/cas-server-webapp/src/main/java/org/jasig/cas/web/flow/CasFlowExecutionKeyFactory.java
CAS-958
Java
apache-2.0
b7fa8cdc5fdc063e2b89660ed258d2d34e4eb49b
0
Hack23/cia,Hack23/cia,Hack23/cia,Hack23/cia
/* * Copyright 2014 James Pether Sรถrling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.systemintegrationtest; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runners.Parameterized.Parameters; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.hack23.cia.model.internal.application.data.impl.DataAgentOperation; import com.hack23.cia.model.internal.application.data.impl.DataAgentTarget; import com.hack23.cia.web.impl.ui.application.action.ViewAction; import com.hack23.cia.web.impl.ui.application.views.common.pagelinks.api.PageModeMenuCommand; import com.hack23.cia.web.impl.ui.application.views.common.viewnames.AdminViews; import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode; /** * The Class AdminRoleSystemTest. */ public final class AdminRoleSystemTest extends AbstractRoleSystemTest { /** The Constant NO_WEBDRIVER_EXIST_FOR_BROWSER. */ private static final String NO_WEBDRIVER_EXIST_FOR_BROWSER = "No webdriver exist for browser:"; /** * Instantiates a new admin role system test. * * @param browser * the browser */ public AdminRoleSystemTest(final String browser) { super(browser); } /** * Browsers strings. * * @return the collection */ @Parameters(name = "AdminRoleSiteTest{index}: browser({0})") public final static Collection<String[]> browsersStrings() { return Arrays.asList(new String[][] { { "chrome" } }); // return Arrays.asList(new Object[][] { { "firefox" },{ "chrome" }, { // "htmlunit-firefox" },{ "htmlunit-ie11" },{ "htmlunit-chrome" } }); } /** * Site admin agency test. * * @throws Exception * the exception */ @Test public void siteAdminAgencyTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_AGENCY_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Agency")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_AGENCY_VIEW_NAME, "")); } /** * Site admin portal test. * * @throws Exception * the exception */ @Test public void siteAdminPortalTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_PORTAL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Portal")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_PORTAL_VIEW_NAME, "")); } /** * Site admin application configuration test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationConfigurationTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit .visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Configuration")); clickFirstRowInGrid(userPageVisit); userPageVisit .validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); userPageVisit.updateConfigurationProperty("Update Configuration.propertyValue", String.valueOf(false)); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); } /** * Site admin country test. * * @throws Exception * the exception */ @Test public void siteAdminCountryTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_COUNTRY_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Country")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_COUNTRY_VIEW_NAME, "")); } /** * Site admin email test. * * @throws Exception * the exception */ @Test public void siteAdminEmailTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_EMAIL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("email")); userPageVisit.sendEmailOnEmailPage("[email protected]", "siteAdminEmailTest", "siteAdminEmailTest content"); userPageVisit.checkNotificationMessage("Email Sent"); } /** * Site admin email failed no valid email test. * * @throws Exception * the exception */ @Test public void siteAdminEmailFailedNoValidEmailTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_EMAIL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("email")); userPageVisit.sendEmailOnEmailPage("nonvalidemail", "siteAdminEmailFailedNoValidEmailTest", "siteAdminEmailFailedNoValidEmailTest content"); userPageVisit.checkNotificationMessage("Send email failedEmail is not a valid email address"); } /** * Site admin useraccount test. * * @throws Exception * the exception */ @Test public void siteAdminUseraccountTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Useraccount")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME, "")); } /** * Site admin language test. * * @throws Exception * the exception */ @Test public void siteAdminLanguageTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Language")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_VIEW_NAME, "")); } /** * Site admin language content test. * * @throws Exception * the exception */ @Test public void siteAdminLanguageContentTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_CONTENT_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Language Content")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_CONTENT_VIEW_NAME, "")); } /** * Site admin application session test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationSessionTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_SESSION_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Session")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_SESSION_VIEW_NAME, "")); } /** * Site admin application event test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationEventTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Action Event")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "")); } /** * Site admin application event charts test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationEventChartsTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, PageMode.CHARTS)); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Action Event chart")); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, PageMode.CHARTS)); } /** * Site admin monitoring failed access test. * * @throws Exception * the exception */ @Test(timeout = 20000) public void siteAdminMonitoringFailedAccessTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_MONITORING_VIEW_NAME, "")); assertTrue("Expect this content", userPageVisit.checkHtmlBodyContainsText("Access denided:adminmonitoring")); // assertTrue("Expect this content", // userPageVisit.getIframesHtmlBodyAsText().contains("Access // denided:adminmonitoring")); } /** * Site admin monitoring success test. * * @throws Exception * the exception */ @Test public void siteAdminMonitoringSuccessTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_MONITORING_VIEW_NAME, "")); assertTrue("Expect this content", userPageVisit.checkHtmlBodyContainsText("Admin Monitoring")); assertFalse("Dont expect this content", userPageVisit.getIframesHtmlBodyAsText().contains("Login with Username and Password")); } /** * Visit admin data summary view. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); } /** * Visit admin data summary view refresh views test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewRefreshViewsTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement refreshViewsButton =userPageVisit.findButton("Refresh Views"); assertNotNull("Expect to find a Refresh Views Button",refreshViewsButton); userPageVisit.performClickAction(refreshViewsButton); } /** * Visit admin data summary view remove politician test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewRemovePoliticianTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement removePoliticiansButton =userPageVisit.findButton("Remove Politicians"); assertNotNull("Expect to find a Button",removePoliticiansButton); userPageVisit.performClickAction(removePoliticiansButton); } /** * Visit admin data summary view remove documents test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewRemoveDocumentsTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement removeDocumentsButton =userPageVisit.findButton("Remove Documents"); assertNotNull("Expect to find a Button",removeDocumentsButton); userPageVisit.performClickAction(removeDocumentsButton); } /** * Visit admin data summary view remove application history test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewRemoveApplicationHistoryTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement removeApplicationHistoryButton =userPageVisit.findButton("Remove Application History"); assertNotNull("Expect to find a Button",removeApplicationHistoryButton); userPageVisit.performClickAction(removeApplicationHistoryButton); } /** * Visit admin data summary view update search index test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewUpdateSearchIndexTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement updateSearchIndexButton =userPageVisit.findButton("Update Search Index"); assertNotNull("Expect to find a Update Search Index Button",updateSearchIndexButton); userPageVisit.performClickAction(updateSearchIndexButton); } /** * Site admin test. * * @throws Exception * the exception */ @Test public void siteAdminAgentOperationTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_AGENT_OPERATIONVIEW_NAME, "")); userPageVisit.verifyViewActions(new ViewAction[] {ViewAction.VISIT_MAIN_VIEW,ViewAction.START_AGENT_BUTTON }); final List<String> actionIdsBy = userPageVisit.getActionIdsBy(ViewAction.START_AGENT_BUTTON); assertTrue(actionIdsBy.size() > 0); userPageVisit.performAdminAgentOperation(DataAgentTarget.MODEL_EXTERNAL_RIKSDAGEN, DataAgentOperation.IMPORT); } }
citizen-intelligence-agency/src/test/java/com/hack23/cia/systemintegrationtest/AdminRoleSystemTest.java
/* * Copyright 2014 James Pether Sรถrling * * 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. * * $Id$ * $HeadURL$ */ package com.hack23.cia.systemintegrationtest; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.junit.Test; import org.junit.runners.Parameterized.Parameters; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import com.hack23.cia.model.internal.application.data.impl.DataAgentOperation; import com.hack23.cia.model.internal.application.data.impl.DataAgentTarget; import com.hack23.cia.web.impl.ui.application.action.ViewAction; import com.hack23.cia.web.impl.ui.application.views.common.pagelinks.api.PageModeMenuCommand; import com.hack23.cia.web.impl.ui.application.views.common.viewnames.AdminViews; import com.hack23.cia.web.impl.ui.application.views.common.viewnames.PageMode; /** * The Class AdminRoleSystemTest. */ public final class AdminRoleSystemTest extends AbstractRoleSystemTest { /** The Constant NO_WEBDRIVER_EXIST_FOR_BROWSER. */ private static final String NO_WEBDRIVER_EXIST_FOR_BROWSER = "No webdriver exist for browser:"; /** * Instantiates a new admin role system test. * * @param browser * the browser */ public AdminRoleSystemTest(final String browser) { super(browser); } /** * Browsers strings. * * @return the collection */ @Parameters(name = "AdminRoleSiteTest{index}: browser({0})") public final static Collection<String[]> browsersStrings() { return Arrays.asList(new String[][] { { "chrome" } }); // return Arrays.asList(new Object[][] { { "firefox" },{ "chrome" }, { // "htmlunit-firefox" },{ "htmlunit-ie11" },{ "htmlunit-chrome" } }); } /** * Site admin agency test. * * @throws Exception * the exception */ @Test public void siteAdminAgencyTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_AGENCY_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Agency")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_AGENCY_VIEW_NAME, "")); } /** * Site admin portal test. * * @throws Exception * the exception */ @Test public void siteAdminPortalTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_PORTAL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Portal")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_PORTAL_VIEW_NAME, "")); } /** * Site admin application configuration test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationConfigurationTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit .visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Configuration")); clickFirstRowInGrid(userPageVisit); userPageVisit .validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); userPageVisit.updateConfigurationProperty("Update Configuration.propertyValue", String.valueOf(false)); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_CONFIGURATION_VIEW_NAME, "")); } /** * Site admin country test. * * @throws Exception * the exception */ @Test public void siteAdminCountryTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_COUNTRY_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Country")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_COUNTRY_VIEW_NAME, "")); } /** * Site admin email test. * * @throws Exception * the exception */ @Test public void siteAdminEmailTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_EMAIL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("email")); userPageVisit.sendEmailOnEmailPage("[email protected]", "siteAdminEmailTest", "siteAdminEmailTest content"); userPageVisit.checkNotificationMessage("Email Sent"); } /** * Site admin email failed no valid email test. * * @throws Exception * the exception */ @Test public void siteAdminEmailFailedNoValidEmailTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_EMAIL_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("email")); userPageVisit.sendEmailOnEmailPage("nonvalidemail", "siteAdminEmailFailedNoValidEmailTest", "siteAdminEmailFailedNoValidEmailTest content"); userPageVisit.checkNotificationMessage("Send email failedEmail is not a valid email address"); } /** * Site admin useraccount test. * * @throws Exception * the exception */ @Test public void siteAdminUseraccountTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Useraccount")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_USERACCOUNT_VIEW_NAME, "")); } /** * Site admin language test. * * @throws Exception * the exception */ @Test public void siteAdminLanguageTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Language")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_VIEW_NAME, "")); } /** * Site admin language content test. * * @throws Exception * the exception */ @Test public void siteAdminLanguageContentTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_CONTENT_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Language Content")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_LANGUAGE_CONTENT_VIEW_NAME, "")); } /** * Site admin application session test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationSessionTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_SESSION_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Session")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_SESSION_VIEW_NAME, "")); } /** * Site admin application event test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationEventTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "")); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Action Event")); clickFirstRowInGrid(userPageVisit); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, "")); } /** * Site admin application event charts test. * * @throws Exception * the exception */ @Test public void siteAdminApplicationEventChartsTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, PageMode.CHARTS)); assertTrue("Expect content",userPageVisit.checkHtmlBodyContainsText("Application Action Event chart")); userPageVisit.validatePage(new PageModeMenuCommand(AdminViews.ADMIN_APPLICATIONS_EVENTS_VIEW_NAME, PageMode.CHARTS)); } /** * Site admin monitoring failed access test. * * @throws Exception * the exception */ @Test(timeout = 20000) public void siteAdminMonitoringFailedAccessTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_MONITORING_VIEW_NAME, "")); assertTrue("Expect this content", userPageVisit.checkHtmlBodyContainsText("Access denided:adminmonitoring")); // assertTrue("Expect this content", // userPageVisit.getIframesHtmlBodyAsText().contains("Access // denided:adminmonitoring")); } /** * Site admin monitoring success test. * * @throws Exception * the exception */ @Test public void siteAdminMonitoringSuccessTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_MONITORING_VIEW_NAME, "")); assertTrue("Expect this content", userPageVisit.checkHtmlBodyContainsText("Admin Monitoring")); assertFalse("Dont expect this content", userPageVisit.getIframesHtmlBodyAsText().contains("Login with Username and Password")); } /** * Visit admin data summary view. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); } /** * Visit admin data summary view refresh views test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewRefreshViewsTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement refreshViewsButton =userPageVisit.findButton("Refresh Views"); assertNotNull("Expect to find a Refresh Views Button",refreshViewsButton); userPageVisit.performClickAction(refreshViewsButton); } /** * Visit admin data summary view update search index test. * * @throws Exception * the exception */ @Test public void visitAdminDataSummaryViewUpdateSearchIndexTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_DATA_SUMMARY_VIEW_NAME, "")); final WebElement updateSearchIndexButton =userPageVisit.findButton("Update Search Index"); assertNotNull("Expect to find a Update Search Index Button",updateSearchIndexButton); userPageVisit.performClickAction(updateSearchIndexButton); } /** * Site admin test. * * @throws Exception * the exception */ @Test public void siteAdminAgentOperationTest() throws Exception { final WebDriver driver = getWebDriver(); assertNotNull(NO_WEBDRIVER_EXIST_FOR_BROWSER + browser, driver); final UserPageVisit userPageVisit = new UserPageVisit(driver, browser); loginAsAdmin(userPageVisit); userPageVisit.visitDirectPage(new PageModeMenuCommand(AdminViews.ADMIN_AGENT_OPERATIONVIEW_NAME, "")); userPageVisit.verifyViewActions(new ViewAction[] {ViewAction.VISIT_MAIN_VIEW,ViewAction.START_AGENT_BUTTON }); final List<String> actionIdsBy = userPageVisit.getActionIdsBy(ViewAction.START_AGENT_BUTTON); assertTrue(actionIdsBy.size() > 0); userPageVisit.performAdminAgentOperation(DataAgentTarget.MODEL_EXTERNAL_RIKSDAGEN, DataAgentOperation.IMPORT); } }
remove data test start
citizen-intelligence-agency/src/test/java/com/hack23/cia/systemintegrationtest/AdminRoleSystemTest.java
remove data test start
Java
apache-2.0
2a90e8f5d6fad5fd58a64e90c69f8955949da18a
0
kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.security.ao; import no.kantega.commons.exception.SystemException; import no.kantega.publishing.api.services.security.PermissionAO; import no.kantega.publishing.common.Aksess; import no.kantega.publishing.common.ao.AssociationAO; import no.kantega.publishing.common.ao.MultimediaAO; import no.kantega.publishing.common.data.BaseObject; import no.kantega.publishing.common.data.enums.ObjectType; import no.kantega.publishing.common.util.database.dbConnectionFactory; import no.kantega.publishing.security.data.*; import no.kantega.publishing.security.data.enums.NotificationPriority; import no.kantega.publishing.security.data.enums.Privilege; import no.kantega.publishing.security.data.enums.RoleType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class PermissionsAOJDBCImpl extends NamedParameterJdbcDaoSupport implements PermissionAO { private static final Logger log = LoggerFactory.getLogger(PermissionsAOJDBCImpl.class); @Override @CacheEvict(value = "permissionCache", key = "#object.securityId") public void setPermissions(BaseObject object, List<Permission> permissions) throws SystemException { int securityId = object.getSecurityId(); try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st; log.debug( "Setting permissions for id: {}, securityId: {}", object.getId(), securityId); boolean setPermissionsFromParent = false; if (permissions != null && permissions.size() == 0) { setPermissionsFromParent = true; } if (object.getId() != -1 && (securityId != object.getId()) && setPermissionsFromParent) { // Brukeren har opprettet nye rettigheter, men ikke valgt noen: gjรธr ingenting return; } if (securityId == object.getId()) { // Slett gamle rettigheter st = c.prepareStatement("delete from objectpermissions where ObjectSecurityId = ? and ObjectType = ?"); st.setInt(1, securityId); st.setInt(2, object.getObjectType()); st.execute(); } st = c.prepareStatement("insert into objectpermissions values(?,?,?,?,?,?)"); // Sett inn nye rettigheter if (permissions != null) { for (Permission permission : permissions) { SecurityIdentifier sid = permission.getSecurityIdentifier(); st.setInt(1, object.getId()); st.setInt(2, object.getObjectType()); st.setInt(3, permission.getPrivilege()); st.setString(4, sid.getType()); st.setString(5, sid.getId()); st.setInt(6, permission.getNotificationPriority() != null ? permission.getNotificationPriority().getNotificationPriorityAsInt() : 0); st.execute(); } } else { // Legger inn default rettigheter, alle har aksess til alt st.setInt(1, object.getId()); st.setInt(2, object.getObjectType()); st.setInt(3, Privilege.FULL_CONTROL); st.setString(4, RoleType.ROLE); st.setString(5, Aksess.getEveryoneRole()); st.setInt(6, NotificationPriority.PRIORITY1.getNotificationPriorityAsInt()); st.execute(); } if (object.getId() != -1) { if (securityId != object.getId()) { // Setter nye rettigheter for disse sidene if (object.getObjectType() == ObjectType.ASSOCIATION) { AssociationAO.setSecurityId(c, object, false); } else if (object.getObjectType() == ObjectType.MULTIMEDIA) { MultimediaAO.setSecurityId(c, object, false); } } else if (setPermissionsFromParent) { if (object.getObjectType() == ObjectType.ASSOCIATION) { AssociationAO.setSecurityId(c, object, true); } else if (object.getObjectType() == ObjectType.MULTIMEDIA) { MultimediaAO.setSecurityId(c, object, true); } } } } catch (SQLException e) { throw new SystemException("SQL feil", e); } } @Override public List<ObjectPermissionsOverview> getPermissionsOverview(int objectType) throws SystemException { List<ObjectPermissionsOverview> overview = new ArrayList<>(); try (Connection c = dbConnectionFactory.getConnection()) { PreparedStatement st; if (objectType == ObjectType.MULTIMEDIA) { st = c.prepareStatement("select multimedia.Name as Name, objectpermissions.* from multimedia, objectpermissions where multimedia.Id = objectpermissions.ObjectSecurityId and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } else if (objectType == ObjectType.TOPICMAP) { st = c.prepareStatement("select tmmaps.Name as Name, objectpermissions.* from tmmaps, objectpermissions where tmmaps.Id = objectpermissions.ObjectSecurityId and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } else { st = c.prepareStatement("select contentversion.Title as Name, objectpermissions.* from content, contentversion, objectpermissions, associations where (contentversion.ContentId = content.ContentId) and (contentversion.IsActive = 1) and (content.contentId = associations.ContentId) and (associations.UniqueId = objectpermissions.ObjectSecurityId) and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } st.setInt(1, objectType); ResultSet rs = st.executeQuery(); List<Permission> permissions = new ArrayList<>(); int prev = -1; while(rs.next()) { String name = rs.getString("Name"); int id = rs.getInt("ObjectSecurityId"); if (id != prev) { ObjectPermissionsOverview opo = new ObjectPermissionsOverview(); opo.setName(name); permissions = new ArrayList<>(); opo.setPermissions(permissions); overview.add(opo); prev = id; } Permission p = new Permission(); p.setPrivilege(rs.getInt("Privilege")); SecurityIdentifier sid; String type = rs.getString("RoleType"); if(type.equals(RoleType.USER)) { sid = new User(); } else { sid = new Role(); } sid.setId(rs.getString("Role")); p.setSecurityIdentifier(sid); if (p.getPrivilege() >= Privilege.APPROVE_CONTENT) { NotificationPriority priority = NotificationPriority.getNotificationPriorityAsEnum(rs.getInt("NotificationPriority")); p.setNotificationPriority(priority); } permissions.add(p); } return overview; } catch (SQLException e) { throw new SystemException("SQL feil", e); } } @Override @Cacheable(value = "permissionCache", key = "#object.securityId") public List<Permission> getPermissions(BaseObject object) { return getJdbcTemplate().query("SELECT ObjectSecurityId, ObjectType, Privilege, RoleType, Role, NotificationPriority FROM objectpermissions where ObjectSecurityId = ?", rowMapper, object.getSecurityId()); } public final RowMapper<Permission> rowMapper = new RowMapper<Permission>() { @Override public Permission mapRow(ResultSet rs, int rowNum) throws SQLException { Permission permission = new Permission(); permission.setObjectSecurityId(rs.getInt("ObjectSecurityId")); permission.setObjectType(rs.getInt("ObjectType")); permission.setPrivilege(rs.getInt("Privilege")); String roleType = rs.getString("RoleType"); SecurityIdentifier identifier = roleType.equalsIgnoreCase(RoleType.USER) ? new User() : new Role(); identifier.setId(rs.getString("Role")); permission.setSecurityIdentifier(identifier); if (permission.getPrivilege() >= Privilege.APPROVE_CONTENT) { NotificationPriority priority = NotificationPriority.getNotificationPriorityAsEnum(rs.getInt("NotificationPriority")); permission.setNotificationPriority(priority); } return permission; } }; }
modules/core/src/java/no/kantega/publishing/security/ao/PermissionsAOJDBCImpl.java
/* * Copyright 2009 Kantega AS * * 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 no.kantega.publishing.security.ao; import no.kantega.commons.exception.SystemException; import no.kantega.publishing.api.services.security.PermissionAO; import no.kantega.publishing.common.Aksess; import no.kantega.publishing.common.ao.AssociationAO; import no.kantega.publishing.common.ao.MultimediaAO; import no.kantega.publishing.common.data.BaseObject; import no.kantega.publishing.common.data.enums.ObjectType; import no.kantega.publishing.common.util.database.dbConnectionFactory; import no.kantega.publishing.security.data.*; import no.kantega.publishing.security.data.enums.NotificationPriority; import no.kantega.publishing.security.data.enums.Privilege; import no.kantega.publishing.security.data.enums.RoleType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class PermissionsAOJDBCImpl extends NamedParameterJdbcDaoSupport implements PermissionAO { private static final Logger log = LoggerFactory.getLogger(PermissionsAOJDBCImpl.class); @Override @CacheEvict(value = "permissionCache", key = "#object.securityId") public void setPermissions(BaseObject object, List<Permission> permissions) throws SystemException { int securityId = object.getSecurityId(); try (Connection c = dbConnectionFactory.getConnection()){ PreparedStatement st; log.debug( "Setting permissions for id: {}, securityId: {}", object.getId(), securityId); boolean setPermissionsFromParent = false; if (permissions != null && permissions.size() == 0) { setPermissionsFromParent = true; } if (object.getId() != -1 && (securityId != object.getId()) && setPermissionsFromParent) { // Brukeren har opprettet nye rettigheter, men ikke valgt noen: gjรธr ingenting return; } if (securityId == object.getId()) { // Slett gamle rettigheter st = c.prepareStatement("delete from objectpermissions where ObjectSecurityId = ? and ObjectType = ?"); st.setInt(1, securityId); st.setInt(2, object.getObjectType()); st.execute(); } st = c.prepareStatement("insert into objectpermissions values(?,?,?,?,?,?)"); // Sett inn nye rettigheter if (permissions != null) { for (Permission permission : permissions) { SecurityIdentifier sid = permission.getSecurityIdentifier(); st.setInt(1, object.getId()); st.setInt(2, object.getObjectType()); st.setInt(3, permission.getPrivilege()); st.setString(4, sid.getType()); st.setString(5, sid.getId()); st.setInt(6, permission.getNotificationPriority() != null ? permission.getNotificationPriority().getNotificationPriorityAsInt() : 0); st.execute(); } } else { // Legger inn default rettigheter, alle har aksess til alt st.setInt(1, object.getId()); st.setInt(2, object.getObjectType()); st.setInt(3, Privilege.FULL_CONTROL); st.setString(4, RoleType.ROLE); st.setString(5, Aksess.getEveryoneRole()); st.setInt(6, NotificationPriority.PRIORITY1.getNotificationPriorityAsInt()); st.execute(); } if (object.getId() != -1) { if (securityId != object.getId()) { // Setter nye rettigheter for disse sidene if (object.getObjectType() == ObjectType.ASSOCIATION) { AssociationAO.setSecurityId(c, object, false); } else if (object.getObjectType() == ObjectType.MULTIMEDIA) { MultimediaAO.setSecurityId(c, object, false); } } else if (setPermissionsFromParent) { if (object.getObjectType() == ObjectType.ASSOCIATION) { AssociationAO.setSecurityId(c, object, true); } else if (object.getObjectType() == ObjectType.MULTIMEDIA) { MultimediaAO.setSecurityId(c, object, true); } } } } catch (SQLException e) { throw new SystemException("SQL feil", e); } } @Override public List<ObjectPermissionsOverview> getPermissionsOverview(int objectType) throws SystemException { List<ObjectPermissionsOverview> overview = new ArrayList<>(); try (Connection c = dbConnectionFactory.getConnection()) { PreparedStatement st; if (objectType == ObjectType.MULTIMEDIA) { st = c.prepareStatement("select multimedia.Name as Name, objectpermissions.* from multimedia, objectpermissions where multimedia.Id = objectpermissions.ObjectSecurityId and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } else if (objectType == ObjectType.TOPICMAP) { st = c.prepareStatement("select tmmaps.Name as Name, objectpermissions.* from tmmaps, objectpermissions where tmmaps.Id = objectpermissions.ObjectSecurityId and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } else { st = c.prepareStatement("select contentversion.Title as Name, objectpermissions.* from content, contentversion, objectpermissions, associations where (contentversion.ContentId = content.ContentId) and (contentversion.IsActive = 1) and (content.contentId = associations.ContentId) and (associations.UniqueId = objectpermissions.ObjectSecurityId) and objectpermissions.ObjectType = ? order by Name, ObjectSecurityId, Role"); } st.setInt(1, objectType); ResultSet rs = st.executeQuery(); List<Permission> permissions = new ArrayList<>(); int prev = -1; while(rs.next()) { String name = rs.getString("Name"); int id = rs.getInt("ObjectSecurityId"); if (id != prev) { ObjectPermissionsOverview opo = new ObjectPermissionsOverview(); opo.setName(name); permissions = new ArrayList<>(); opo.setPermissions(permissions); overview.add(opo); prev = id; } Permission p = new Permission(); p.setPrivilege(rs.getInt("Privilege")); SecurityIdentifier sid; String type = rs.getString("RoleType"); if(type.equals(RoleType.USER)) { sid = new User(); } else { sid = new Role(); } sid.setId(rs.getString("Role")); p.setSecurityIdentifier(sid); if (p.getPrivilege() >= Privilege.APPROVE_CONTENT) { NotificationPriority priority = NotificationPriority.getNotificationPriorityAsEnum(rs.getInt("NotificationPriority")); p.setNotificationPriority(priority); } permissions.add(p); } return overview; } catch (SQLException e) { throw new SystemException("SQL feil", e); } } @Override @Cacheable(value = "permissionCache", key = "#object.securityId") public List<Permission> getPermissions(BaseObject object) { return getJdbcTemplate().query("SELECT ObjectSecurityId, ObjectType, Privilege, RoleType, Role, NotificationPriority FROM objectpermissions where ObjectSecurityId = ?", rowMapper, object.getId()); } public final RowMapper<Permission> rowMapper = new RowMapper<Permission>() { @Override public Permission mapRow(ResultSet rs, int rowNum) throws SQLException { Permission permission = new Permission(); permission.setObjectSecurityId(rs.getInt("ObjectSecurityId")); permission.setObjectType(rs.getInt("ObjectType")); permission.setPrivilege(rs.getInt("Privilege")); String roleType = rs.getString("RoleType"); SecurityIdentifier identifier = roleType.equalsIgnoreCase(RoleType.USER) ? new User() : new Role(); identifier.setId(rs.getString("Role")); permission.setSecurityIdentifier(identifier); if (permission.getPrivilege() >= Privilege.APPROVE_CONTENT) { NotificationPriority priority = NotificationPriority.getNotificationPriorityAsEnum(rs.getInt("NotificationPriority")); permission.setNotificationPriority(priority); } return permission; } }; }
AP-1666: PermissionsAO returns wrong permissions for pages git-svn-id: 8def386c603904b39326d3fc08add479b8279298@4846 fd808399-8219-4f14-9d4c-37719d9ec93d
modules/core/src/java/no/kantega/publishing/security/ao/PermissionsAOJDBCImpl.java
AP-1666: PermissionsAO returns wrong permissions for pages
Java
apache-2.0
950acbe9b3730f3a2f65bfc7b10169088d778960
0
MovingBlocks/Terasology,Nanoware/Terasology,Nanoware/Terasology,MovingBlocks/Terasology,MovingBlocks/Terasology,Nanoware/Terasology
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.rendering.world; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.joml.Math; import org.joml.Vector3f; import org.joml.Vector3fc; import org.joml.Vector3i; import org.joml.Vector3ic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.engine.config.Config; import org.terasology.engine.config.RenderingConfig; import org.terasology.engine.context.Context; import org.terasology.engine.core.GameScheduler; import org.terasology.engine.monitoring.PerformanceMonitor; import org.terasology.engine.monitoring.chunk.ChunkMonitor; import org.terasology.engine.registry.CoreRegistry; import org.terasology.engine.rendering.cameras.Camera; import org.terasology.engine.rendering.logic.ChunkMeshRenderer; import org.terasology.engine.rendering.primitives.ChunkMesh; import org.terasology.engine.rendering.primitives.ChunkTessellator; import org.terasology.engine.rendering.world.viewDistance.ViewDistance; import org.terasology.engine.world.ChunkView; import org.terasology.engine.world.WorldProvider; import org.terasology.engine.world.block.BlockRegion; import org.terasology.engine.world.chunks.Chunk; import org.terasology.engine.world.chunks.ChunkProvider; import org.terasology.engine.world.chunks.Chunks; import org.terasology.engine.world.chunks.LodChunkProvider; import org.terasology.engine.world.chunks.RenderableChunk; import org.terasology.engine.world.generator.ScalableWorldGenerator; import org.terasology.engine.world.generator.WorldGenerator; import org.terasology.joml.geom.AABBfc; import reactor.core.publisher.Sinks; import reactor.function.TupleUtils; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; /** * TODO: write javadoc unless this class gets slated for removal, which might be. */ class RenderableWorldImpl implements RenderableWorld { private static final Logger logger = LoggerFactory.getLogger(RenderableWorldImpl.class); private static final int MAX_ANIMATED_CHUNKS = 64; private static final int MAX_LOADABLE_CHUNKS = ViewDistance.MEGA.getChunkDistance().x() * ViewDistance.MEGA.getChunkDistance().y() * ViewDistance.MEGA.getChunkDistance().z(); private static final Vector3fc CHUNK_CENTER_OFFSET = new Vector3f(Chunks.CHUNK_SIZE).div(2); private final int maxChunksForShadows; private final WorldProvider worldProvider; private final ChunkProvider chunkProvider; private final LodChunkProvider lodChunkProvider; private final ChunkTessellator chunkTessellator; private final List<Chunk> chunksInProximityOfCamera = Lists.newArrayListWithCapacity(MAX_LOADABLE_CHUNKS); private BlockRegion renderableRegion = new BlockRegion(BlockRegion.INVALID); private ViewDistance currentViewDistance; private final RenderQueuesHelper renderQueues; private ChunkMeshRenderer chunkMeshRenderer; private final Camera playerCamera; private Camera shadowMapCamera; private final Config config; private final RenderingConfig renderingConfig; private int statDirtyChunks; private int statVisibleChunks; private int statIgnoredPhases; private final Set<Vector3ic> chunkMeshProcessing = Sets.newConcurrentHashSet(); private final Sinks.Many<Chunk> chunkMeshPublisher = Sinks.many().unicast().onBackpressureBuffer(); RenderableWorldImpl(Context context, Camera playerCamera) { this.worldProvider = context.get(WorldProvider.class); this.chunkProvider = context.get(ChunkProvider.class); this.chunkTessellator = context.get(ChunkTessellator.class); this.config = context.get(Config.class); this.renderingConfig = config.getRendering(); this.maxChunksForShadows = Math.clamp(config.getRendering().getMaxChunksUsedForShadowMapping(), 64, 1024); this.playerCamera = playerCamera; WorldGenerator worldGenerator = context.get(WorldGenerator.class); if (worldGenerator instanceof ScalableWorldGenerator) { lodChunkProvider = new LodChunkProvider(context, (ScalableWorldGenerator) worldGenerator, chunkTessellator, renderingConfig.getViewDistance(), (int) renderingConfig.getChunkLods(), calcCameraCoordinatesInChunkUnits()); } else { lodChunkProvider = null; } renderQueues = new RenderQueuesHelper(new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkBackToFrontComparator())); chunkMeshPublisher.asFlux() .distinct(Chunk::getPosition, () -> chunkMeshProcessing) .doOnNext(k -> k.setDirty(false)) .parallel(5).runOn(GameScheduler.parallel()) .<Optional<Tuple2<Chunk, ChunkMesh>>>map(c -> { ChunkView chunkView = worldProvider.getLocalView(c.getPosition()); if (chunkView != null && chunkView.isValidView() && chunkMeshProcessing.remove(c.getPosition())) { ChunkMesh newMesh = chunkTessellator.generateMesh(chunkView); ChunkMonitor.fireChunkTessellated(new Vector3i(c.getPosition()), newMesh); return Optional.of(Tuples.of(c, newMesh)); } return Optional.empty(); }).filter(Optional::isPresent).sequential() .publishOn(GameScheduler.gameMain()) .subscribe(result -> result.ifPresent(TupleUtils.consumer((chunk, chunkMesh) -> { if (chunksInProximityOfCamera.contains(chunk)) { chunkMesh.generateVBOs(); chunkMesh.discardData(); if (chunk.hasMesh()) { chunk.getMesh().dispose(); } chunk.setMesh(chunkMesh); } })), throwable -> logger.error("Failed to build mesh {}", throwable)); } @Override public void onChunkLoaded(Vector3ic chunkCoordinates) { if (renderableRegion.contains(chunkCoordinates)) { Chunk chunk = chunkProvider.getChunk(chunkCoordinates); if (chunk != null) { chunksInProximityOfCamera.add(chunk); chunksInProximityOfCamera.sort(new ChunkFrontToBackComparator()); if (lodChunkProvider != null) { lodChunkProvider.onRealChunkLoaded(chunkCoordinates); } } else { logger.warn("Warning: onChunkLoaded called for a null chunk!"); } } for (Vector3ic pos : new BlockRegion(chunkCoordinates).expand(1, 1, 1)) { Chunk chunk = chunkProvider.getChunk(pos); if (chunk != null) { chunk.setDirty(true); } } } @Override public void onChunkUnloaded(Vector3ic chunkCoordinates) { chunkMeshProcessing.remove(chunkCoordinates); if (renderableRegion.contains(chunkCoordinates)) { Chunk chunk; Iterator<Chunk> iterator = chunksInProximityOfCamera.iterator(); while (iterator.hasNext()) { chunk = iterator.next(); if (chunk.getPosition().equals(chunkCoordinates)) { chunk.disposeMesh(); iterator.remove(); break; } } } if (lodChunkProvider != null) { lodChunkProvider.onRealChunkUnloaded(chunkCoordinates); } } /** * @return true if pregeneration is complete */ @Override public boolean pregenerateChunks() { boolean pregenerationIsComplete = true; chunkProvider.update(); Chunk chunk; ChunkMesh newMesh; ChunkView localView; for (Vector3ic chunkCoordinates : calculateRenderableRegion(renderingConfig.getViewDistance())) { chunk = chunkProvider.getChunk(chunkCoordinates); if (chunk == null) { pregenerationIsComplete = false; } else if (chunk.isDirty()) { localView = worldProvider.getLocalView(chunkCoordinates); if (localView == null) { continue; } chunk.setDirty(false); newMesh = chunkTessellator.generateMesh(localView); newMesh.generateVBOs(); newMesh.discardData(); if (chunk.hasMesh()) { chunk.getMesh().dispose(); } chunk.setMesh(newMesh); pregenerationIsComplete = false; break; } } return pregenerationIsComplete; } @Override public void update() { PerformanceMonitor.startActivity("Update Lighting"); worldProvider.processPropagation(); PerformanceMonitor.endActivity(); PerformanceMonitor.startActivity("Chunk update"); chunkProvider.update(); PerformanceMonitor.endActivity(); PerformanceMonitor.startActivity("Update Close Chunks"); updateChunksInProximity(calculateRenderableRegion(renderingConfig.getViewDistance())); PerformanceMonitor.endActivity(); if (lodChunkProvider != null) { PerformanceMonitor.startActivity("Update LOD Chunks"); lodChunkProvider.update(calcCameraCoordinatesInChunkUnits()); PerformanceMonitor.endActivity(); } } /** * Updates the list of chunks around the player. * * @return True if the list was changed */ @Override public boolean updateChunksInProximity(BlockRegion newRenderableRegion) { if (!newRenderableRegion.equals(renderableRegion)) { Chunk chunk; for (Vector3ic chunkPositionToRemove : renderableRegion) { if (!newRenderableRegion.contains(chunkPositionToRemove)) { Iterator<Chunk> nearbyChunks = chunksInProximityOfCamera.iterator(); while (nearbyChunks.hasNext()) { chunk = nearbyChunks.next(); if (chunk.getPosition().equals(chunkPositionToRemove)) { chunk.disposeMesh(); nearbyChunks.remove(); break; } } } } boolean chunksHaveBeenAdded = false; for (Vector3ic chunkPositionToAdd : newRenderableRegion) { if (!renderableRegion.contains(chunkPositionToAdd)) { chunk = chunkProvider.getChunk(chunkPositionToAdd); if (chunk != null) { chunksInProximityOfCamera.add(chunk); chunksHaveBeenAdded = true; } } } if (chunksHaveBeenAdded) { chunksInProximityOfCamera.sort(new ChunkFrontToBackComparator()); } renderableRegion = newRenderableRegion; return true; } return false; } @Override public boolean updateChunksInProximity(ViewDistance newViewDistance, int chunkLods) { if (newViewDistance != currentViewDistance || (lodChunkProvider != null && chunkLods != lodChunkProvider.getChunkLods())) { logger.info("New Viewing Distance: {}", newViewDistance); currentViewDistance = newViewDistance; if (lodChunkProvider != null) { lodChunkProvider.updateRenderableRegion(newViewDistance, chunkLods, calcCameraCoordinatesInChunkUnits()); } return updateChunksInProximity(calculateRenderableRegion(newViewDistance)); } else { return false; } } private BlockRegion calculateRenderableRegion(ViewDistance newViewDistance) { Vector3i cameraCoordinates = calcCameraCoordinatesInChunkUnits(); Vector3ic renderableRegionSize = newViewDistance.getChunkDistance(); Vector3i renderableRegionExtents = new Vector3i(renderableRegionSize.x() / 2, renderableRegionSize.y() / 2, renderableRegionSize.z() / 2); return new BlockRegion(cameraCoordinates).expand(renderableRegionExtents); } /** * Chunk position of the player. * * @return The player offset chunk */ private Vector3i calcCameraCoordinatesInChunkUnits() { Vector3f cameraCoordinates = playerCamera.getPosition(); return Chunks.toChunkPos(cameraCoordinates, new Vector3i()); } /** * Updates the currently visible chunks (in sight of the player). */ @Override public int queueVisibleChunks(boolean isFirstRenderingStageForCurrentFrame) { PerformanceMonitor.startActivity("Queueing Visible Chunks"); statDirtyChunks = 0; statVisibleChunks = 0; statIgnoredPhases = 0; int chunkCounter = 0; renderQueues.clear(); ChunkMesh mesh; boolean isDynamicShadows = renderingConfig.isDynamicShadows(); int billboardLimit = (int) renderingConfig.getBillboardLimit(); List<RenderableChunk> allChunks = new ArrayList<>(chunksInProximityOfCamera); allChunks.addAll(chunkMeshRenderer.getRenderableChunks()); if (lodChunkProvider != null) { lodChunkProvider.addAllChunks(allChunks); } for (RenderableChunk chunk : allChunks) { if (isChunkValidForRender(chunk)) { mesh = chunk.getMesh(); if (isDynamicShadows && isFirstRenderingStageForCurrentFrame && chunkCounter < maxChunksForShadows && isChunkVisibleFromMainLight(chunk)) { if (triangleCount(mesh, ChunkMesh.RenderPhase.OPAQUE) > 0) { renderQueues.chunksOpaqueShadow.add(chunk); } else { statIgnoredPhases++; } } if (isChunkVisible(chunk)) { if (triangleCount(mesh, ChunkMesh.RenderPhase.OPAQUE) > 0) { renderQueues.chunksOpaque.add(chunk); } else { statIgnoredPhases++; } if (triangleCount(mesh, ChunkMesh.RenderPhase.REFRACTIVE) > 0) { renderQueues.chunksAlphaBlend.add(chunk); } else { statIgnoredPhases++; } if (triangleCount(mesh, ChunkMesh.RenderPhase.ALPHA_REJECT) > 0 && (billboardLimit == 0 || chunkCounter < billboardLimit)) { renderQueues.chunksAlphaReject.add(chunk); } else { statIgnoredPhases++; } statVisibleChunks++; chunk.setAnimated(statVisibleChunks < MAX_ANIMATED_CHUNKS); } if (isChunkVisibleReflection(chunk)) { renderQueues.chunksOpaqueReflection.add(chunk); } } chunkCounter++; } if (isFirstRenderingStageForCurrentFrame) { for (Chunk chunk : chunksInProximityOfCamera) { if (isChunkValidForRender(chunk) && chunk.isDirty()) { statDirtyChunks++; Sinks.EmitResult result = chunkMeshPublisher.tryEmitNext(chunk); if (result.isFailure()) { logger.error("failed to process chunk {} : {}", chunk, result); } } } } PerformanceMonitor.endActivity(); return chunkMeshProcessing.size(); } private int triangleCount(ChunkMesh mesh, ChunkMesh.RenderPhase renderPhase) { if (mesh != null) { return mesh.triangleCount(renderPhase); } else { return 0; } } @Override public void dispose() { if (lodChunkProvider != null) { lodChunkProvider.shutdown(); } } private boolean isChunkValidForRender(RenderableChunk chunk) { return chunk.isReady(); } private boolean isChunkVisibleFromMainLight(RenderableChunk chunk) { //TODO: need to work out better scheme for shadowMapCamera if (shadowMapCamera == null) { return false; } return isChunkVisible(shadowMapCamera, chunk); //TODO: find an elegant way } private boolean isChunkVisible(RenderableChunk chunk) { return isChunkVisible(playerCamera, chunk); } private boolean isChunkVisible(Camera camera, RenderableChunk chunk) { return camera.hasInSight(chunk.getAABB()); } private boolean isChunkVisibleReflection(RenderableChunk chunk) { AABBfc bounds = chunk.getAABB(); return playerCamera.getViewFrustumReflected().testAab(bounds.minX(), bounds.minY(), bounds.minZ(), bounds.maxX(), bounds.maxY(), bounds.maxZ()); } @Override public RenderQueuesHelper getRenderQueues() { return renderQueues; } @Override public ChunkProvider getChunkProvider() { return chunkProvider; } @Override public void setShadowMapCamera(Camera camera) { this.shadowMapCamera = camera; } @Override public void setChunkMeshRenderer(ChunkMeshRenderer meshes) { chunkMeshRenderer = meshes; } @Override public String getMetrics() { String stringToReturn = ""; stringToReturn += "Dirty Chunks: "; stringToReturn += statDirtyChunks; stringToReturn += "\n"; stringToReturn += "Ignored Phases: "; stringToReturn += statIgnoredPhases; stringToReturn += "\n"; stringToReturn += "Visible Chunks: "; stringToReturn += statVisibleChunks; stringToReturn += "\n"; return stringToReturn; } private static float squaredDistanceToCamera(RenderableChunk chunk, Vector3f cameraPosition) { // For performance reasons, to avoid instantiating too many vectors in a frequently called method, // comments are in use instead of appropriately named vectors. Vector3f result = chunk.getRenderPosition(); result.add(CHUNK_CENTER_OFFSET); result.sub(cameraPosition); // camera to chunk vector return result.lengthSquared(); } // TODO: find the right place to check if the activeCamera has changed, // TODO: so that the comparators can hold an up-to-date reference to it // TODO: and avoid having to find it on a per-comparison basis. private static class ChunkFrontToBackComparator implements Comparator<RenderableChunk> { @Override public int compare(RenderableChunk chunk1, RenderableChunk chunk2) { Preconditions.checkNotNull(chunk1); Preconditions.checkNotNull(chunk2); Vector3f cameraPosition = CoreRegistry.get(WorldRenderer.class).getActiveCamera().getPosition(); double distance1 = squaredDistanceToCamera(chunk1, cameraPosition); double distance2 = squaredDistanceToCamera(chunk2, cameraPosition); // Using Double.compare as simple d1 < d2 comparison is flagged as problematic by Jenkins // On the other hand Double.compare can return any positive/negative value apparently, // hence the need for Math.signum(). return (int) Math.signum(Double.compare(distance1, distance2)); } } private static class ChunkBackToFrontComparator implements Comparator<RenderableChunk> { @Override public int compare(RenderableChunk chunk1, RenderableChunk chunk2) { Preconditions.checkNotNull(chunk1); Preconditions.checkNotNull(chunk2); Vector3f cameraPosition = CoreRegistry.get(WorldRenderer.class).getActiveCamera().getPosition(); double distance1 = squaredDistanceToCamera(chunk1, cameraPosition); double distance2 = squaredDistanceToCamera(chunk2, cameraPosition); return Double.compare(distance2, distance1); } } }
engine/src/main/java/org/terasology/engine/rendering/world/RenderableWorldImpl.java
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.rendering.world; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.joml.Math; import org.joml.Vector3f; import org.joml.Vector3fc; import org.joml.Vector3i; import org.joml.Vector3ic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.engine.config.Config; import org.terasology.engine.config.RenderingConfig; import org.terasology.engine.context.Context; import org.terasology.engine.core.GameScheduler; import org.terasology.engine.monitoring.PerformanceMonitor; import org.terasology.engine.monitoring.chunk.ChunkMonitor; import org.terasology.engine.registry.CoreRegistry; import org.terasology.engine.rendering.cameras.Camera; import org.terasology.engine.rendering.logic.ChunkMeshRenderer; import org.terasology.engine.rendering.primitives.ChunkMesh; import org.terasology.engine.rendering.primitives.ChunkTessellator; import org.terasology.engine.rendering.world.viewDistance.ViewDistance; import org.terasology.engine.world.ChunkView; import org.terasology.engine.world.WorldProvider; import org.terasology.engine.world.block.BlockRegion; import org.terasology.engine.world.chunks.Chunk; import org.terasology.engine.world.chunks.ChunkProvider; import org.terasology.engine.world.chunks.Chunks; import org.terasology.engine.world.chunks.LodChunkProvider; import org.terasology.engine.world.chunks.RenderableChunk; import org.terasology.engine.world.generator.ScalableWorldGenerator; import org.terasology.engine.world.generator.WorldGenerator; import org.terasology.joml.geom.AABBfc; import reactor.core.publisher.Sinks; import reactor.function.TupleUtils; import reactor.util.function.Tuple2; import reactor.util.function.Tuples; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.PriorityQueue; import java.util.Set; /** * TODO: write javadoc unless this class gets slated for removal, which might be. */ class RenderableWorldImpl implements RenderableWorld { private static final Logger logger = LoggerFactory.getLogger(RenderableWorldImpl.class); private static final int MAX_ANIMATED_CHUNKS = 64; private static final int MAX_LOADABLE_CHUNKS = ViewDistance.MEGA.getChunkDistance().x() * ViewDistance.MEGA.getChunkDistance().y() * ViewDistance.MEGA.getChunkDistance().z(); private static final Vector3fc CHUNK_CENTER_OFFSET = new Vector3f(Chunks.CHUNK_SIZE).div(2); private final int maxChunksForShadows; private final WorldProvider worldProvider; private final ChunkProvider chunkProvider; private final LodChunkProvider lodChunkProvider; private final ChunkTessellator chunkTessellator; private final List<Chunk> chunksInProximityOfCamera = Lists.newArrayListWithCapacity(MAX_LOADABLE_CHUNKS); private BlockRegion renderableRegion = new BlockRegion(BlockRegion.INVALID); private ViewDistance currentViewDistance; private final RenderQueuesHelper renderQueues; private ChunkMeshRenderer chunkMeshRenderer; private final Camera playerCamera; private Camera shadowMapCamera; private final Config config; private final RenderingConfig renderingConfig; private int statDirtyChunks; private int statVisibleChunks; private int statIgnoredPhases; private final Set<Vector3ic> chunkMeshProcessing = Sets.newConcurrentHashSet(); private final Sinks.Many<Chunk> chunkMeshPublisher = Sinks.many().unicast().onBackpressureBuffer(); RenderableWorldImpl(Context context, Camera playerCamera) { this.worldProvider = context.get(WorldProvider.class); this.chunkProvider = context.get(ChunkProvider.class); this.chunkTessellator = context.get(ChunkTessellator.class); this.config = context.get(Config.class); this.renderingConfig = config.getRendering(); this.maxChunksForShadows = Math.clamp(config.getRendering().getMaxChunksUsedForShadowMapping(), 64, 1024); this.playerCamera = playerCamera; WorldGenerator worldGenerator = context.get(WorldGenerator.class); if (worldGenerator instanceof ScalableWorldGenerator) { lodChunkProvider = new LodChunkProvider(context, (ScalableWorldGenerator) worldGenerator, chunkTessellator, renderingConfig.getViewDistance(), (int) renderingConfig.getChunkLods(), calcCameraCoordinatesInChunkUnits()); } else { lodChunkProvider = null; } renderQueues = new RenderQueuesHelper(new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkFrontToBackComparator()), new PriorityQueue<>(MAX_LOADABLE_CHUNKS, new ChunkBackToFrontComparator())); chunkMeshPublisher.asFlux() .distinct(Chunk::getPosition, () -> chunkMeshProcessing) .doOnNext(k -> k.setDirty(false)) .parallel(5).runOn(GameScheduler.parallel()) .<Optional<Tuple2<Chunk, ChunkMesh>>>map(c -> { ChunkView chunkView = worldProvider.getLocalView(c.getPosition()); if (chunkView != null && chunkView.isValidView() && chunkMeshProcessing.remove(c.getPosition())) { ChunkMesh newMesh = chunkTessellator.generateMesh(chunkView); ChunkMonitor.fireChunkTessellated(new Vector3i(c.getPosition()), newMesh); return Optional.of(Tuples.of(c, newMesh)); } return Optional.empty(); }).filter(Optional::isPresent).sequential() .publishOn(GameScheduler.gameMain()) .subscribe(result -> result.ifPresent(TupleUtils.consumer((chunk, chunkMesh) -> { if (chunksInProximityOfCamera.contains(chunk)) { chunkMesh.generateVBOs(); chunkMesh.discardData(); if (chunk.hasMesh()) { chunk.getMesh().dispose(); } chunk.setMesh(chunkMesh); } })), throwable -> logger.error("Failed to build mesh {}", throwable)); } @Override public void onChunkLoaded(Vector3ic chunkCoordinates) { if (renderableRegion.contains(chunkCoordinates)) { Chunk chunk = chunkProvider.getChunk(chunkCoordinates); if (chunk != null) { chunksInProximityOfCamera.add(chunk); chunksInProximityOfCamera.sort(new ChunkFrontToBackComparator()); if (lodChunkProvider != null) { lodChunkProvider.onRealChunkLoaded(chunkCoordinates); } } else { logger.warn("Warning: onChunkLoaded called for a null chunk!"); } } for (Vector3ic pos : new BlockRegion(chunkCoordinates).expand(1, 1, 1)) { Chunk chunk = chunkProvider.getChunk(pos); if (chunk != null) { chunk.setDirty(true); } } } @Override public void onChunkUnloaded(Vector3ic chunkCoordinates) { chunkMeshProcessing.remove(chunkCoordinates); if (renderableRegion.contains(chunkCoordinates)) { Chunk chunk; Iterator<Chunk> iterator = chunksInProximityOfCamera.iterator(); while (iterator.hasNext()) { chunk = iterator.next(); if (chunk.getPosition().equals(chunkCoordinates)) { chunk.disposeMesh(); iterator.remove(); break; } } } if (lodChunkProvider != null) { lodChunkProvider.onRealChunkUnloaded(chunkCoordinates); } } /** * @return true if pregeneration is complete */ @Override public boolean pregenerateChunks() { boolean pregenerationIsComplete = true; chunkProvider.update(); Chunk chunk; ChunkMesh newMesh; ChunkView localView; for (Vector3ic chunkCoordinates : calculateRenderableRegion(renderingConfig.getViewDistance())) { chunk = chunkProvider.getChunk(chunkCoordinates); if (chunk == null) { pregenerationIsComplete = false; } else if (chunk.isDirty()) { localView = worldProvider.getLocalView(chunkCoordinates); if (localView == null) { continue; } chunk.setDirty(false); newMesh = chunkTessellator.generateMesh(localView); newMesh.generateVBOs(); newMesh.discardData(); if (chunk.hasMesh()) { chunk.getMesh().dispose(); } chunk.setMesh(newMesh); pregenerationIsComplete = false; break; } } return pregenerationIsComplete; } @Override public void update() { PerformanceMonitor.startActivity("Update Lighting"); worldProvider.processPropagation(); PerformanceMonitor.endActivity(); PerformanceMonitor.startActivity("Chunk update"); chunkProvider.update(); PerformanceMonitor.endActivity(); PerformanceMonitor.startActivity("Update Close Chunks"); updateChunksInProximity(calculateRenderableRegion(renderingConfig.getViewDistance())); PerformanceMonitor.endActivity(); if (lodChunkProvider != null) { PerformanceMonitor.startActivity("Update LOD Chunks"); lodChunkProvider.update(calcCameraCoordinatesInChunkUnits()); PerformanceMonitor.endActivity(); } } /** * Updates the list of chunks around the player. * * @return True if the list was changed */ @Override public boolean updateChunksInProximity(BlockRegion newRenderableRegion) { if (!newRenderableRegion.equals(renderableRegion)) { Chunk chunk; for (Vector3ic chunkPositionToRemove : renderableRegion) { if (!newRenderableRegion.contains(chunkPositionToRemove)) { Iterator<Chunk> nearbyChunks = chunksInProximityOfCamera.iterator(); while (nearbyChunks.hasNext()) { chunk = nearbyChunks.next(); if (chunk.getPosition().equals(chunkPositionToRemove)) { chunk.disposeMesh(); nearbyChunks.remove(); break; } } } } boolean chunksHaveBeenAdded = false; for (Vector3ic chunkPositionToAdd : newRenderableRegion) { if (!renderableRegion.contains(chunkPositionToAdd)) { chunk = chunkProvider.getChunk(chunkPositionToAdd); if (chunk != null) { chunksInProximityOfCamera.add(chunk); chunksHaveBeenAdded = true; } } } if (chunksHaveBeenAdded) { chunksInProximityOfCamera.sort(new ChunkFrontToBackComparator()); } renderableRegion = newRenderableRegion; return true; } return false; } @Override public boolean updateChunksInProximity(ViewDistance newViewDistance, int chunkLods) { if (newViewDistance != currentViewDistance || (lodChunkProvider != null && chunkLods != lodChunkProvider.getChunkLods())) { logger.info("New Viewing Distance: {}", newViewDistance); currentViewDistance = newViewDistance; if (lodChunkProvider != null) { lodChunkProvider.updateRenderableRegion(newViewDistance, chunkLods, calcCameraCoordinatesInChunkUnits()); } return updateChunksInProximity(calculateRenderableRegion(newViewDistance)); } else { return false; } } private BlockRegion calculateRenderableRegion(ViewDistance newViewDistance) { Vector3i cameraCoordinates = calcCameraCoordinatesInChunkUnits(); Vector3ic renderableRegionSize = newViewDistance.getChunkDistance(); Vector3i renderableRegionExtents = new Vector3i(renderableRegionSize.x() / 2, renderableRegionSize.y() / 2, renderableRegionSize.z() / 2); return new BlockRegion(cameraCoordinates).expand(renderableRegionExtents); } /** * Chunk position of the player. * * @return The player offset chunk */ private Vector3i calcCameraCoordinatesInChunkUnits() { Vector3f cameraCoordinates = playerCamera.getPosition(); return Chunks.toChunkPos(cameraCoordinates, new Vector3i()); } /** * Updates the currently visible chunks (in sight of the player). */ @Override public int queueVisibleChunks(boolean isFirstRenderingStageForCurrentFrame) { PerformanceMonitor.startActivity("Queueing Visible Chunks"); statDirtyChunks = 0; statVisibleChunks = 0; statIgnoredPhases = 0; int chunkCounter = 0; renderQueues.clear(); ChunkMesh mesh; boolean isDynamicShadows = renderingConfig.isDynamicShadows(); int billboardLimit = (int) renderingConfig.getBillboardLimit(); List<RenderableChunk> allChunks = new ArrayList<>(chunksInProximityOfCamera); allChunks.addAll(chunkMeshRenderer.getRenderableChunks()); if (lodChunkProvider != null) { lodChunkProvider.addAllChunks(allChunks); } for (RenderableChunk chunk : allChunks) { if (isChunkValidForRender(chunk)) { mesh = chunk.getMesh(); if (isDynamicShadows && isFirstRenderingStageForCurrentFrame && chunkCounter < maxChunksForShadows && isChunkVisibleFromMainLight(chunk)) { if (triangleCount(mesh, ChunkMesh.RenderPhase.OPAQUE) > 0) { renderQueues.chunksOpaqueShadow.add(chunk); } else { statIgnoredPhases++; } } if (isChunkVisible(chunk)) { if (triangleCount(mesh, ChunkMesh.RenderPhase.OPAQUE) > 0) { renderQueues.chunksOpaque.add(chunk); } else { statIgnoredPhases++; } if (triangleCount(mesh, ChunkMesh.RenderPhase.REFRACTIVE) > 0) { renderQueues.chunksAlphaBlend.add(chunk); } else { statIgnoredPhases++; } if (triangleCount(mesh, ChunkMesh.RenderPhase.ALPHA_REJECT) > 0 && (billboardLimit == 0 || chunkCounter < billboardLimit)) { renderQueues.chunksAlphaReject.add(chunk); } else { statIgnoredPhases++; } statVisibleChunks++; chunk.setAnimated(statVisibleChunks < MAX_ANIMATED_CHUNKS); } if (isChunkVisibleReflection(chunk)) { renderQueues.chunksOpaqueReflection.add(chunk); } } chunkCounter++; } if (isFirstRenderingStageForCurrentFrame) { for (Chunk chunk : chunksInProximityOfCamera) { if (isChunkValidForRender(chunk) && chunk.isDirty()) { statDirtyChunks++; chunkMeshPublisher.tryEmitNext(chunk); } } } PerformanceMonitor.endActivity(); return chunkMeshProcessing.size(); } private int triangleCount(ChunkMesh mesh, ChunkMesh.RenderPhase renderPhase) { if (mesh != null) { return mesh.triangleCount(renderPhase); } else { return 0; } } @Override public void dispose() { if (lodChunkProvider != null) { lodChunkProvider.shutdown(); } } private boolean isChunkValidForRender(RenderableChunk chunk) { return chunk.isReady(); } private boolean isChunkVisibleFromMainLight(RenderableChunk chunk) { //TODO: need to work out better scheme for shadowMapCamera if (shadowMapCamera == null) { return false; } return isChunkVisible(shadowMapCamera, chunk); //TODO: find an elegant way } private boolean isChunkVisible(RenderableChunk chunk) { return isChunkVisible(playerCamera, chunk); } private boolean isChunkVisible(Camera camera, RenderableChunk chunk) { return camera.hasInSight(chunk.getAABB()); } private boolean isChunkVisibleReflection(RenderableChunk chunk) { AABBfc bounds = chunk.getAABB(); return playerCamera.getViewFrustumReflected().testAab(bounds.minX(), bounds.minY(), bounds.minZ(), bounds.maxX(), bounds.maxY(), bounds.maxZ()); } @Override public RenderQueuesHelper getRenderQueues() { return renderQueues; } @Override public ChunkProvider getChunkProvider() { return chunkProvider; } @Override public void setShadowMapCamera(Camera camera) { this.shadowMapCamera = camera; } @Override public void setChunkMeshRenderer(ChunkMeshRenderer meshes) { chunkMeshRenderer = meshes; } @Override public String getMetrics() { String stringToReturn = ""; stringToReturn += "Dirty Chunks: "; stringToReturn += statDirtyChunks; stringToReturn += "\n"; stringToReturn += "Ignored Phases: "; stringToReturn += statIgnoredPhases; stringToReturn += "\n"; stringToReturn += "Visible Chunks: "; stringToReturn += statVisibleChunks; stringToReturn += "\n"; return stringToReturn; } private static float squaredDistanceToCamera(RenderableChunk chunk, Vector3f cameraPosition) { // For performance reasons, to avoid instantiating too many vectors in a frequently called method, // comments are in use instead of appropriately named vectors. Vector3f result = chunk.getRenderPosition(); result.add(CHUNK_CENTER_OFFSET); result.sub(cameraPosition); // camera to chunk vector return result.lengthSquared(); } // TODO: find the right place to check if the activeCamera has changed, // TODO: so that the comparators can hold an up-to-date reference to it // TODO: and avoid having to find it on a per-comparison basis. private static class ChunkFrontToBackComparator implements Comparator<RenderableChunk> { @Override public int compare(RenderableChunk chunk1, RenderableChunk chunk2) { Preconditions.checkNotNull(chunk1); Preconditions.checkNotNull(chunk2); Vector3f cameraPosition = CoreRegistry.get(WorldRenderer.class).getActiveCamera().getPosition(); double distance1 = squaredDistanceToCamera(chunk1, cameraPosition); double distance2 = squaredDistanceToCamera(chunk2, cameraPosition); // Using Double.compare as simple d1 < d2 comparison is flagged as problematic by Jenkins // On the other hand Double.compare can return any positive/negative value apparently, // hence the need for Math.signum(). return (int) Math.signum(Double.compare(distance1, distance2)); } } private static class ChunkBackToFrontComparator implements Comparator<RenderableChunk> { @Override public int compare(RenderableChunk chunk1, RenderableChunk chunk2) { Preconditions.checkNotNull(chunk1); Preconditions.checkNotNull(chunk2); Vector3f cameraPosition = CoreRegistry.get(WorldRenderer.class).getActiveCamera().getPosition(); double distance1 = squaredDistanceToCamera(chunk1, cameraPosition); double distance2 = squaredDistanceToCamera(chunk2, cameraPosition); return Double.compare(distance2, distance1); } } }
handle emission error when submitting chunk for mesh
engine/src/main/java/org/terasology/engine/rendering/world/RenderableWorldImpl.java
handle emission error when submitting chunk for mesh
Java
apache-2.0
c8374d82967242de5a7b214d3feaf70d8f6d9e53
0
tballison/lucene-addons,tballison/lucene-addons,tballison/lucene-addons
package org.apache.lucene.search.spans; /* * 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; public class SimpleSpanQueryConverter { /** * Converts a regular query to a {@link org.apache.lucene.search.spans.SpanQuery} for use in a highlighter. * Because of subtle differences in {@link org.apache.lucene.search.spans.SpanQuery} and {@link org.apache.lucene.search.Query}, this * {@link org.apache.lucene.search.spans.SpanQuery} will not necessarily return the same documents as the * initial Query. For example, the generated SpanQuery will not include * clauses of type BooleanClause.Occur.MUST_NOT. Also, the * {@link org.apache.lucene.search.spans.SpanQuery} will only cover a single field, whereas the {@link org.apache.lucene.search.Query} * might contain multiple fields. * <p/> * Returns an empty SpanQuery if the {@link org.apache.lucene.search.Query} is a class that * is handled, but for some reason can't be converted from a {@link org.apache.lucene.search.Query} to a * {@link org.apache.lucene.search.spans.SpanQuery}. This can happen for many reasons: e.g. if the Query * contains no terms in the requested "field" or the Query is a MatchAllDocsQuery. * <p/> * Throws IllegalArgumentException if the Query is a class that is * is not yet handled. * <p/> * This class does not rewrite the SpanQuery before returning it. * Clients are required to rewrite if necessary. * <p/> * Much of this code is copied directly from * oal.search.highlight.WeightedSpanTermExtractor. There are some subtle * differences. * <p/> * Throws IllegalArgumentException for unknown query types. * * @param field single field to extract SpanQueries for * @param queryToConvert query to convert * @return SpanQuery for use in highlighting; can return empty SpanQuery * @throws java.io.IOException */ public SpanQuery convert(String field, Query queryToConvert) throws IOException { Float boost = null; Query query = queryToConvert; if (queryToConvert instanceof BoostQuery) { query = ((BoostQuery)query).getQuery(); boost = ((BoostQuery)query).getBoost(); } /* * copied nearly verbatim from * org.apache.lucene.search.highlight.WeightedSpanTermExtractor * TODO:refactor to avoid duplication of code if possible. * Beware: there are some subtle differences. */ if (query instanceof SpanQuery) { SpanQuery sq = (SpanQuery) query; if (sq.getField().equals(field)) { return (SpanQuery) query; } else { return getEmptySpanQuery(); } } else if (query instanceof BooleanQuery) { List<BooleanClause> queryClauses = ((BooleanQuery) query).clauses(); List<SpanQuery> spanQs = new ArrayList<SpanQuery>(); for (int i = 0; i < queryClauses.size(); i++) { if (!queryClauses.get(i).isProhibited()) { tryToAdd(field, convert(field, queryClauses.get(i).getQuery()), spanQs); } } return addBoost(buildSpanOr(spanQs), boost); } else if (query instanceof PhraseQuery) { PhraseQuery phraseQuery = ((PhraseQuery) query); Term[] phraseQueryTerms = phraseQuery.getTerms(); if (phraseQueryTerms.length == 0) { return getEmptySpanQuery(); } else if (!phraseQueryTerms[0].field().equals(field)) { return getEmptySpanQuery(); } SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.length]; for (int i = 0; i < phraseQueryTerms.length; i++) { clauses[i] = new SpanTermQuery(phraseQueryTerms[i]); } int slop = phraseQuery.getSlop(); int[] positions = phraseQuery.getPositions(); // sum position increments (>1) and add to slop if (positions.length > 0) { int lastPos = positions[0]; int sz = positions.length; for (int i = 1; i < sz; i++) { int pos = positions[i]; int inc = pos - lastPos - 1; slop += inc; lastPos = pos; } } boolean inorder = false; if (phraseQuery.getSlop() == 0) { inorder = true; } SpanQuery sp = new SpanNearQuery(clauses, slop, inorder); if (query instanceof BoostQuery) { sp = new SpanBoostQuery(sp, ((BoostQuery)query).getBoost()); } return addBoost(sp, boost); } else if (query instanceof TermQuery) { TermQuery tq = (TermQuery) query; if (tq.getTerm().field().equals(field)) { return addBoost(new SpanTermQuery(tq.getTerm()), boost); } else { return getEmptySpanQuery(); } } else if (query instanceof ConstantScoreQuery) { return convert(field, ((ConstantScoreQuery) query).getQuery()); } else if (query instanceof DisjunctionMaxQuery) { List<SpanQuery> spanQs = new ArrayList<>(); for (Iterator<Query> iterator = ((DisjunctionMaxQuery) query).iterator(); iterator .hasNext(); ) { tryToAdd(field, convert(field, iterator.next()), spanQs); } if (spanQs.size() == 0) { return getEmptySpanQuery(); } else if (spanQs.size() == 1) { return addBoost(spanQs.get(0), boost); } else { return addBoost(new SpanOrQuery(spanQs.toArray(new SpanQuery[spanQs.size()])), boost); } } else if (query instanceof MatchAllDocsQuery) { return getEmptySpanQuery(); } else if (query instanceof MultiPhraseQuery) { final MultiPhraseQuery mpq = (MultiPhraseQuery) query; final Term[][] termArrays = mpq.getTermArrays(); //test for empty or wrong field if (termArrays.length == 0) { return getEmptySpanQuery(); } else if (termArrays.length > 1) { Term[] ts = termArrays[0]; if (ts.length > 0) { Term t = ts[0]; if (!t.field().equals(field)) { return getEmptySpanQuery(); } } } final int[] positions = mpq.getPositions(); if (positions.length > 0) { int maxPosition = positions[positions.length - 1]; for (int i = 0; i < positions.length - 1; ++i) { if (positions[i] > maxPosition) { maxPosition = positions[i]; } } @SuppressWarnings("unchecked") final List<SpanQuery>[] disjunctLists = new List[maxPosition + 1]; int distinctPositions = 0; for (int i = 0; i < termArrays.length; ++i) { final Term[] termArray = termArrays[i]; List<SpanQuery> disjuncts = disjunctLists[positions[i]]; if (disjuncts == null) { disjuncts = (disjunctLists[positions[i]] = new ArrayList<SpanQuery>( termArray.length)); ++distinctPositions; } for (int j = 0; j < termArray.length; ++j) { disjuncts.add(new SpanTermQuery(termArray[j])); } } int positionGaps = 0; int position = 0; final SpanQuery[] clauses = new SpanQuery[distinctPositions]; for (int i = 0; i < disjunctLists.length; ++i) { List<SpanQuery> disjuncts = disjunctLists[i]; if (disjuncts != null) { if (disjuncts.size() == 1) { clauses[position++] = disjuncts.get(0); } else { clauses[position++] = new SpanOrQuery( disjuncts.toArray(new SpanQuery[disjuncts.size()])); } } else { ++positionGaps; } } final int slop = mpq.getSlop(); final boolean inorder = (slop == 0); SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder); return addBoost(sp, boost); } } else if (query instanceof MultiTermQuery) { MultiTermQuery tq = (MultiTermQuery) query; if (! tq.getField().equals(field)) { return getEmptySpanQuery(); } return addBoost( new SpanMultiTermQueryWrapper<>((MultiTermQuery) query), boost); } else if (query instanceof SynonymQuery) { SynonymQuery sq = (SynonymQuery)query; List<SpanQuery> spanQs = new ArrayList<>(); for (Term t : sq.getTerms()) { spanQs.add(new SpanTermQuery(t)); } return addBoost(buildSpanOr(spanQs), boost); } return convertUnknownQuery(field, queryToConvert); } private SpanQuery buildSpanOr(List<SpanQuery> spanQs) { if (spanQs.size() == 0) { return getEmptySpanQuery(); } else if (spanQs.size() == 1) { return spanQs.get(0); } else { return new SpanOrQuery(spanQs.toArray(new SpanQuery[spanQs.size()])); } } private SpanQuery addBoost(SpanQuery sq, Float boost) { if (boost == null) { return sq; } return new SpanBoostQuery(sq, boost); } private void tryToAdd(String field, SpanQuery q, List<SpanQuery> qs) { if (q == null || isEmptyQuery(q) || !q.getField().equals(field)) { return; } qs.add(q); } /** * Extend this to handle queries that are not currently handled. * Might consider extending SpanQueryConverter in the queries compilation unit; * that includes CommonTermsQuery. * <p/> * In this class, this always throws an IllegalArgumentException * * @param field field to convert * @param query query to convert * @return nothing. Throws IllegalArgumentException */ protected SpanQuery convertUnknownQuery(String field, Query query) { throw new IllegalArgumentException("SpanQueryConverter is unable to convert this class " + query.getClass().toString()); } /** * @return an empty SpanQuery (SpanOrQuery with no cluases) */ protected SpanQuery getEmptySpanQuery() { SpanQuery q = new SpanOrQuery(new SpanTermQuery[0]); return q; } /** * Is this a null or empty SpanQuery * * @param q query to test * @return whether a null or empty SpanQuery */ protected boolean isEmptyQuery(SpanQuery q) { if (q == null) { return true; } if (q instanceof SpanOrQuery) { SpanOrQuery soq = (SpanOrQuery) q; for (SpanQuery sq : soq.getClauses()) { if (!isEmptyQuery(sq)) { return false; } } return true; } return false; } }
lucene-5317/src/main/java/org/apache/lucene/search/spans/SimpleSpanQueryConverter.java
package org.apache.lucene.search.spans; /* * 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. */ import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.lucene.index.Term; import org.apache.lucene.search.*; public class SimpleSpanQueryConverter { /** * Converts a regular query to a {@link org.apache.lucene.search.spans.SpanQuery} for use in a highlighter. * Because of subtle differences in {@link org.apache.lucene.search.spans.SpanQuery} and {@link org.apache.lucene.search.Query}, this * {@link org.apache.lucene.search.spans.SpanQuery} will not necessarily return the same documents as the * initial Query. For example, the generated SpanQuery will not include * clauses of type BooleanClause.Occur.MUST_NOT. Also, the * {@link org.apache.lucene.search.spans.SpanQuery} will only cover a single field, whereas the {@link org.apache.lucene.search.Query} * might contain multiple fields. * <p/> * Returns an empty SpanQuery if the {@link org.apache.lucene.search.Query} is a class that * is handled, but for some reason can't be converted from a {@link org.apache.lucene.search.Query} to a * {@link org.apache.lucene.search.spans.SpanQuery}. This can happen for many reasons: e.g. if the Query * contains no terms in the requested "field" or the Query is a MatchAllDocsQuery. * <p/> * Throws IllegalArgumentException if the Query is a class that is * is not yet handled. * <p/> * This class does not rewrite the SpanQuery before returning it. * Clients are required to rewrite if necessary. * <p/> * Much of this code is copied directly from * oal.search.highlight.WeightedSpanTermExtractor. There are some subtle * differences. * * @param field single field to extract SpanQueries for * @param queryToConvert query to convert * @return SpanQuery for use in highlighting; can return empty SpanQuery * @throws java.io.IOException, IllegalArgumentException */ public SpanQuery convert(String field, Query queryToConvert) throws IOException { Float boost = null; Query query = queryToConvert; if (queryToConvert instanceof BoostQuery) { query = ((BoostQuery)query).getQuery(); boost = ((BoostQuery)query).getBoost(); } /* * copied nearly verbatim from * org.apache.lucene.search.highlight.WeightedSpanTermExtractor * TODO:refactor to avoid duplication of code if possible. * Beware: there are some subtle differences. */ if (query instanceof SpanQuery) { SpanQuery sq = (SpanQuery) query; if (sq.getField().equals(field)) { return (SpanQuery) query; } else { return getEmptySpanQuery(); } } else if (query instanceof BooleanQuery) { List<BooleanClause> queryClauses = ((BooleanQuery) query).clauses(); List<SpanQuery> spanQs = new ArrayList<SpanQuery>(); for (int i = 0; i < queryClauses.size(); i++) { if (!queryClauses.get(i).isProhibited()) { tryToAdd(field, convert(field, queryClauses.get(i).getQuery()), spanQs); } } return addBoost(buildSpanOr(spanQs), boost); } else if (query instanceof PhraseQuery) { PhraseQuery phraseQuery = ((PhraseQuery) query); Term[] phraseQueryTerms = phraseQuery.getTerms(); if (phraseQueryTerms.length == 0) { return getEmptySpanQuery(); } else if (!phraseQueryTerms[0].field().equals(field)) { return getEmptySpanQuery(); } SpanQuery[] clauses = new SpanQuery[phraseQueryTerms.length]; for (int i = 0; i < phraseQueryTerms.length; i++) { clauses[i] = new SpanTermQuery(phraseQueryTerms[i]); } int slop = phraseQuery.getSlop(); int[] positions = phraseQuery.getPositions(); // sum position increments (>1) and add to slop if (positions.length > 0) { int lastPos = positions[0]; int sz = positions.length; for (int i = 1; i < sz; i++) { int pos = positions[i]; int inc = pos - lastPos - 1; slop += inc; lastPos = pos; } } boolean inorder = false; if (phraseQuery.getSlop() == 0) { inorder = true; } SpanQuery sp = new SpanNearQuery(clauses, slop, inorder); if (query instanceof BoostQuery) { sp = new SpanBoostQuery(sp, ((BoostQuery)query).getBoost()); } return addBoost(sp, boost); } else if (query instanceof TermQuery) { TermQuery tq = (TermQuery) query; if (tq.getTerm().field().equals(field)) { return addBoost(new SpanTermQuery(tq.getTerm()), boost); } else { return getEmptySpanQuery(); } } else if (query instanceof ConstantScoreQuery) { return convert(field, ((ConstantScoreQuery) query).getQuery()); } else if (query instanceof DisjunctionMaxQuery) { List<SpanQuery> spanQs = new ArrayList<>(); for (Iterator<Query> iterator = ((DisjunctionMaxQuery) query).iterator(); iterator .hasNext(); ) { tryToAdd(field, convert(field, iterator.next()), spanQs); } if (spanQs.size() == 0) { return getEmptySpanQuery(); } else if (spanQs.size() == 1) { return addBoost(spanQs.get(0), boost); } else { return addBoost(new SpanOrQuery(spanQs.toArray(new SpanQuery[spanQs.size()])), boost); } } else if (query instanceof MatchAllDocsQuery) { return getEmptySpanQuery(); } else if (query instanceof MultiPhraseQuery) { final MultiPhraseQuery mpq = (MultiPhraseQuery) query; final Term[][] termArrays = mpq.getTermArrays(); //test for empty or wrong field if (termArrays.length == 0) { return getEmptySpanQuery(); } else if (termArrays.length > 1) { Term[] ts = termArrays[0]; if (ts.length > 0) { Term t = ts[0]; if (!t.field().equals(field)) { return getEmptySpanQuery(); } } } final int[] positions = mpq.getPositions(); if (positions.length > 0) { int maxPosition = positions[positions.length - 1]; for (int i = 0; i < positions.length - 1; ++i) { if (positions[i] > maxPosition) { maxPosition = positions[i]; } } @SuppressWarnings("unchecked") final List<SpanQuery>[] disjunctLists = new List[maxPosition + 1]; int distinctPositions = 0; for (int i = 0; i < termArrays.length; ++i) { final Term[] termArray = termArrays[i]; List<SpanQuery> disjuncts = disjunctLists[positions[i]]; if (disjuncts == null) { disjuncts = (disjunctLists[positions[i]] = new ArrayList<SpanQuery>( termArray.length)); ++distinctPositions; } for (int j = 0; j < termArray.length; ++j) { disjuncts.add(new SpanTermQuery(termArray[j])); } } int positionGaps = 0; int position = 0; final SpanQuery[] clauses = new SpanQuery[distinctPositions]; for (int i = 0; i < disjunctLists.length; ++i) { List<SpanQuery> disjuncts = disjunctLists[i]; if (disjuncts != null) { if (disjuncts.size() == 1) { clauses[position++] = disjuncts.get(0); } else { clauses[position++] = new SpanOrQuery( disjuncts.toArray(new SpanQuery[disjuncts.size()])); } } else { ++positionGaps; } } final int slop = mpq.getSlop(); final boolean inorder = (slop == 0); SpanNearQuery sp = new SpanNearQuery(clauses, slop + positionGaps, inorder); return addBoost(sp, boost); } } else if (query instanceof MultiTermQuery) { MultiTermQuery tq = (MultiTermQuery) query; if (! tq.getField().equals(field)) { return getEmptySpanQuery(); } return addBoost( new SpanMultiTermQueryWrapper<>((MultiTermQuery) query), boost); } else if (query instanceof SynonymQuery) { SynonymQuery sq = (SynonymQuery)query; List<SpanQuery> spanQs = new ArrayList<>(); for (Term t : sq.getTerms()) { spanQs.add(new SpanTermQuery(t)); } return addBoost(buildSpanOr(spanQs), boost); } return convertUnknownQuery(field, queryToConvert); } private SpanQuery buildSpanOr(List<SpanQuery> spanQs) { if (spanQs.size() == 0) { return getEmptySpanQuery(); } else if (spanQs.size() == 1) { return spanQs.get(0); } else { return new SpanOrQuery(spanQs.toArray(new SpanQuery[spanQs.size()])); } } private SpanQuery addBoost(SpanQuery sq, Float boost) { if (boost == null) { return sq; } return new SpanBoostQuery(sq, boost); } private void tryToAdd(String field, SpanQuery q, List<SpanQuery> qs) { if (q == null || isEmptyQuery(q) || !q.getField().equals(field)) { return; } qs.add(q); } /** * Extend this to handle queries that are not currently handled. * Might consider extending SpanQueryConverter in the queries compilation unit; * that includes CommonTermsQuery. * <p/> * In this class, this always throws an IllegalArgumentException * * @param field field to convert * @param query query to convert * @return nothing. Throws IllegalArgumentException */ protected SpanQuery convertUnknownQuery(String field, Query query) { throw new IllegalArgumentException("SpanQueryConverter is unable to convert this class " + query.getClass().toString()); } /** * @return an empty SpanQuery (SpanOrQuery with no cluases) */ protected SpanQuery getEmptySpanQuery() { SpanQuery q = new SpanOrQuery(new SpanTermQuery[0]); return q; } /** * Is this a null or empty SpanQuery * * @param q query to test * @return whether a null or empty SpanQuery */ protected boolean isEmptyQuery(SpanQuery q) { if (q == null) { return true; } if (q instanceof SpanOrQuery) { SpanOrQuery soq = (SpanOrQuery) q; for (SpanQuery sq : soq.getClauses()) { if (!isEmptyQuery(sq)) { return false; } } return true; } return false; } }
fix javadoc
lucene-5317/src/main/java/org/apache/lucene/search/spans/SimpleSpanQueryConverter.java
fix javadoc
Java
apache-2.0
5c05575c0d53110c37d1922d56f2406cdb70503f
0
jgrandja/spring-security,cyratech/spring-security,zgscwjm/spring-security,Xcorpio/spring-security,dsyer/spring-security,mrkingybc/spring-security,raindev/spring-security,eddumelendez/spring-security,Krasnyanskiy/spring-security,spring-projects/spring-security,Xcorpio/spring-security,hippostar/spring-security,spring-projects/spring-security,panchenko/spring-security,follow99/spring-security,pwheel/spring-security,hippostar/spring-security,Peter32/spring-security,panchenko/spring-security,MatthiasWinzeler/spring-security,spring-projects/spring-security,ajdinhedzic/spring-security,cyratech/spring-security,jmnarloch/spring-security,tekul/spring-security,raindev/spring-security,izeye/spring-security,rwinch/spring-security,djechelon/spring-security,mparaz/spring-security,mrkingybc/spring-security,likaiwalkman/spring-security,zshift/spring-security,diegofernandes/spring-security,jgrandja/spring-security,spring-projects/spring-security,mdeinum/spring-security,zhaoqin102/spring-security,fhanik/spring-security,fhanik/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,spring-projects/spring-security,wilkinsona/spring-security,adairtaosy/spring-security,diegofernandes/spring-security,dsyer/spring-security,rwinch/spring-security,fhanik/spring-security,kazuki43zoo/spring-security,Peter32/spring-security,SanjayUser/SpringSecurityPro,cyratech/spring-security,driftman/spring-security,rwinch/spring-security,jmnarloch/spring-security,zgscwjm/spring-security,ollie314/spring-security,liuguohua/spring-security,ajdinhedzic/spring-security,Peter32/spring-security,wilkinsona/spring-security,Krasnyanskiy/spring-security,ractive/spring-security,MatthiasWinzeler/spring-security,vitorgv/spring-security,follow99/spring-security,fhanik/spring-security,adairtaosy/spring-security,zhaoqin102/spring-security,jgrandja/spring-security,diegofernandes/spring-security,ajdinhedzic/spring-security,chinazhaoht/spring-security,dsyer/spring-security,liuguohua/spring-security,forestqqqq/spring-security,kazuki43zoo/spring-security,thomasdarimont/spring-security,yinhe402/spring-security,djechelon/spring-security,driftman/spring-security,ollie314/spring-security,mdeinum/spring-security,ajdinhedzic/spring-security,pkdevbox/spring-security,panchenko/spring-security,rwinch/spring-security,pwheel/spring-security,mdeinum/spring-security,pkdevbox/spring-security,chinazhaoht/spring-security,MatthiasWinzeler/spring-security,tekul/spring-security,olezhuravlev/spring-security,mdeinum/spring-security,yinhe402/spring-security,diegofernandes/spring-security,raindev/spring-security,spring-projects/spring-security,vitorgv/spring-security,chinazhaoht/spring-security,olezhuravlev/spring-security,thomasdarimont/spring-security,likaiwalkman/spring-security,mparaz/spring-security,mparaz/spring-security,eddumelendez/spring-security,driftman/spring-security,Krasnyanskiy/spring-security,olezhuravlev/spring-security,SanjayUser/SpringSecurityPro,fhanik/spring-security,xingguang2013/spring-security,Peter32/spring-security,pwheel/spring-security,pkdevbox/spring-security,jgrandja/spring-security,mounb/spring-security,jmnarloch/spring-security,zhaoqin102/spring-security,eddumelendez/spring-security,eddumelendez/spring-security,hippostar/spring-security,zhaoqin102/spring-security,SanjayUser/SpringSecurityPro,caiwenshu/spring-security,zshift/spring-security,cyratech/spring-security,ractive/spring-security,wkorando/spring-security,pwheel/spring-security,mrkingybc/spring-security,ollie314/spring-security,izeye/spring-security,adairtaosy/spring-security,panchenko/spring-security,zshift/spring-security,MatthiasWinzeler/spring-security,zgscwjm/spring-security,kazuki43zoo/spring-security,yinhe402/spring-security,Krasnyanskiy/spring-security,follow99/spring-security,thomasdarimont/spring-security,liuguohua/spring-security,spring-projects/spring-security,tekul/spring-security,wilkinsona/spring-security,SanjayUser/SpringSecurityPro,zgscwjm/spring-security,thomasdarimont/spring-security,mounb/spring-security,caiwenshu/spring-security,xingguang2013/spring-security,wkorando/spring-security,rwinch/spring-security,raindev/spring-security,Xcorpio/spring-security,driftman/spring-security,djechelon/spring-security,olezhuravlev/spring-security,follow99/spring-security,hippostar/spring-security,izeye/spring-security,jgrandja/spring-security,yinhe402/spring-security,SanjayUser/SpringSecurityPro,wilkinsona/spring-security,tekul/spring-security,kazuki43zoo/spring-security,forestqqqq/spring-security,izeye/spring-security,ractive/spring-security,eddumelendez/spring-security,vitorgv/spring-security,caiwenshu/spring-security,xingguang2013/spring-security,mparaz/spring-security,dsyer/spring-security,vitorgv/spring-security,jgrandja/spring-security,caiwenshu/spring-security,dsyer/spring-security,pwheel/spring-security,olezhuravlev/spring-security,rwinch/spring-security,zshift/spring-security,kazuki43zoo/spring-security,jmnarloch/spring-security,ollie314/spring-security,fhanik/spring-security,forestqqqq/spring-security,xingguang2013/spring-security,mounb/spring-security,adairtaosy/spring-security,djechelon/spring-security,wkorando/spring-security,wkorando/spring-security,liuguohua/spring-security,Xcorpio/spring-security,ractive/spring-security,mounb/spring-security,djechelon/spring-security,likaiwalkman/spring-security,mrkingybc/spring-security,chinazhaoht/spring-security,pkdevbox/spring-security,forestqqqq/spring-security
package org.springframework.security.openid; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.*; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.junit.*; import org.junit.runner.RunWith; import org.openid4java.association.AssociationException; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.Message; import org.openid4java.message.MessageException; import org.openid4java.message.ParameterList; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchResponse; import org.springframework.mock.web.MockHttpServletRequest; import java.util.*; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; /** * @author Luke Taylor * @author Rob Winch */ @RunWith(PowerMockRunner.class) @PrepareForTest({MultiThreadedHttpConnectionManager.class,Message.class}) public class OpenID4JavaConsumerTests { List<OpenIDAttribute> attributes = Arrays.asList(new OpenIDAttribute("a","b"), new OpenIDAttribute("b","b", Arrays.asList("c"))); @SuppressWarnings("deprecation") @Test public void beginConsumptionCreatesExpectedSessionData() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); AuthRequest authReq = mock(AuthRequest.class); DiscoveryInformation di = mock(DiscoveryInformation.class); when(mgr.authenticate(any(DiscoveryInformation.class), anyString(), anyString())).thenReturn(authReq); when(mgr.associate(anyList())).thenReturn(di); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, attributes); MockHttpServletRequest request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); assertEquals(attributes, request.getSession().getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")); assertSame(di, request.getSession().getAttribute(DiscoveryInformation.class.getName())); // Check with empty attribute fetch list consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); } @Test(expected = OpenIDConsumerException.class) public void discoveryExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.discover(anyString())).thenThrow(new DiscoveryException("msg")); consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); } @Test public void messageOrConsumerAuthenticationExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.authenticate(any(DiscoveryInformation.class), anyString(), anyString())) .thenThrow(new MessageException("msg"), new ConsumerException("msg")); try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); fail(); } catch (OpenIDConsumerException expected) { } } @Test public void failedVerificationReturnsFailedAuthenticationStatus() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertEquals(OpenIDAuthenticationStatus.FAILURE, auth.getStatus()); } @Test public void verificationExceptionsRaiseOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))) .thenThrow(new MessageException("")) .thenThrow(new AssociationException("")) .thenThrow(new DiscoveryException("")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("x=5"); try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } } @SuppressWarnings("serial") @Test public void successfulVerificationReturnsExpectedAuthentication() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); Identifier id = new Identifier() { public String getIdentifier() { return "id"; } }; Message msg = mock(Message.class); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); when(vr.getVerifiedId()).thenReturn(id); when(vr.getAuthResponse()).thenReturn(msg); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); request.getSession().setAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST", attributes); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertEquals(OpenIDAuthenticationStatus.SUCCESS, auth.getStatus()); } @Test public void fetchAttributesReturnsExpectedValues() throws Exception { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenReturn(fr); when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x","y")); List<OpenIDAttribute> fetched = consumer.fetchAxAttributes(msg, attributes); assertEquals(1, fetched.size()); assertEquals(2, fetched.get(0).getValues().size()); } @Test(expected = OpenIDConsumerException.class) public void messageExceptionFetchingAttributesRaisesOpenIDException() throws Exception { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenThrow(new MessageException("")); when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x","y")); consumer.fetchAxAttributes(msg, attributes); } @SuppressWarnings("deprecation") @Test public void additionalConstructorsWork() throws Exception { new OpenID4JavaConsumer(); new OpenID4JavaConsumer(attributes); } @Test public void afterPropertiesSetRegister() throws Exception { mockStatic(Message.class); new OpenID4JavaConsumer().afterPropertiesSet(); verifyStatic(); Message.addExtensionFactory(SignedAxMessageExtensionFactory.class); } @Test public void afterPropertiesSetSkipRegister() throws Exception { mockStatic(Message.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(); consumer.setSkipSignedAxMessageRegistration(true); consumer.afterPropertiesSet(); verifyStatic(never()); Message.addExtensionFactory(SignedAxMessageExtensionFactory.class); } @Test public void destroyInvokesShutdownAll() throws Exception { mockStatic(MultiThreadedHttpConnectionManager.class); new OpenID4JavaConsumer().destroy(); verifyStatic(); MultiThreadedHttpConnectionManager.shutdownAll(); } @Test public void destroyOverrideShutdownAll() throws Exception { mockStatic(MultiThreadedHttpConnectionManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(); consumer.setSkipShutdownConnectionManager(true); consumer.destroy(); verifyStatic(never()); MultiThreadedHttpConnectionManager.shutdownAll(); } }
openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java
package org.springframework.security.openid; import static org.junit.Assert.*; import static org.mockito.Matchers.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.*; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.junit.*; import org.junit.runner.RunWith; import org.openid4java.association.AssociationException; import org.openid4java.consumer.ConsumerException; import org.openid4java.consumer.ConsumerManager; import org.openid4java.consumer.VerificationResult; import org.openid4java.discovery.DiscoveryException; import org.openid4java.discovery.DiscoveryInformation; import org.openid4java.discovery.Identifier; import org.openid4java.message.AuthRequest; import org.openid4java.message.Message; import org.openid4java.message.MessageException; import org.openid4java.message.ParameterList; import org.openid4java.message.ax.AxMessage; import org.openid4java.message.ax.FetchResponse; import org.springframework.mock.web.MockHttpServletRequest; import java.util.*; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.mock.web.MockHttpServletRequest; /** * @author Luke Taylor * @author Rob Winch */ @RunWith(PowerMockRunner.class) @PrepareForTest({MultiThreadedHttpConnectionManager.class,Message.class}) public class OpenID4JavaConsumerTests { List<OpenIDAttribute> attributes = Arrays.asList(new OpenIDAttribute("a","b"), new OpenIDAttribute("b","b", Arrays.asList("c"))); @Test public void beginConsumptionCreatesExpectedSessionData() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); AuthRequest authReq = mock(AuthRequest.class); DiscoveryInformation di = mock(DiscoveryInformation.class); when(mgr.authenticate(any(DiscoveryInformation.class), anyString(), anyString())).thenReturn(authReq); when(mgr.associate(anyList())).thenReturn(di); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, attributes); MockHttpServletRequest request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); assertEquals(attributes, request.getSession().getAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST")); assertSame(di, request.getSession().getAttribute(DiscoveryInformation.class.getName())); // Check with empty attribute fetch list consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); request = new MockHttpServletRequest(); consumer.beginConsumption(request, "", "", ""); } @Test(expected = OpenIDConsumerException.class) public void discoveryExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.discover(anyString())).thenThrow(new DiscoveryException("msg")); consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); } @Test public void messageOrConsumerAuthenticationExceptionRaisesOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.authenticate(any(DiscoveryInformation.class), anyString(), anyString())) .thenThrow(new MessageException("msg"), new ConsumerException("msg")); try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.beginConsumption(new MockHttpServletRequest(), "", "", ""); fail(); } catch (OpenIDConsumerException expected) { } } @Test public void failedVerificationReturnsFailedAuthenticationStatus() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertEquals(OpenIDAuthenticationStatus.FAILURE, auth.getStatus()); } @Test public void verificationExceptionsRaiseOpenIDException() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))) .thenThrow(new MessageException("")) .thenThrow(new AssociationException("")) .thenThrow(new DiscoveryException("")); MockHttpServletRequest request = new MockHttpServletRequest(); request.setQueryString("x=5"); try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } try { consumer.endConsumption(request); fail(); } catch (OpenIDConsumerException expected) { } } @Test public void successfulVerificationReturnsExpectedAuthentication() throws Exception { ConsumerManager mgr = mock(ConsumerManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(mgr, new NullAxFetchListFactory()); VerificationResult vr = mock(VerificationResult.class); DiscoveryInformation di = mock(DiscoveryInformation.class); Identifier id = new Identifier() { public String getIdentifier() { return "id"; } }; Message msg = mock(Message.class); when(mgr.verify(anyString(), any(ParameterList.class), any(DiscoveryInformation.class))).thenReturn(vr); when(vr.getVerifiedId()).thenReturn(id); when(vr.getAuthResponse()).thenReturn(msg); MockHttpServletRequest request = new MockHttpServletRequest(); request.getSession().setAttribute(DiscoveryInformation.class.getName(), di); request.getSession().setAttribute("SPRING_SECURITY_OPEN_ID_ATTRIBUTES_FETCH_LIST", attributes); OpenIDAuthenticationToken auth = consumer.endConsumption(request); assertEquals(OpenIDAuthenticationStatus.SUCCESS, auth.getStatus()); } @Test public void fetchAttributesReturnsExpectedValues() throws Exception { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenReturn(fr); when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x","y")); List<OpenIDAttribute> fetched = consumer.fetchAxAttributes(msg, attributes); assertEquals(1, fetched.size()); assertEquals(2, fetched.get(0).getValues().size()); } @Test(expected = OpenIDConsumerException.class) public void messageExceptionFetchingAttributesRaisesOpenIDException() throws Exception { OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(new NullAxFetchListFactory()); Message msg = mock(Message.class); FetchResponse fr = mock(FetchResponse.class); when(msg.hasExtension(AxMessage.OPENID_NS_AX)).thenReturn(true); when(msg.getExtension(AxMessage.OPENID_NS_AX)).thenThrow(new MessageException("")); when(fr.getAttributeValues("a")).thenReturn(Arrays.asList("x","y")); consumer.fetchAxAttributes(msg, attributes); } @Test public void additionalConstructorsWork() throws Exception { new OpenID4JavaConsumer(); new OpenID4JavaConsumer(attributes); } @Test public void afterPropertiesSetRegister() throws Exception { mockStatic(Message.class); new OpenID4JavaConsumer().afterPropertiesSet(); verifyStatic(); Message.addExtensionFactory(SignedAxMessageExtensionFactory.class); } @Test public void afterPropertiesSetSkipRegister() throws Exception { mockStatic(Message.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(); consumer.setSkipSignedAxMessageRegistration(true); consumer.afterPropertiesSet(); verifyStatic(never()); Message.addExtensionFactory(SignedAxMessageExtensionFactory.class); } @Test public void destroyInvokesShutdownAll() throws Exception { mockStatic(MultiThreadedHttpConnectionManager.class); new OpenID4JavaConsumer().destroy(); verifyStatic(); MultiThreadedHttpConnectionManager.shutdownAll(); } @Test public void destroyOverrideShutdownAll() throws Exception { mockStatic(MultiThreadedHttpConnectionManager.class); OpenID4JavaConsumer consumer = new OpenID4JavaConsumer(); consumer.setSkipShutdownConnectionManager(true); consumer.destroy(); verifyStatic(never()); MultiThreadedHttpConnectionManager.shutdownAll(); } }
Cleaned up warnings in openid module
openid/src/test/java/org/springframework/security/openid/OpenID4JavaConsumerTests.java
Cleaned up warnings in openid module
Java
apache-2.0
2bbf177fe8f8daa3d0fc2157490d774609bef3b2
0
blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,gstevey/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,lsmaira/gradle,gstevey/gradle,robinverduijn/gradle,blindpirate/gradle,blindpirate/gradle,gradle/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle
/* * Copyright 2010 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.process.internal.worker.child; import org.gradle.api.Action; import org.gradle.api.logging.LogLevel; import org.gradle.internal.UncheckedException; import org.gradle.internal.io.ClassLoaderObjectInputStream; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.logging.services.LoggingServiceRegistry; import org.gradle.internal.remote.MessagingClient; import org.gradle.internal.remote.ObjectConnection; import org.gradle.internal.remote.internal.inet.MultiChoiceAddress; import org.gradle.internal.remote.internal.inet.MultiChoiceAddressSerializer; import org.gradle.internal.remote.services.MessagingServices; import org.gradle.internal.serialize.Decoder; import org.gradle.internal.serialize.InputStreamBackedDecoder; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.ObjectInputStream; import java.util.concurrent.Callable; /** * <p>Stage 2 of the start-up for a worker process with the application classes loaded in the system ClassLoader. Takes * care of deserializing and invoking the worker action.</p> * * <p> Instantiated in the implementation ClassLoader and invoked from {@link org.gradle.process.internal.worker.GradleWorkerMain}. * See {@link ApplicationClassesInSystemClassLoaderWorkerFactory} for details.</p> */ public class SystemApplicationClassLoaderWorker implements Callable<Void> { private final DataInputStream configInputStream; public SystemApplicationClassLoaderWorker(DataInputStream configInputStream) { this.configInputStream = configInputStream; } public Void call() throws Exception { if (System.getProperty("org.gradle.worker.test.stuck") != null) { // Simulate a stuck worker. There's probably a way to inject this failure... Thread.sleep(30000); return null; } Decoder decoder = new InputStreamBackedDecoder(configInputStream); // Read logging config and setup logging int logLevel = decoder.readSmallInt(); LoggingManagerInternal loggingManager = createLoggingManager(); loggingManager.setLevelInternal(LogLevel.values()[logLevel]).start(); // Read server address and start connecting MultiChoiceAddress serverAddress = new MultiChoiceAddressSerializer().read(decoder); MessagingServices messagingServices = createClient(); try { final ObjectConnection connection = messagingServices.get(MessagingClient.class).getConnection(serverAddress); configureLogging(loggingManager, connection); try { // Read serialized worker byte[] serializedWorker = decoder.readBinary(); // Deserialize the worker action Action<WorkerContext> action; try { ObjectInputStream instr = new ClassLoaderObjectInputStream(new ByteArrayInputStream(serializedWorker), getClass().getClassLoader()); action = (Action<WorkerContext>) instr.readObject(); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } action.execute(new WorkerContext() { public ClassLoader getApplicationClassLoader() { return ClassLoader.getSystemClassLoader(); } @Override public ObjectConnection getServerConnection() { return connection; } }); } finally { connection.stop(); } } finally { messagingServices.close(); } return null; } private void configureLogging(LoggingManagerInternal loggingManager, ObjectConnection connection) { WorkerLoggingProtocol workerLoggingProtocol = connection.addOutgoing(WorkerLoggingProtocol.class); loggingManager.addOutputEventListener(new WorkerOutputEventListener(workerLoggingProtocol)); } MessagingServices createClient() { return new MessagingServices(); } LoggingManagerInternal createLoggingManager() { LoggingManagerInternal loggingManagerInternal = LoggingServiceRegistry.newEmbeddableLogging().newInstance(LoggingManagerInternal.class); loggingManagerInternal.captureSystemSources(); return loggingManagerInternal; } }
subprojects/core/src/main/java/org/gradle/process/internal/worker/child/SystemApplicationClassLoaderWorker.java
/* * Copyright 2010 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.process.internal.worker.child; import org.gradle.api.Action; import org.gradle.api.logging.LogLevel; import org.gradle.internal.UncheckedException; import org.gradle.internal.io.ClassLoaderObjectInputStream; import org.gradle.internal.serialize.Decoder; import org.gradle.internal.serialize.InputStreamBackedDecoder; import org.gradle.internal.logging.LoggingManagerInternal; import org.gradle.internal.logging.services.LoggingServiceRegistry; import org.gradle.internal.remote.MessagingClient; import org.gradle.internal.remote.ObjectConnection; import org.gradle.internal.remote.services.MessagingServices; import org.gradle.internal.remote.internal.inet.MultiChoiceAddress; import org.gradle.internal.remote.internal.inet.MultiChoiceAddressSerializer; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.ObjectInputStream; import java.util.concurrent.Callable; /** * <p>Stage 2 of the start-up for a worker process with the application classes loaded in the system ClassLoader. Takes * care of deserializing and invoking the worker action.</p> * * <p> Instantiated in the implementation ClassLoader and invoked from {@link org.gradle.process.internal.worker.GradleWorkerMain}. * See {@link ApplicationClassesInSystemClassLoaderWorkerFactory} for details.</p> */ public class SystemApplicationClassLoaderWorker implements Callable<Void> { private final DataInputStream configInputStream; public SystemApplicationClassLoaderWorker(DataInputStream configInputStream) { this.configInputStream = configInputStream; } public Void call() throws Exception { if (System.getProperty("org.gradle.worker.test.stuck") != null) { // Simulate a stuck worker. There's probably a way to inject this failure... Thread.sleep(30000); return null; } Decoder decoder = new InputStreamBackedDecoder(configInputStream); // Read logging config and setup logging int logLevel = decoder.readSmallInt(); LoggingManagerInternal loggingManager = createLoggingManager(); loggingManager.setLevelInternal(LogLevel.values()[logLevel]).start(); // Read server address and start connecting MultiChoiceAddress serverAddress = new MultiChoiceAddressSerializer().read(decoder); MessagingServices messagingServices = createClient(); try { final ObjectConnection connection = messagingServices.get(MessagingClient.class).getConnection(serverAddress); configureLogging(loggingManager, connection); try { // Read serialized worker byte[] serializedWorker = decoder.readBinary(); // Deserialize the worker action Action<WorkerContext> action; try { ObjectInputStream instr = new ClassLoaderObjectInputStream(new ByteArrayInputStream(serializedWorker), getClass().getClassLoader()); action = (Action<WorkerContext>) instr.readObject(); } catch (Exception e) { throw UncheckedException.throwAsUncheckedException(e); } action.execute(new WorkerContext() { public ClassLoader getApplicationClassLoader() { return ClassLoader.getSystemClassLoader(); } @Override public ObjectConnection getServerConnection() { return connection; } }); } finally { connection.stop(); } } finally { messagingServices.close(); } return null; } private void configureLogging(LoggingManagerInternal loggingManager, ObjectConnection connection) { WorkerLoggingProtocol workerLoggingProtocol = connection.addOutgoing(WorkerLoggingProtocol.class); loggingManager.addOutputEventListener(new WorkerOutputEventListener(workerLoggingProtocol)); } MessagingServices createClient() { return new MessagingServices(); } LoggingManagerInternal createLoggingManager() { return LoggingServiceRegistry.newCommandLineProcessLogging().newInstance(LoggingManagerInternal.class); } }
Don't attach stdout and stderr to loggingmanager in worker processes
subprojects/core/src/main/java/org/gradle/process/internal/worker/child/SystemApplicationClassLoaderWorker.java
Don't attach stdout and stderr to loggingmanager in worker processes
Java
apache-2.0
eb3ceabaf7a493fe19b971a0b100a0fc668e8686
0
volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard
/** * Copyright ยฉ 2016-2021 The Thingsboard 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.thingsboard.server.transport.lwm2m.server.ota; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.core.node.codec.CodecException; import org.eclipse.leshan.core.request.ContentFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.thingsboard.common.util.DonAsynchron; import org.thingsboard.server.cache.ota.OtaPackageDataCache; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.device.data.lwm2m.OtherConfiguration; import org.thingsboard.server.common.data.ota.OtaPackageKey; import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus; import org.thingsboard.server.common.transport.TransportService; import org.thingsboard.server.common.transport.TransportServiceCallback; import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.queue.util.TbLwM2mTransportComponent; import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import org.thingsboard.server.transport.lwm2m.server.LwM2mTransportServerHelper; import org.thingsboard.server.transport.lwm2m.server.attributes.LwM2MAttributesService; import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient; import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClientContext; import org.thingsboard.server.transport.lwm2m.server.common.LwM2MExecutorAwareService; import org.thingsboard.server.transport.lwm2m.server.downlink.LwM2mDownlinkMsgHandler; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MExecuteCallback; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MExecuteRequest; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MWriteReplaceRequest; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MWriteResponseCallback; import org.thingsboard.server.transport.lwm2m.server.log.LwM2MTelemetryLogService; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.LwM2MClientFwOtaInfo; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.LwM2MFirmwareUpdateStrategy; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareDeliveryMethod; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareUpdateResult; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareUpdateState; import org.thingsboard.server.transport.lwm2m.server.ota.software.LwM2MClientSwOtaInfo; import org.thingsboard.server.transport.lwm2m.server.ota.software.LwM2MSoftwareUpdateStrategy; import org.thingsboard.server.transport.lwm2m.server.ota.software.SoftwareUpdateResult; import org.thingsboard.server.transport.lwm2m.server.ota.software.SoftwareUpdateState; import org.thingsboard.server.transport.lwm2m.server.store.TbLwM2MClientOtaInfoStore; import org.thingsboard.server.transport.lwm2m.server.uplink.LwM2mUplinkMsgHandler; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import static org.thingsboard.server.common.data.ota.OtaPackageKey.STATE; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.DOWNLOADED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.DOWNLOADING; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.FAILED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATING; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.VERIFIED; import static org.thingsboard.server.common.data.ota.OtaPackageUtil.getAttributeKey; import static org.thingsboard.server.transport.lwm2m.server.LwM2mTransportUtil.LOG_LWM2M_TELEMETRY; import static org.thingsboard.server.transport.lwm2m.server.LwM2mTransportUtil.convertObjectIdToVersionedId; @Slf4j @Service @TbLwM2mTransportComponent @RequiredArgsConstructor public class DefaultLwM2MOtaUpdateService extends LwM2MExecutorAwareService implements LwM2MOtaUpdateService { public static final String FIRMWARE_VERSION = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.VERSION); public static final String FIRMWARE_TITLE = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.TITLE); public static final String FIRMWARE_URL = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.URL); public static final String SOFTWARE_VERSION = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.VERSION); public static final String SOFTWARE_TITLE = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.TITLE); public static final String SOFTWARE_URL = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.URL); public static final String FIRMWARE_UPDATE_COAP_RESOURCE = "tbfw"; public static final String SOFTWARE_UPDATE_COAP_RESOURCE = "tbsw"; private static final String FW_PACKAGE_5_ID = "/5/0/0"; private static final String FW_PACKAGE_19_ID = "/19/0/0"; private static final String FW_URL_ID = "/5/0/1"; private static final String FW_EXECUTE_ID = "/5/0/2"; public static final String FW_STATE_ID = "/5/0/3"; public static final String FW_RESULT_ID = "/5/0/5"; public static final String FW_NAME_ID = "/5/0/6"; public static final String FW_VER_ID = "/5/0/7"; /** * Quectel@Hi15RM1-HLB_V1.0@BC68JAR01A10,V150R100C20B300SP7,V150R100C20B300SP7@8 * Revision:BC68JAR01A10 */ public static final String FW_3_VER_ID = "/3/0/3"; public static final String FW_DELIVERY_METHOD = "/5/0/9"; public static final String SW_3_VER_ID = "/3/0/19"; public static final String SW_NAME_ID = "/9/0/0"; public static final String SW_VER_ID = "/9/0/1"; public static final String SW_PACKAGE_ID = "/9/0/2"; public static final String SW_PACKAGE_URI_ID = "/9/0/3"; public static final String SW_INSTALL_ID = "/9/0/4"; public static final String SW_STATE_ID = "/9/0/7"; public static final String SW_RESULT_ID = "/9/0/9"; public static final String SW_UN_INSTALL_ID = "/9/0/6"; private final Map<String, LwM2MClientFwOtaInfo> fwStates = new ConcurrentHashMap<>(); private final Map<String, LwM2MClientSwOtaInfo> swStates = new ConcurrentHashMap<>(); private final TransportService transportService; private final LwM2mClientContext clientContext; private final LwM2MTransportServerConfig config; private final LwM2mUplinkMsgHandler uplinkHandler; private final LwM2mDownlinkMsgHandler downlinkHandler; private final OtaPackageDataCache otaPackageDataCache; private final LwM2MTelemetryLogService logService; private final LwM2mTransportServerHelper helper; private final TbLwM2MClientOtaInfoStore otaInfoStore; @Autowired @Lazy private LwM2MAttributesService attributesService; @PostConstruct public void init() { super.init(); } @PreDestroy public void destroy() { super.destroy(); } @Override protected int getExecutorSize() { return config.getOtaPoolSize(); } @Override protected String getExecutorName() { return "LwM2M OTA"; } @Override public void init(LwM2mClient client) { //TODO: add locks by client fwInfo. //TODO: check that the client supports FW and SW by checking the supported objects in the model. List<String> attributesToFetch = new ArrayList<>(); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); if (fwInfo.isSupported()) { attributesToFetch.add(FIRMWARE_TITLE); attributesToFetch.add(FIRMWARE_VERSION); attributesToFetch.add(FIRMWARE_URL); } LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); if (swInfo.isSupported()) { attributesToFetch.add(SOFTWARE_TITLE); attributesToFetch.add(SOFTWARE_VERSION); attributesToFetch.add(SOFTWARE_URL); } var clientSettings = clientContext.getProfile(client.getProfileId()).getClientLwM2mSettings(); onFirmwareStrategyUpdate(client, clientSettings); onCurrentSoftwareStrategyUpdate(client, clientSettings); if (!attributesToFetch.isEmpty()) { var future = attributesService.getSharedAttributes(client, attributesToFetch); DonAsynchron.withCallback(future, attrs -> { if (fwInfo.isSupported()) { Optional<String> newFwTitle = getAttributeValue(attrs, FIRMWARE_TITLE); Optional<String> newFwVersion = getAttributeValue(attrs, FIRMWARE_VERSION); Optional<String> newFwUrl = getAttributeValue(attrs, FIRMWARE_URL); if (newFwTitle.isPresent() && newFwVersion.isPresent()) { onTargetFirmwareUpdate(client, newFwTitle.get(), newFwVersion.get(), newFwUrl); } } if (swInfo.isSupported()) { Optional<String> newSwTitle = getAttributeValue(attrs, SOFTWARE_TITLE); Optional<String> newSwVersion = getAttributeValue(attrs, SOFTWARE_VERSION); Optional<String> newSwUrl = getAttributeValue(attrs, SOFTWARE_URL); if (newSwTitle.isPresent() && newSwVersion.isPresent()) { onTargetSoftwareUpdate(client, newSwTitle.get(), newSwVersion.get(), newSwUrl); } } }, throwable -> { if (fwInfo.isSupported()) { update(fwInfo); } }, executor); } } @Override public void forceFirmwareUpdate(LwM2mClient client) { LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setRetryAttempts(0); fwInfo.setFailedPackageId(null); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onTargetFirmwareUpdate(LwM2mClient client, String newFirmwareTitle, String newFirmwareVersion, Optional<String> newFirmwareUrl) { LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.updateTarget(newFirmwareTitle, newFirmwareVersion, newFirmwareUrl); update(fwInfo); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onCurrentFirmwareNameUpdate(LwM2mClient client, String name) { log.debug("[{}] Current fw name: {}", client.getEndpoint(), name); getOrInitFwInfo(client).setCurrentName(name); } @Override public void onCurrentSoftwareNameUpdate(LwM2mClient client, String name) { log.debug("[{}] Current sw name: {}", client.getEndpoint(), name); getOrInitSwInfo(client).setCurrentName(name); } @Override public void onFirmwareStrategyUpdate(LwM2mClient client, OtherConfiguration configuration) { log.debug("[{}] Current fw strategy: {}", client.getEndpoint(), configuration.getFwUpdateStrategy()); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setStrategy(LwM2MFirmwareUpdateStrategy.fromStrategyFwByCode(configuration.getFwUpdateStrategy())); fwInfo.setBaseUrl(configuration.getFwUpdateResource()); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onCurrentSoftwareStrategyUpdate(LwM2mClient client, OtherConfiguration configuration) { log.debug("[{}] Current sw strategy: {}", client.getEndpoint(), configuration.getSwUpdateStrategy()); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); swInfo.setStrategy(LwM2MSoftwareUpdateStrategy.fromStrategySwByCode(configuration.getSwUpdateStrategy())); swInfo.setBaseUrl(configuration.getSwUpdateResource()); startSoftwareUpdateIfNeeded(client, swInfo); } @Override public void onCurrentFirmwareVersion3Update(LwM2mClient client, String version) { log.debug("[{}] Current fw version(3): {}", client.getEndpoint(), version); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setCurrentVersion3(version); } @Override public void onCurrentFirmwareVersionUpdate(LwM2mClient client, String version) { log.debug("[{}] Current fw version(5): {}", client.getEndpoint(), version); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setCurrentVersion(version); } @Override public void onCurrentFirmwareStateUpdate(LwM2mClient client, Long stateCode) { log.debug("[{}] Current fw state: {}", client.getEndpoint(), stateCode); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); FirmwareUpdateState state = FirmwareUpdateState.fromStateFwByCode(stateCode.intValue()); if (FirmwareUpdateState.DOWNLOADED.equals(state)) { executeFwUpdate(client); } fwInfo.setUpdateState(state); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(state); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, fwInfo, otaStatus, "Firmware Update State: " + state.name())); update(fwInfo); } @Override public void onCurrentFirmwareResultUpdate(LwM2mClient client, Long code) { log.debug("[{}] Current fw result: {}", client.getEndpoint(), code); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); FirmwareUpdateResult result = FirmwareUpdateResult.fromUpdateResultFwByCode(code.intValue()); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(result); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, fwInfo, otaStatus, "Firmware Update Result: " + result.name())); if (result.isAgain() && fwInfo.getRetryAttempts() <= 2) { fwInfo.setRetryAttempts(fwInfo.getRetryAttempts() + 1); startFirmwareUpdateIfNeeded(client, fwInfo); } else { fwInfo.update(result); } update(fwInfo); } @Override public void onCurrentFirmwareDeliveryMethodUpdate(LwM2mClient client, Long value) { log.debug("[{}] Current fw delivery method: {}", client.getEndpoint(), value); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setDeliveryMethod(value.intValue()); } @Override public void onCurrentSoftwareVersion3Update(LwM2mClient client, String version) { log.debug("[{}] Current sw version(3): {}", client.getEndpoint(), version); getOrInitSwInfo(client).setCurrentVersion3(version); } @Override public void onCurrentSoftwareVersionUpdate(LwM2mClient client, String version) { log.debug("[{}] Current sw version(9): {}", client.getEndpoint(), version); getOrInitSwInfo(client).setCurrentVersion(version); } @Override public void onCurrentSoftwareStateUpdate(LwM2mClient client, Long stateCode) { log.debug("[{}] Current sw state: {}", client.getEndpoint(), stateCode); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); SoftwareUpdateState state = SoftwareUpdateState.fromUpdateStateSwByCode(stateCode.intValue()); if (SoftwareUpdateState.INITIAL.equals(state)) { startSoftwareUpdateIfNeeded(client, swInfo); } else if (SoftwareUpdateState.DELIVERED.equals(state)) { executeSwInstall(client); } swInfo.setUpdateState(state); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(state); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, swInfo, otaStatus, "Firmware Update State: " + state.name())); update(swInfo); } @Override public void onCurrentSoftwareResultUpdate(LwM2mClient client, Long code) { log.debug("[{}] Current sw result: {}", client.getEndpoint(), code); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); SoftwareUpdateResult result = SoftwareUpdateResult.fromUpdateResultSwByCode(code.intValue()); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(result); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, swInfo, otaStatus, "Software Update Result: " + result.name())); if (result.isAgain() && swInfo.getRetryAttempts() <= 2) { swInfo.setRetryAttempts(swInfo.getRetryAttempts() + 1); startSoftwareUpdateIfNeeded(client, swInfo); } else { swInfo.update(result); } update(swInfo); } @Override public void onTargetSoftwareUpdate(LwM2mClient client, String newSoftwareTitle, String newSoftwareVersion, Optional<String> newFirmwareUrl) { LwM2MClientSwOtaInfo fwInfo = getOrInitSwInfo(client); fwInfo.updateTarget(newSoftwareTitle, newSoftwareVersion, newFirmwareUrl); update(fwInfo); startSoftwareUpdateIfNeeded(client, fwInfo); } private void startFirmwareUpdateIfNeeded(LwM2mClient client, LwM2MClientFwOtaInfo fwInfo) { try { if (!fwInfo.isSupported()) { log.debug("[{}] Fw update is not supported: {}", client.getEndpoint(), fwInfo); sendStateUpdateToTelemetry(client, fwInfo, OtaPackageUpdateStatus.FAILED, "Client does not support firmware update or profile misconfiguration!"); } else if (fwInfo.isUpdateRequired()) { if (StringUtils.isNotEmpty(fwInfo.getTargetUrl())) { log.debug("[{}] Starting update to [{}{}] using URL: {}", client.getEndpoint(), fwInfo.getTargetName(), fwInfo.getTargetVersion(), fwInfo.getTargetUrl()); startUpdateUsingUrl(client, FW_URL_ID, fwInfo.getTargetUrl()); } else { log.debug("[{}] Starting update to [{}{}] using binary", client.getEndpoint(), fwInfo.getTargetName(), fwInfo.getTargetVersion()); startUpdateUsingBinary(client, fwInfo); } } } catch (Exception e) { log.info("[{}] failed to update client: {}", client.getEndpoint(), fwInfo, e); sendStateUpdateToTelemetry(client, fwInfo, OtaPackageUpdateStatus.FAILED, "Internal server error: " + e.getMessage()); } } private void startSoftwareUpdateIfNeeded(LwM2mClient client, LwM2MClientSwOtaInfo swInfo) { try { if (!swInfo.isSupported()) { log.debug("[{}] Sw update is not supported: {}", client.getEndpoint(), swInfo); sendStateUpdateToTelemetry(client, swInfo, OtaPackageUpdateStatus.FAILED, "Client does not support software update or profile misconfiguration!"); } else if (swInfo.isUpdateRequired()) { if (SoftwareUpdateState.INSTALLED.equals(swInfo.getUpdateState())) { log.debug("[{}] Attempt to restore the update state: {}", client.getEndpoint(), swInfo.getUpdateState()); executeSwUninstallForUpdate(client); } else { if (StringUtils.isNotEmpty(swInfo.getTargetUrl())) { log.debug("[{}] Starting update to [{}{}] using URL: {}", client.getEndpoint(), swInfo.getTargetName(), swInfo.getTargetVersion(), swInfo.getTargetUrl()); startUpdateUsingUrl(client, SW_PACKAGE_URI_ID, swInfo.getTargetUrl()); } else { log.debug("[{}] Starting update to [{}{}] using binary", client.getEndpoint(), swInfo.getTargetName(), swInfo.getTargetVersion()); startUpdateUsingBinary(client, swInfo); } } } } catch (Exception e) { log.info("[{}] failed to update client: {}", client.getEndpoint(), swInfo, e); sendStateUpdateToTelemetry(client, swInfo, OtaPackageUpdateStatus.FAILED, "Internal server error: " + e.getMessage()); } } public void startUpdateUsingBinary(LwM2mClient client, LwM2MClientSwOtaInfo swInfo) { this.transportService.process(client.getSession(), createOtaPackageRequestMsg(client.getSession(), swInfo.getType().name()), new TransportServiceCallback<>() { @Override public void onSuccess(TransportProtos.GetOtaPackageResponseMsg response) { executor.submit(() -> doUpdateSoftwareUsingBinary(response, swInfo, client)); } @Override public void onError(Throwable e) { logService.log(client, "Failed to process software update: " + e.getMessage()); } }); } private void startUpdateUsingUrl(LwM2mClient client, String id, String url) { String targetIdVer = convertObjectIdToVersionedId(id, client.getRegistration()); TbLwM2MWriteReplaceRequest request = TbLwM2MWriteReplaceRequest.builder().versionedId(targetIdVer).value(url).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendWriteReplaceRequest(client, request, new TbLwM2MWriteResponseCallback(uplinkHandler, logService, client, targetIdVer)); } public void startUpdateUsingBinary(LwM2mClient client, LwM2MClientFwOtaInfo fwInfo) { this.transportService.process(client.getSession(), createOtaPackageRequestMsg(client.getSession(), fwInfo.getType().name()), new TransportServiceCallback<>() { @Override public void onSuccess(TransportProtos.GetOtaPackageResponseMsg response) { executor.submit(() -> doUpdateFirmwareUsingBinary(response, fwInfo, client)); } @Override public void onError(Throwable e) { logService.log(client, "Failed to process firmware update: " + e.getMessage()); } }); } private void doUpdateFirmwareUsingBinary(TransportProtos.GetOtaPackageResponseMsg response, LwM2MClientFwOtaInfo info, LwM2mClient client) { if (TransportProtos.ResponseStatus.SUCCESS.equals(response.getResponseStatus())) { UUID otaPackageId = new UUID(response.getOtaPackageIdMSB(), response.getOtaPackageIdLSB()); LwM2MFirmwareUpdateStrategy strategy; if (info.getDeliveryMethod() == null || info.getDeliveryMethod() == FirmwareDeliveryMethod.BOTH.code) { strategy = info.getStrategy(); } else { strategy = info.getDeliveryMethod() == FirmwareDeliveryMethod.PULL.code ? LwM2MFirmwareUpdateStrategy.OBJ_5_TEMP_URL : LwM2MFirmwareUpdateStrategy.OBJ_5_BINARY; } switch (strategy) { case OBJ_5_BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(FW_PACKAGE_5_ID, client.getRegistration()), otaPackageId); break; case OBJ_19_BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(FW_PACKAGE_19_ID, client.getRegistration()), otaPackageId); break; case OBJ_5_TEMP_URL: startUpdateUsingUrl(client, FW_URL_ID, info.getBaseUrl() + "/" + FIRMWARE_UPDATE_COAP_RESOURCE + "/" + otaPackageId.toString()); break; default: sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Unsupported strategy: " + strategy.name()); } } else { sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Failed to fetch OTA package: " + response.getResponseStatus()); } } private void doUpdateSoftwareUsingBinary(TransportProtos.GetOtaPackageResponseMsg response, LwM2MClientSwOtaInfo info, LwM2mClient client) { if (TransportProtos.ResponseStatus.SUCCESS.equals(response.getResponseStatus())) { UUID otaPackageId = new UUID(response.getOtaPackageIdMSB(), response.getOtaPackageIdLSB()); LwM2MSoftwareUpdateStrategy strategy = info.getStrategy(); switch (strategy) { case BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(SW_PACKAGE_ID, client.getRegistration()), otaPackageId); break; case TEMP_URL: startUpdateUsingUrl(client, SW_PACKAGE_URI_ID, info.getBaseUrl() + "/" + FIRMWARE_UPDATE_COAP_RESOURCE + "/" + otaPackageId.toString()); break; default: sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Unsupported strategy: " + strategy.name()); } } else { sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Failed to fetch OTA package: " + response.getResponseStatus()); } } private void startUpdateUsingBinary(LwM2mClient client, String versionedId, UUID otaPackageId) { byte[] firmwareChunk = otaPackageDataCache.get(otaPackageId.toString(), 0, 0); TbLwM2MWriteReplaceRequest writeRequest = TbLwM2MWriteReplaceRequest.builder().versionedId(versionedId) .value(firmwareChunk).contentFormat(ContentFormat.OPAQUE) .timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendWriteReplaceRequest(client, writeRequest, new TbLwM2MWriteResponseCallback(uplinkHandler, logService, client, versionedId)); } private TransportProtos.GetOtaPackageRequestMsg createOtaPackageRequestMsg(TransportProtos.SessionInfoProto sessionInfo, String nameFwSW) { return TransportProtos.GetOtaPackageRequestMsg.newBuilder() .setDeviceIdMSB(sessionInfo.getDeviceIdMSB()) .setDeviceIdLSB(sessionInfo.getDeviceIdLSB()) .setTenantIdMSB(sessionInfo.getTenantIdMSB()) .setTenantIdLSB(sessionInfo.getTenantIdLSB()) .setType(nameFwSW) .build(); } private void executeFwUpdate(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(FW_EXECUTE_ID).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, FW_EXECUTE_ID)); } private void executeSwInstall(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(SW_INSTALL_ID).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, SW_INSTALL_ID)); } private void executeSwUninstallForUpdate(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(SW_UN_INSTALL_ID).params("1").timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, SW_INSTALL_ID)); } private Optional<String> getAttributeValue(List<TransportProtos.TsKvProto> attrs, String keyName) { for (TransportProtos.TsKvProto attr : attrs) { if (keyName.equals(attr.getKv().getKey())) { if (attr.getKv().getType().equals(TransportProtos.KeyValueType.STRING_V)) { return Optional.of(attr.getKv().getStringV()); } else { return Optional.empty(); } } } return Optional.empty(); } private LwM2MClientFwOtaInfo getOrInitFwInfo(LwM2mClient client) { return this.fwStates.computeIfAbsent(client.getEndpoint(), endpoint -> { LwM2MClientFwOtaInfo info = otaInfoStore.getFw(endpoint); if (info == null) { var profile = clientContext.getProfile(client.getProfileId()); info = new LwM2MClientFwOtaInfo(endpoint, profile.getClientLwM2mSettings().getFwUpdateResource(), LwM2MFirmwareUpdateStrategy.fromStrategyFwByCode(profile.getClientLwM2mSettings().getFwUpdateStrategy())); update(info); } return info; }); } private LwM2MClientSwOtaInfo getOrInitSwInfo(LwM2mClient client) { return this.swStates.computeIfAbsent(client.getEndpoint(), endpoint -> { LwM2MClientSwOtaInfo info = otaInfoStore.getSw(endpoint); if (info == null) { var profile = clientContext.getProfile(client.getProfileId()); info = new LwM2MClientSwOtaInfo(endpoint, profile.getClientLwM2mSettings().getSwUpdateResource(), LwM2MSoftwareUpdateStrategy.fromStrategySwByCode(profile.getClientLwM2mSettings().getSwUpdateStrategy())); update(info); } return info; }); } private void update(LwM2MClientFwOtaInfo info) { otaInfoStore.putFw(info); } private void update(LwM2MClientSwOtaInfo info) { otaInfoStore.putSw(info); } private void sendStateUpdateToTelemetry(LwM2mClient client, LwM2MClientOtaInfo<?, ?, ?> fwInfo, OtaPackageUpdateStatus status, String log) { List<TransportProtos.KeyValueProto> result = new ArrayList<>(); TransportProtos.KeyValueProto.Builder kvProto = TransportProtos.KeyValueProto.newBuilder().setKey(getAttributeKey(fwInfo.getType(), STATE)); kvProto.setType(TransportProtos.KeyValueType.STRING_V).setStringV(status.name()); result.add(kvProto.build()); kvProto = TransportProtos.KeyValueProto.newBuilder().setKey(LOG_LWM2M_TELEMETRY); kvProto.setType(TransportProtos.KeyValueType.STRING_V).setStringV(log); result.add(kvProto.build()); helper.sendParametersOnThingsboardTelemetry(result, client.getSession()); } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(FirmwareUpdateResult fwUpdateResult) { switch (fwUpdateResult) { case INITIAL: return Optional.empty(); case UPDATE_SUCCESSFULLY: return Optional.of(UPDATED); case NOT_ENOUGH: case OUT_OFF_MEMORY: case CONNECTION_LOST: case INTEGRITY_CHECK_FAILURE: case UNSUPPORTED_TYPE: case INVALID_URI: case UPDATE_FAILED: case UNSUPPORTED_PROTOCOL: return Optional.of(FAILED); default: throw new CodecException("Invalid value stateFw %s for FirmwareUpdateStatus.", fwUpdateResult.name()); } } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(FirmwareUpdateState firmwareUpdateState) { switch (firmwareUpdateState) { case IDLE: return Optional.empty(); case DOWNLOADING: return Optional.of(DOWNLOADING); case DOWNLOADED: return Optional.of(DOWNLOADED); case UPDATING: return Optional.of(UPDATING); default: throw new CodecException("Invalid value stateFw %d for FirmwareUpdateStatus.", firmwareUpdateState); } } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(SoftwareUpdateState swUpdateState) { switch (swUpdateState) { case INITIAL: return Optional.empty(); case DOWNLOAD_STARTED: return Optional.of(DOWNLOADING); case DOWNLOADED: return Optional.of(DOWNLOADING); case DELIVERED: return Optional.of(DOWNLOADED); case INSTALLED: return Optional.empty(); default: throw new CodecException("Invalid value stateSw %d for SoftwareUpdateState.", swUpdateState); } } /** * FirmwareUpdateStatus { * DOWNLOADING, DOWNLOADED, VERIFIED, UPDATING, UPDATED, FAILED */ public static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(SoftwareUpdateResult softwareUpdateResult) { switch (softwareUpdateResult) { case INITIAL: return Optional.empty(); case DOWNLOADING: return Optional.of(DOWNLOADING); case SUCCESSFULLY_INSTALLED: return Optional.of(UPDATED); case SUCCESSFULLY_DOWNLOADED_VERIFIED: return Optional.of(VERIFIED); case NOT_ENOUGH_STORAGE: case OUT_OFF_MEMORY: case CONNECTION_LOST: case PACKAGE_CHECK_FAILURE: case UNSUPPORTED_PACKAGE_TYPE: case INVALID_URI: case UPDATE_ERROR: case INSTALL_FAILURE: case UN_INSTALL_FAILURE: return Optional.of(FAILED); default: throw new CodecException("Invalid value stateFw %s for FirmwareUpdateStatus.", softwareUpdateResult.name()); } } }
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ota/DefaultLwM2MOtaUpdateService.java
/** * Copyright ยฉ 2016-2021 The Thingsboard 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.thingsboard.server.transport.lwm2m.server.ota; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.eclipse.leshan.core.node.codec.CodecException; import org.eclipse.leshan.core.request.ContentFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.thingsboard.common.util.DonAsynchron; import org.thingsboard.server.cache.ota.OtaPackageDataCache; import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.device.data.lwm2m.OtherConfiguration; import org.thingsboard.server.common.data.ota.OtaPackageKey; import org.thingsboard.server.common.data.ota.OtaPackageType; import org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus; import org.thingsboard.server.common.transport.TransportService; import org.thingsboard.server.common.transport.TransportServiceCallback; import org.thingsboard.server.gen.transport.TransportProtos; import org.thingsboard.server.queue.util.TbLwM2mTransportComponent; import org.thingsboard.server.transport.lwm2m.config.LwM2MTransportServerConfig; import org.thingsboard.server.transport.lwm2m.server.LwM2mTransportServerHelper; import org.thingsboard.server.transport.lwm2m.server.attributes.LwM2MAttributesService; import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClient; import org.thingsboard.server.transport.lwm2m.server.client.LwM2mClientContext; import org.thingsboard.server.transport.lwm2m.server.common.LwM2MExecutorAwareService; import org.thingsboard.server.transport.lwm2m.server.downlink.LwM2mDownlinkMsgHandler; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MExecuteCallback; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MExecuteRequest; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MWriteReplaceRequest; import org.thingsboard.server.transport.lwm2m.server.downlink.TbLwM2MWriteResponseCallback; import org.thingsboard.server.transport.lwm2m.server.log.LwM2MTelemetryLogService; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.LwM2MClientFwOtaInfo; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.LwM2MFirmwareUpdateStrategy; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareDeliveryMethod; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareUpdateResult; import org.thingsboard.server.transport.lwm2m.server.ota.firmware.FirmwareUpdateState; import org.thingsboard.server.transport.lwm2m.server.ota.software.LwM2MClientSwOtaInfo; import org.thingsboard.server.transport.lwm2m.server.ota.software.LwM2MSoftwareUpdateStrategy; import org.thingsboard.server.transport.lwm2m.server.ota.software.SoftwareUpdateResult; import org.thingsboard.server.transport.lwm2m.server.ota.software.SoftwareUpdateState; import org.thingsboard.server.transport.lwm2m.server.store.TbLwM2MClientOtaInfoStore; import org.thingsboard.server.transport.lwm2m.server.uplink.LwM2mUplinkMsgHandler; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import static org.thingsboard.server.common.data.ota.OtaPackageKey.STATE; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.DOWNLOADED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.DOWNLOADING; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.FAILED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATED; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.UPDATING; import static org.thingsboard.server.common.data.ota.OtaPackageUpdateStatus.VERIFIED; import static org.thingsboard.server.common.data.ota.OtaPackageUtil.getAttributeKey; import static org.thingsboard.server.transport.lwm2m.server.LwM2mTransportUtil.LOG_LWM2M_TELEMETRY; import static org.thingsboard.server.transport.lwm2m.server.LwM2mTransportUtil.convertObjectIdToVersionedId; @Slf4j @Service @TbLwM2mTransportComponent @RequiredArgsConstructor public class DefaultLwM2MOtaUpdateService extends LwM2MExecutorAwareService implements LwM2MOtaUpdateService { public static final String FIRMWARE_VERSION = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.VERSION); public static final String FIRMWARE_TITLE = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.TITLE); public static final String FIRMWARE_URL = getAttributeKey(OtaPackageType.FIRMWARE, OtaPackageKey.URL); public static final String SOFTWARE_VERSION = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.VERSION); public static final String SOFTWARE_TITLE = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.TITLE); public static final String SOFTWARE_URL = getAttributeKey(OtaPackageType.SOFTWARE, OtaPackageKey.URL); public static final String FIRMWARE_UPDATE_COAP_RESOURCE = "tbfw"; public static final String SOFTWARE_UPDATE_COAP_RESOURCE = "tbsw"; private static final String FW_PACKAGE_5_ID = "/5/0/0"; private static final String FW_PACKAGE_19_ID = "/19/0/0"; private static final String FW_URL_ID = "/5/0/1"; private static final String FW_EXECUTE_ID = "/5/0/2"; public static final String FW_STATE_ID = "/5/0/3"; public static final String FW_RESULT_ID = "/5/0/5"; public static final String FW_NAME_ID = "/5/0/6"; public static final String FW_VER_ID = "/5/0/7"; /** * Quectel@Hi15RM1-HLB_V1.0@BC68JAR01A10,V150R100C20B300SP7,V150R100C20B300SP7@8 * Revision:BC68JAR01A10 */ public static final String FW_3_VER_ID = "/3/0/3"; public static final String FW_DELIVERY_METHOD = "/5/0/9"; public static final String SW_3_VER_ID = "/3/0/19"; public static final String SW_NAME_ID = "/9/0/0"; public static final String SW_VER_ID = "/9/0/1"; public static final String SW_PACKAGE_ID = "/9/0/2"; public static final String SW_PACKAGE_URI_ID = "/9/0/3"; public static final String SW_INSTALL_ID = "/9/0/4"; public static final String SW_STATE_ID = "/9/0/7"; public static final String SW_RESULT_ID = "/9/0/9"; public static final String SW_UN_INSTALL_ID = "/9/0/6"; private final Map<String, LwM2MClientFwOtaInfo> fwStates = new ConcurrentHashMap<>(); private final Map<String, LwM2MClientSwOtaInfo> swStates = new ConcurrentHashMap<>(); private final TransportService transportService; private final LwM2mClientContext clientContext; private final LwM2MTransportServerConfig config; private final LwM2mUplinkMsgHandler uplinkHandler; private final LwM2mDownlinkMsgHandler downlinkHandler; private final OtaPackageDataCache otaPackageDataCache; private final LwM2MTelemetryLogService logService; private final LwM2mTransportServerHelper helper; private final TbLwM2MClientOtaInfoStore otaInfoStore; @Autowired @Lazy private LwM2MAttributesService attributesService; @PostConstruct public void init() { super.init(); } @PreDestroy public void destroy() { super.destroy(); } @Override protected int getExecutorSize() { return config.getOtaPoolSize(); } @Override protected String getExecutorName() { return "LwM2M OTA"; } @Override public void init(LwM2mClient client) { //TODO: add locks by client fwInfo. //TODO: check that the client supports FW and SW by checking the supported objects in the model. List<String> attributesToFetch = new ArrayList<>(); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); if (fwInfo.isSupported()) { attributesToFetch.add(FIRMWARE_TITLE); attributesToFetch.add(FIRMWARE_VERSION); attributesToFetch.add(FIRMWARE_URL); } LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); if (swInfo.isSupported()) { attributesToFetch.add(SOFTWARE_TITLE); attributesToFetch.add(SOFTWARE_VERSION); attributesToFetch.add(SOFTWARE_URL); } if (!attributesToFetch.isEmpty()) { var future = attributesService.getSharedAttributes(client, attributesToFetch); DonAsynchron.withCallback(future, attrs -> { if (fwInfo.isSupported()) { Optional<String> newFwTitle = getAttributeValue(attrs, FIRMWARE_TITLE); Optional<String> newFwVersion = getAttributeValue(attrs, FIRMWARE_VERSION); Optional<String> newFwUrl = getAttributeValue(attrs, FIRMWARE_URL); if (newFwTitle.isPresent() && newFwVersion.isPresent()) { onTargetFirmwareUpdate(client, newFwTitle.get(), newFwVersion.get(), newFwUrl); } } if (swInfo.isSupported()) { Optional<String> newSwTitle = getAttributeValue(attrs, SOFTWARE_TITLE); Optional<String> newSwVersion = getAttributeValue(attrs, SOFTWARE_VERSION); Optional<String> newSwUrl = getAttributeValue(attrs, SOFTWARE_URL); if (newSwTitle.isPresent() && newSwVersion.isPresent()) { onTargetSoftwareUpdate(client, newSwTitle.get(), newSwVersion.get(), newSwUrl); } } }, throwable -> { if (fwInfo.isSupported()) { update(fwInfo); } }, executor); } var clientSettings = clientContext.getProfile(client.getProfileId()).getClientLwM2mSettings(); onFirmwareStrategyUpdate(client, clientSettings); onCurrentSoftwareStrategyUpdate(client, clientSettings); } @Override public void forceFirmwareUpdate(LwM2mClient client) { LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setRetryAttempts(0); fwInfo.setFailedPackageId(null); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onTargetFirmwareUpdate(LwM2mClient client, String newFirmwareTitle, String newFirmwareVersion, Optional<String> newFirmwareUrl) { LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.updateTarget(newFirmwareTitle, newFirmwareVersion, newFirmwareUrl); update(fwInfo); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onCurrentFirmwareNameUpdate(LwM2mClient client, String name) { log.debug("[{}] Current fw name: {}", client.getEndpoint(), name); getOrInitFwInfo(client).setCurrentName(name); } @Override public void onCurrentSoftwareNameUpdate(LwM2mClient client, String name) { log.debug("[{}] Current sw name: {}", client.getEndpoint(), name); getOrInitSwInfo(client).setCurrentName(name); } @Override public void onFirmwareStrategyUpdate(LwM2mClient client, OtherConfiguration configuration) { log.debug("[{}] Current fw strategy: {}", client.getEndpoint(), configuration.getFwUpdateStrategy()); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setStrategy(LwM2MFirmwareUpdateStrategy.fromStrategyFwByCode(configuration.getFwUpdateStrategy())); fwInfo.setBaseUrl(configuration.getFwUpdateResource()); startFirmwareUpdateIfNeeded(client, fwInfo); } @Override public void onCurrentSoftwareStrategyUpdate(LwM2mClient client, OtherConfiguration configuration) { log.debug("[{}] Current sw strategy: {}", client.getEndpoint(), configuration.getSwUpdateStrategy()); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); swInfo.setStrategy(LwM2MSoftwareUpdateStrategy.fromStrategySwByCode(configuration.getSwUpdateStrategy())); swInfo.setBaseUrl(configuration.getSwUpdateResource()); startSoftwareUpdateIfNeeded(client, swInfo); } @Override public void onCurrentFirmwareVersion3Update(LwM2mClient client, String version) { log.debug("[{}] Current fw version(3): {}", client.getEndpoint(), version); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setCurrentVersion3(version); } @Override public void onCurrentFirmwareVersionUpdate(LwM2mClient client, String version) { log.debug("[{}] Current fw version(5): {}", client.getEndpoint(), version); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setCurrentVersion(version); } @Override public void onCurrentFirmwareStateUpdate(LwM2mClient client, Long stateCode) { log.debug("[{}] Current fw state: {}", client.getEndpoint(), stateCode); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); FirmwareUpdateState state = FirmwareUpdateState.fromStateFwByCode(stateCode.intValue()); if (FirmwareUpdateState.DOWNLOADED.equals(state)) { executeFwUpdate(client); } fwInfo.setUpdateState(state); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(state); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, fwInfo, otaStatus, "Firmware Update State: " + state.name())); update(fwInfo); } @Override public void onCurrentFirmwareResultUpdate(LwM2mClient client, Long code) { log.debug("[{}] Current fw result: {}", client.getEndpoint(), code); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); FirmwareUpdateResult result = FirmwareUpdateResult.fromUpdateResultFwByCode(code.intValue()); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(result); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, fwInfo, otaStatus, "Firmware Update Result: " + result.name())); if (result.isAgain() && fwInfo.getRetryAttempts() <= 2) { fwInfo.setRetryAttempts(fwInfo.getRetryAttempts() + 1); startFirmwareUpdateIfNeeded(client, fwInfo); } else { fwInfo.update(result); } update(fwInfo); } @Override public void onCurrentFirmwareDeliveryMethodUpdate(LwM2mClient client, Long value) { log.debug("[{}] Current fw delivery method: {}", client.getEndpoint(), value); LwM2MClientFwOtaInfo fwInfo = getOrInitFwInfo(client); fwInfo.setDeliveryMethod(value.intValue()); } @Override public void onCurrentSoftwareVersion3Update(LwM2mClient client, String version) { log.debug("[{}] Current sw version(3): {}", client.getEndpoint(), version); getOrInitSwInfo(client).setCurrentVersion3(version); } @Override public void onCurrentSoftwareVersionUpdate(LwM2mClient client, String version) { log.debug("[{}] Current sw version(9): {}", client.getEndpoint(), version); getOrInitSwInfo(client).setCurrentVersion(version); } @Override public void onCurrentSoftwareStateUpdate(LwM2mClient client, Long stateCode) { log.debug("[{}] Current sw state: {}", client.getEndpoint(), stateCode); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); SoftwareUpdateState state = SoftwareUpdateState.fromUpdateStateSwByCode(stateCode.intValue()); if (SoftwareUpdateState.INITIAL.equals(state)) { startSoftwareUpdateIfNeeded(client, swInfo); } else if (SoftwareUpdateState.DELIVERED.equals(state)) { executeSwInstall(client); } swInfo.setUpdateState(state); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(state); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, swInfo, otaStatus, "Firmware Update State: " + state.name())); update(swInfo); } @Override public void onCurrentSoftwareResultUpdate(LwM2mClient client, Long code) { log.debug("[{}] Current sw result: {}", client.getEndpoint(), code); LwM2MClientSwOtaInfo swInfo = getOrInitSwInfo(client); SoftwareUpdateResult result = SoftwareUpdateResult.fromUpdateResultSwByCode(code.intValue()); Optional<OtaPackageUpdateStatus> status = toOtaPackageUpdateStatus(result); status.ifPresent(otaStatus -> sendStateUpdateToTelemetry(client, swInfo, otaStatus, "Software Update Result: " + result.name())); if (result.isAgain() && swInfo.getRetryAttempts() <= 2) { swInfo.setRetryAttempts(swInfo.getRetryAttempts() + 1); startSoftwareUpdateIfNeeded(client, swInfo); } else { swInfo.update(result); } update(swInfo); } @Override public void onTargetSoftwareUpdate(LwM2mClient client, String newSoftwareTitle, String newSoftwareVersion, Optional<String> newFirmwareUrl) { LwM2MClientSwOtaInfo fwInfo = getOrInitSwInfo(client); fwInfo.updateTarget(newSoftwareTitle, newSoftwareVersion, newFirmwareUrl); update(fwInfo); startSoftwareUpdateIfNeeded(client, fwInfo); } private void startFirmwareUpdateIfNeeded(LwM2mClient client, LwM2MClientFwOtaInfo fwInfo) { try { if (!fwInfo.isSupported()) { log.debug("[{}] Fw update is not supported: {}", client.getEndpoint(), fwInfo); sendStateUpdateToTelemetry(client, fwInfo, OtaPackageUpdateStatus.FAILED, "Client does not support firmware update or profile misconfiguration!"); } else if (fwInfo.isUpdateRequired()) { if (StringUtils.isNotEmpty(fwInfo.getTargetUrl())) { log.debug("[{}] Starting update to [{}{}] using URL: {}", client.getEndpoint(), fwInfo.getTargetName(), fwInfo.getTargetVersion(), fwInfo.getTargetUrl()); startUpdateUsingUrl(client, FW_URL_ID, fwInfo.getTargetUrl()); } else { log.debug("[{}] Starting update to [{}{}] using binary", client.getEndpoint(), fwInfo.getTargetName(), fwInfo.getTargetVersion()); startUpdateUsingBinary(client, fwInfo); } } } catch (Exception e) { log.info("[{}] failed to update client: {}", client.getEndpoint(), fwInfo, e); sendStateUpdateToTelemetry(client, fwInfo, OtaPackageUpdateStatus.FAILED, "Internal server error: " + e.getMessage()); } } private void startSoftwareUpdateIfNeeded(LwM2mClient client, LwM2MClientSwOtaInfo swInfo) { try { if (!swInfo.isSupported()) { log.debug("[{}] Sw update is not supported: {}", client.getEndpoint(), swInfo); sendStateUpdateToTelemetry(client, swInfo, OtaPackageUpdateStatus.FAILED, "Client does not support software update or profile misconfiguration!"); } else if (swInfo.isUpdateRequired()) { if (SoftwareUpdateState.INSTALLED.equals(swInfo.getUpdateState())) { log.debug("[{}] Attempt to restore the update state: {}", client.getEndpoint(), swInfo.getUpdateState()); executeSwUninstallForUpdate(client); } else { if (StringUtils.isNotEmpty(swInfo.getTargetUrl())) { log.debug("[{}] Starting update to [{}{}] using URL: {}", client.getEndpoint(), swInfo.getTargetName(), swInfo.getTargetVersion(), swInfo.getTargetUrl()); startUpdateUsingUrl(client, SW_PACKAGE_URI_ID, swInfo.getTargetUrl()); } else { log.debug("[{}] Starting update to [{}{}] using binary", client.getEndpoint(), swInfo.getTargetName(), swInfo.getTargetVersion()); startUpdateUsingBinary(client, swInfo); } } } } catch (Exception e) { log.info("[{}] failed to update client: {}", client.getEndpoint(), swInfo, e); sendStateUpdateToTelemetry(client, swInfo, OtaPackageUpdateStatus.FAILED, "Internal server error: " + e.getMessage()); } } public void startUpdateUsingBinary(LwM2mClient client, LwM2MClientSwOtaInfo swInfo) { this.transportService.process(client.getSession(), createOtaPackageRequestMsg(client.getSession(), swInfo.getType().name()), new TransportServiceCallback<>() { @Override public void onSuccess(TransportProtos.GetOtaPackageResponseMsg response) { executor.submit(() -> doUpdateSoftwareUsingBinary(response, swInfo, client)); } @Override public void onError(Throwable e) { logService.log(client, "Failed to process software update: " + e.getMessage()); } }); } private void startUpdateUsingUrl(LwM2mClient client, String id, String url) { String targetIdVer = convertObjectIdToVersionedId(id, client.getRegistration()); TbLwM2MWriteReplaceRequest request = TbLwM2MWriteReplaceRequest.builder().versionedId(targetIdVer).value(url).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendWriteReplaceRequest(client, request, new TbLwM2MWriteResponseCallback(uplinkHandler, logService, client, targetIdVer)); } public void startUpdateUsingBinary(LwM2mClient client, LwM2MClientFwOtaInfo fwInfo) { this.transportService.process(client.getSession(), createOtaPackageRequestMsg(client.getSession(), fwInfo.getType().name()), new TransportServiceCallback<>() { @Override public void onSuccess(TransportProtos.GetOtaPackageResponseMsg response) { executor.submit(() -> doUpdateFirmwareUsingBinary(response, fwInfo, client)); } @Override public void onError(Throwable e) { logService.log(client, "Failed to process firmware update: " + e.getMessage()); } }); } private void doUpdateFirmwareUsingBinary(TransportProtos.GetOtaPackageResponseMsg response, LwM2MClientFwOtaInfo info, LwM2mClient client) { if (TransportProtos.ResponseStatus.SUCCESS.equals(response.getResponseStatus())) { UUID otaPackageId = new UUID(response.getOtaPackageIdMSB(), response.getOtaPackageIdLSB()); LwM2MFirmwareUpdateStrategy strategy; if (info.getDeliveryMethod() == null || info.getDeliveryMethod() == FirmwareDeliveryMethod.BOTH.code) { strategy = info.getStrategy(); } else { strategy = info.getDeliveryMethod() == FirmwareDeliveryMethod.PULL.code ? LwM2MFirmwareUpdateStrategy.OBJ_5_TEMP_URL : LwM2MFirmwareUpdateStrategy.OBJ_5_BINARY; } switch (strategy) { case OBJ_5_BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(FW_PACKAGE_5_ID, client.getRegistration()), otaPackageId); break; case OBJ_19_BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(FW_PACKAGE_19_ID, client.getRegistration()), otaPackageId); break; case OBJ_5_TEMP_URL: startUpdateUsingUrl(client, FW_URL_ID, info.getBaseUrl() + "/" + FIRMWARE_UPDATE_COAP_RESOURCE + "/" + otaPackageId.toString()); break; default: sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Unsupported strategy: " + strategy.name()); } } else { sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Failed to fetch OTA package: " + response.getResponseStatus()); } } private void doUpdateSoftwareUsingBinary(TransportProtos.GetOtaPackageResponseMsg response, LwM2MClientSwOtaInfo info, LwM2mClient client) { if (TransportProtos.ResponseStatus.SUCCESS.equals(response.getResponseStatus())) { UUID otaPackageId = new UUID(response.getOtaPackageIdMSB(), response.getOtaPackageIdLSB()); LwM2MSoftwareUpdateStrategy strategy = info.getStrategy(); switch (strategy) { case BINARY: startUpdateUsingBinary(client, convertObjectIdToVersionedId(SW_PACKAGE_ID, client.getRegistration()), otaPackageId); break; case TEMP_URL: startUpdateUsingUrl(client, SW_PACKAGE_URI_ID, info.getBaseUrl() + "/" + FIRMWARE_UPDATE_COAP_RESOURCE + "/" + otaPackageId.toString()); break; default: sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Unsupported strategy: " + strategy.name()); } } else { sendStateUpdateToTelemetry(client, info, OtaPackageUpdateStatus.FAILED, "Failed to fetch OTA package: " + response.getResponseStatus()); } } private void startUpdateUsingBinary(LwM2mClient client, String versionedId, UUID otaPackageId) { byte[] firmwareChunk = otaPackageDataCache.get(otaPackageId.toString(), 0, 0); TbLwM2MWriteReplaceRequest writeRequest = TbLwM2MWriteReplaceRequest.builder().versionedId(versionedId) .value(firmwareChunk).contentFormat(ContentFormat.OPAQUE) .timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendWriteReplaceRequest(client, writeRequest, new TbLwM2MWriteResponseCallback(uplinkHandler, logService, client, versionedId)); } private TransportProtos.GetOtaPackageRequestMsg createOtaPackageRequestMsg(TransportProtos.SessionInfoProto sessionInfo, String nameFwSW) { return TransportProtos.GetOtaPackageRequestMsg.newBuilder() .setDeviceIdMSB(sessionInfo.getDeviceIdMSB()) .setDeviceIdLSB(sessionInfo.getDeviceIdLSB()) .setTenantIdMSB(sessionInfo.getTenantIdMSB()) .setTenantIdLSB(sessionInfo.getTenantIdLSB()) .setType(nameFwSW) .build(); } private void executeFwUpdate(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(FW_EXECUTE_ID).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, FW_EXECUTE_ID)); } private void executeSwInstall(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(SW_INSTALL_ID).timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, SW_INSTALL_ID)); } private void executeSwUninstallForUpdate(LwM2mClient client) { TbLwM2MExecuteRequest request = TbLwM2MExecuteRequest.builder().versionedId(SW_UN_INSTALL_ID).params("1").timeout(clientContext.getRequestTimeout(client)).build(); downlinkHandler.sendExecuteRequest(client, request, new TbLwM2MExecuteCallback(logService, client, SW_INSTALL_ID)); } private Optional<String> getAttributeValue(List<TransportProtos.TsKvProto> attrs, String keyName) { for (TransportProtos.TsKvProto attr : attrs) { if (keyName.equals(attr.getKv().getKey())) { if (attr.getKv().getType().equals(TransportProtos.KeyValueType.STRING_V)) { return Optional.of(attr.getKv().getStringV()); } else { return Optional.empty(); } } } return Optional.empty(); } private LwM2MClientFwOtaInfo getOrInitFwInfo(LwM2mClient client) { return this.fwStates.computeIfAbsent(client.getEndpoint(), endpoint -> { LwM2MClientFwOtaInfo info = otaInfoStore.getFw(endpoint); if (info == null) { var profile = clientContext.getProfile(client.getProfileId()); info = new LwM2MClientFwOtaInfo(endpoint, profile.getClientLwM2mSettings().getFwUpdateResource(), LwM2MFirmwareUpdateStrategy.fromStrategyFwByCode(profile.getClientLwM2mSettings().getFwUpdateStrategy())); update(info); } return info; }); } private LwM2MClientSwOtaInfo getOrInitSwInfo(LwM2mClient client) { return this.swStates.computeIfAbsent(client.getEndpoint(), endpoint -> { LwM2MClientSwOtaInfo info = otaInfoStore.getSw(endpoint); if (info == null) { var profile = clientContext.getProfile(client.getProfileId()); info = new LwM2MClientSwOtaInfo(endpoint, profile.getClientLwM2mSettings().getSwUpdateResource(), LwM2MSoftwareUpdateStrategy.fromStrategySwByCode(profile.getClientLwM2mSettings().getSwUpdateStrategy())); update(info); } return info; }); } private void update(LwM2MClientFwOtaInfo info) { otaInfoStore.putFw(info); } private void update(LwM2MClientSwOtaInfo info) { otaInfoStore.putSw(info); } private void sendStateUpdateToTelemetry(LwM2mClient client, LwM2MClientOtaInfo<?, ?, ?> fwInfo, OtaPackageUpdateStatus status, String log) { List<TransportProtos.KeyValueProto> result = new ArrayList<>(); TransportProtos.KeyValueProto.Builder kvProto = TransportProtos.KeyValueProto.newBuilder().setKey(getAttributeKey(fwInfo.getType(), STATE)); kvProto.setType(TransportProtos.KeyValueType.STRING_V).setStringV(status.name()); result.add(kvProto.build()); kvProto = TransportProtos.KeyValueProto.newBuilder().setKey(LOG_LWM2M_TELEMETRY); kvProto.setType(TransportProtos.KeyValueType.STRING_V).setStringV(log); result.add(kvProto.build()); helper.sendParametersOnThingsboardTelemetry(result, client.getSession()); } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(FirmwareUpdateResult fwUpdateResult) { switch (fwUpdateResult) { case INITIAL: return Optional.empty(); case UPDATE_SUCCESSFULLY: return Optional.of(UPDATED); case NOT_ENOUGH: case OUT_OFF_MEMORY: case CONNECTION_LOST: case INTEGRITY_CHECK_FAILURE: case UNSUPPORTED_TYPE: case INVALID_URI: case UPDATE_FAILED: case UNSUPPORTED_PROTOCOL: return Optional.of(FAILED); default: throw new CodecException("Invalid value stateFw %s for FirmwareUpdateStatus.", fwUpdateResult.name()); } } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(FirmwareUpdateState firmwareUpdateState) { switch (firmwareUpdateState) { case IDLE: return Optional.empty(); case DOWNLOADING: return Optional.of(DOWNLOADING); case DOWNLOADED: return Optional.of(DOWNLOADED); case UPDATING: return Optional.of(UPDATING); default: throw new CodecException("Invalid value stateFw %d for FirmwareUpdateStatus.", firmwareUpdateState); } } private static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(SoftwareUpdateState swUpdateState) { switch (swUpdateState) { case INITIAL: return Optional.empty(); case DOWNLOAD_STARTED: return Optional.of(DOWNLOADING); case DOWNLOADED: return Optional.of(DOWNLOADING); case DELIVERED: return Optional.of(DOWNLOADED); case INSTALLED: return Optional.empty(); default: throw new CodecException("Invalid value stateSw %d for SoftwareUpdateState.", swUpdateState); } } /** * FirmwareUpdateStatus { * DOWNLOADING, DOWNLOADED, VERIFIED, UPDATING, UPDATED, FAILED */ public static Optional<OtaPackageUpdateStatus> toOtaPackageUpdateStatus(SoftwareUpdateResult softwareUpdateResult) { switch (softwareUpdateResult) { case INITIAL: return Optional.empty(); case DOWNLOADING: return Optional.of(DOWNLOADING); case SUCCESSFULLY_INSTALLED: return Optional.of(UPDATED); case SUCCESSFULLY_DOWNLOADED_VERIFIED: return Optional.of(VERIFIED); case NOT_ENOUGH_STORAGE: case OUT_OFF_MEMORY: case CONNECTION_LOST: case PACKAGE_CHECK_FAILURE: case UNSUPPORTED_PACKAGE_TYPE: case INVALID_URI: case UPDATE_ERROR: case INSTALL_FAILURE: case UN_INSTALL_FAILURE: return Optional.of(FAILED); default: throw new CodecException("Invalid value stateFw %s for FirmwareUpdateStatus.", softwareUpdateResult.name()); } } }
Correct initialization order.
common/transport/lwm2m/src/main/java/org/thingsboard/server/transport/lwm2m/server/ota/DefaultLwM2MOtaUpdateService.java
Correct initialization order.
Java
bsd-3-clause
93db3f9a327477c2d6ad9919f141f54ec2731de1
0
CBIIT/caaers,NCIP/caaers,NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.web.ae; import java.util.Map; import gov.nih.nci.cabig.caaers.domain.LocalResearchStaff; import gov.nih.nci.cabig.caaers.domain.ResearchStaff; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.userdetails.User; import org.springframework.validation.BindException; import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDao; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.service.ReportSubmittability; import gov.nih.nci.cabig.caaers.tools.configuration.Configuration; import gov.nih.nci.cabig.caaers.domain.Fixtures; import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.repository.CSMUserRepository; import gov.nih.nci.cabig.caaers.domain.repository.ReportValidationService; import gov.nih.nci.cabig.caaers.validation.ValidationErrors; import gov.nih.nci.cabig.caaers.web.WebTestCase; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; /** * This class tests - ReviewAeReportController.java * @author Sameer Sawant */ public class ReviewAeReportControllerTest extends WebTestCase{ protected ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao; protected ReportDao reportDao; protected StudyParticipantAssignmentDao assignmentDao; protected Configuration configuration; BindException errors; protected ReviewAeReportController controller; protected ReviewAeReportCommand command; protected EvaluationService evaluationService; protected ReportValidationService reportValidationService; protected CSMUserRepository csmUserRepository; protected void setUp() throws Exception { super.setUp(); expeditedAdverseEventReportDao = registerDaoMockFor(ExpeditedAdverseEventReportDao.class); assignmentDao = registerDaoMockFor(StudyParticipantAssignmentDao.class); configuration = registerMockFor(Configuration.class); evaluationService = registerMockFor(EvaluationService.class); reportValidationService = registerMockFor(ReportValidationService.class); reportDao = registerDaoMockFor(ReportDao.class); command = new ReviewAeReportCommand(expeditedAdverseEventReportDao, reportDao); errors = new BindException(command,"command"); csmUserRepository = registerMockFor(CSMUserRepository.class); controller = new ReviewAeReportController(); controller.setExpeditedAdverseEventReportDao(expeditedAdverseEventReportDao); controller.setAssignmentDao(assignmentDao); controller.setConfiguration(configuration); controller.setEvaluationService(evaluationService); controller.setReportValidationService(reportValidationService); controller.setCsmUserRepository(csmUserRepository); } public void testFormBackingObject() throws Exception{ request.setParameter("aeReport", "1"); request.setParameter("report", "1"); ExpeditedAdverseEventReport report = new ExpeditedAdverseEventReport(); report.setId(1); expect(expeditedAdverseEventReportDao.getById(1)).andReturn(report); expect(configuration.get(Configuration.ENABLE_WORKFLOW)).andReturn(true); replayMocks(); command = (ReviewAeReportCommand) controller.formBackingObject(request); verifyMocks(); } public void testReferenceData() throws Exception{ ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport(); Report report = Fixtures.createReport("test report"); SecurityContext context = registerMockFor(SecurityContext.class); Authentication auth = registerMockFor(Authentication.class); User user = registerMockFor(User.class); session.setAttribute(ReviewAeReportController.class + ".FORM.command",command); session.setAttribute("ACEGI_SECURITY_CONTEXT",context); aeReport.addReport(report); report.setId(1); command.setAeReport(aeReport); command.setReportId(1); ValidationErrors vErrors = new ValidationErrors(); expect(evaluationService.validateReportingBusinessRules(isA(ExpeditedAdverseEventReport.class), isA(ExpeditedReportSection.class))).andReturn(vErrors).anyTimes(); expect(reportValidationService.isSubmittable(report)).andReturn(new ReportSubmittability()); expect(context.getAuthentication()).andReturn(auth); expect(auth.getPrincipal()).andReturn(user); expect(user.getUsername()).andReturn("SYSTEM_ADMIN"); expect(csmUserRepository.getUserByName("SYSTEM_ADMIN")).andReturn(new LocalResearchStaff()); replayMocks(); Map<String, Object> refdata = controller.referenceData(request, command, errors); verifyMocks(); assertFalse("isUserSAECoordinator flag set incorrectly", (Boolean)refdata.get("isUserSAECoordinato")); assertContainsKey("Report messages is expected in jsp, but not set in the reference data", refdata, "reportMessages"); } }
caAERS/software/web/src/test/java/gov/nih/nci/cabig/caaers/web/ae/ReviewAeReportControllerTest.java
package gov.nih.nci.cabig.caaers.web.ae; import java.util.Map; import org.acegisecurity.Authentication; import org.acegisecurity.context.SecurityContext; import org.acegisecurity.userdetails.User; import org.springframework.validation.BindException; import gov.nih.nci.cabig.caaers.dao.ExpeditedAdverseEventReportDao; import gov.nih.nci.cabig.caaers.dao.StudyParticipantAssignmentDao; import gov.nih.nci.cabig.caaers.dao.report.ReportDao; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.service.EvaluationService; import gov.nih.nci.cabig.caaers.service.ReportSubmittability; import gov.nih.nci.cabig.caaers.tools.configuration.Configuration; import gov.nih.nci.cabig.caaers.domain.Fixtures; import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.domain.repository.CSMUserRepository; import gov.nih.nci.cabig.caaers.domain.repository.ReportValidationService; import gov.nih.nci.cabig.caaers.validation.ValidationErrors; import gov.nih.nci.cabig.caaers.web.WebTestCase; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.isA; /** * This class tests - ReviewAeReportController.java * @author Sameer Sawant */ public class ReviewAeReportControllerTest extends WebTestCase{ protected ExpeditedAdverseEventReportDao expeditedAdverseEventReportDao; protected ReportDao reportDao; protected StudyParticipantAssignmentDao assignmentDao; protected Configuration configuration; BindException errors; protected ReviewAeReportController controller; protected ReviewAeReportCommand command; protected EvaluationService evaluationService; protected ReportValidationService reportValidationService; protected CSMUserRepository csmUserRepository; protected void setUp() throws Exception { super.setUp(); expeditedAdverseEventReportDao = registerDaoMockFor(ExpeditedAdverseEventReportDao.class); assignmentDao = registerDaoMockFor(StudyParticipantAssignmentDao.class); configuration = registerMockFor(Configuration.class); evaluationService = registerMockFor(EvaluationService.class); reportValidationService = registerMockFor(ReportValidationService.class); reportDao = registerDaoMockFor(ReportDao.class); command = new ReviewAeReportCommand(expeditedAdverseEventReportDao, reportDao); errors = new BindException(command,"command"); csmUserRepository = registerMockFor(CSMUserRepository.class); controller = new ReviewAeReportController(); controller.setExpeditedAdverseEventReportDao(expeditedAdverseEventReportDao); controller.setAssignmentDao(assignmentDao); controller.setConfiguration(configuration); controller.setEvaluationService(evaluationService); controller.setReportValidationService(reportValidationService); controller.setCsmUserRepository(csmUserRepository); } public void testFormBackingObject() throws Exception{ request.setParameter("aeReport", "1"); request.setParameter("report", "1"); ExpeditedAdverseEventReport report = new ExpeditedAdverseEventReport(); report.setId(1); expect(expeditedAdverseEventReportDao.getById(1)).andReturn(report); expect(configuration.get(Configuration.ENABLE_WORKFLOW)).andReturn(true); replayMocks(); command = (ReviewAeReportCommand) controller.formBackingObject(request); verifyMocks(); } public void testReferenceData() throws Exception{ ExpeditedAdverseEventReport aeReport = Fixtures.createSavableExpeditedReport(); Report report = Fixtures.createReport("test report"); SecurityContext context = registerMockFor(SecurityContext.class); Authentication auth = registerMockFor(Authentication.class); User user = registerMockFor(User.class); session.setAttribute(ReviewAeReportController.class + ".FORM.command",command); session.setAttribute("ACEGI_SECURITY_CONTEXT",context); aeReport.addReport(report); report.setId(1); command.setAeReport(aeReport); command.setReportId(1); ValidationErrors vErrors = new ValidationErrors(); expect(evaluationService.validateReportingBusinessRules(isA(ExpeditedAdverseEventReport.class), isA(ExpeditedReportSection.class))).andReturn(vErrors).anyTimes(); expect(reportValidationService.isSubmittable(report)).andReturn(new ReportSubmittability()); expect(context.getAuthentication()).andReturn(auth); expect(auth.getPrincipal()).andReturn(user); expect(user.getUsername()).andReturn("SYSTEM_ADMIN"); replayMocks(); Map<String, Object> refdata = controller.referenceData(request, command, errors); verifyMocks(); assertFalse("isUserSAECoordinator flag set incorrectly", (Boolean)refdata.get("isUserSAECoordinato")); assertContainsKey("Report messages is expected in jsp, but not set in the reference data", refdata, "reportMessages"); } }
CAAERS-4164 - Fix CI build failures SVN-Revision: 14108
caAERS/software/web/src/test/java/gov/nih/nci/cabig/caaers/web/ae/ReviewAeReportControllerTest.java
CAAERS-4164 - Fix CI build failures
Java
bsd-3-clause
a506ac89bbe539fbc62376ab16a388d06d9b956a
0
NCIP/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers
package gov.nih.nci.cabig.caaers.dao; import static gov.nih.nci.cabig.caaers.CaaersUseCase.MAPPING_VOCAB; import gov.nih.nci.cabig.caaers.CaaersUseCases; import gov.nih.nci.cabig.caaers.DaoTestCase; import gov.nih.nci.cabig.caaers.domain.CtcGrade; import gov.nih.nci.cabig.caaers.domain.CtcTerm; import gov.nih.nci.cabig.caaers.domain.Grade; import org.dbunit.operation.DatabaseOperation; import java.util.List; /** * @author Rhett Sutphin */ @CaaersUseCases( { MAPPING_VOCAB }) public class CtcTermDaoTest extends DaoTestCase<CtcTermDao> { public void testGetById() throws Exception { CtcTerm loaded = getDao().getById(3001); assertNotNull(loaded); assertEquals("Wrong category", 301, (int) loaded.getCategory().getId()); assertEquals("Wrong CTC version", 3, (int) loaded.getCategory().getCtc().getId()); assertTrue("Other is required", loaded.isOtherRequired()); } public void testGetBySubnameMatchesTermSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "dry" }, 2, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 2002, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesCtepTermSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "thermal" }, 2, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 2001, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesSelectSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "chemorad" }, 3, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 3004, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesFiltersByCategory() throws Exception { List<CtcTerm> unfilteredMatches = getDao().getBySubname(new String[] { "skin" }, 3, null); assertEquals("Test setup invalid: wrong number of matches w/o category filter", 2, unfilteredMatches.size()); List<CtcTerm> matches = getDao().getBySubname(new String[] { "skin" }, 3, 302); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 3010, (int) matches.get(0).getId()); } public void testGetContextualGrades() throws Exception { CtcTerm term = getDao().getById(3010); assertEquals("Wrong number of contextual grades", 2, term.getContextualGrades().size()); assertEquals("Wrong 0th grade", 30103, (int) term.getContextualGrades().get(0).getId()); CtcGrade actual = term.getContextualGrades().get(1); assertEquals("Wrong 1st grade", 30104, (int) actual.getId()); assertEquals("Wrong grade", Grade.LIFE_THREATENING, actual.getGrade()); assertEquals("Wrong text", "On fire", actual.getText()); } public void testGetCtcTerm(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" }); assertNotNull(ctcTerm); } public void testGetCtcTerm_1a(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "1a_Rash: dermatitis associated with radiation" }); assertNull(ctcTerm); } public void testGetAll(){ List<CtcTerm> ctcTerms = getDao().getAll(); assertNotNull(ctcTerms); assertTrue(ctcTerms.size() > 0); } public void testGetByCtepCodeandVersion() throws Exception { List<CtcTerm> ctcTerms = getDao().getByCtepCodeandVersion("10016241",3); assertEquals(1, ctcTerms.size()); assertEquals("Atrophy, subcutaneous fat", ctcTerms.get(0).getTerm()); } public void testGetCtcTerm_1(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },null,null); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_2(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },new Integer(3),null); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_3(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },new Integer(3),new Integer(301)); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_4() { CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "1_Rash: dermatitis associated with radiation" },new Integer(3),new Integer(301)); assertNull(ctcTerm); } /* * Get the list of Ctc Term providing term name, category name and ctcae version * */ public void testGetCtcTermByNameCategoryCtcVersion() { List<CtcTerm> terms = getDao().getCtcTerm("DERMATOLOGY/SKIN", 2, "Burn"); assertEquals(1, terms.size()); assertEquals("Burn", terms.get(0).getTerm()); assertEquals("DERMATOLOGY/SKIN", terms.get(0).getCategory().getName()); assertEquals(2, terms.get(0).getCategory().getCtc().getId().intValue()); } @Override protected DatabaseOperation getTearDownOperation() throws Exception { return DatabaseOperation.REFRESH; } }
caAERS/software/core/src/test/java/gov/nih/nci/cabig/caaers/dao/CtcTermDaoTest.java
package gov.nih.nci.cabig.caaers.dao; import static gov.nih.nci.cabig.caaers.CaaersUseCase.MAPPING_VOCAB; import gov.nih.nci.cabig.caaers.CaaersUseCases; import gov.nih.nci.cabig.caaers.DaoTestCase; import gov.nih.nci.cabig.caaers.domain.CtcGrade; import gov.nih.nci.cabig.caaers.domain.CtcTerm; import gov.nih.nci.cabig.caaers.domain.Grade; import java.util.List; /** * @author Rhett Sutphin */ @CaaersUseCases( { MAPPING_VOCAB }) public class CtcTermDaoTest extends DaoTestCase<CtcTermDao> { public void testGetById() throws Exception { CtcTerm loaded = getDao().getById(3001); assertNotNull(loaded); assertEquals("Wrong category", 301, (int) loaded.getCategory().getId()); assertEquals("Wrong CTC version", 3, (int) loaded.getCategory().getCtc().getId()); assertTrue("Other is required", loaded.isOtherRequired()); } public void testGetBySubnameMatchesTermSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "dry" }, 2, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 2002, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesCtepTermSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "thermal" }, 2, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 2001, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesSelectSubstring() throws Exception { List<CtcTerm> matches = getDao().getBySubname(new String[] { "chemorad" }, 3, null); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 3004, (int) matches.get(0).getId()); } public void testGetBySubnameMatchesFiltersByCategory() throws Exception { List<CtcTerm> unfilteredMatches = getDao().getBySubname(new String[] { "skin" }, 3, null); assertEquals("Test setup invalid: wrong number of matches w/o category filter", 2, unfilteredMatches.size()); List<CtcTerm> matches = getDao().getBySubname(new String[] { "skin" }, 3, 302); assertEquals("Wrong number of matches", 1, matches.size()); assertEquals("Wrong match", 3010, (int) matches.get(0).getId()); } public void testGetContextualGrades() throws Exception { CtcTerm term = getDao().getById(3010); assertEquals("Wrong number of contextual grades", 2, term.getContextualGrades().size()); assertEquals("Wrong 0th grade", 30103, (int) term.getContextualGrades().get(0).getId()); CtcGrade actual = term.getContextualGrades().get(1); assertEquals("Wrong 1st grade", 30104, (int) actual.getId()); assertEquals("Wrong grade", Grade.LIFE_THREATENING, actual.getGrade()); assertEquals("Wrong text", "On fire", actual.getText()); } public void testGetCtcTerm(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" }); assertNotNull(ctcTerm); } public void testGetCtcTerm_1a(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "1a_Rash: dermatitis associated with radiation" }); assertNull(ctcTerm); } public void testGetAll(){ List<CtcTerm> ctcTerms = getDao().getAll(); assertNotNull(ctcTerms); assertTrue(ctcTerms.size() > 0); } public void testGetByCtepCodeandVersion() throws Exception { List<CtcTerm> ctcTerms = getDao().getByCtepCodeandVersion("10016241",3); assertEquals(1, ctcTerms.size()); assertEquals("Atrophy, subcutaneous fat", ctcTerms.get(0).getTerm()); } public void testGetCtcTerm_1(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },null,null); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_2(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },new Integer(3),null); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_3(){ CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "Rash: dermatitis associated with radiation" },new Integer(3),new Integer(301)); assertNotNull(ctcTerm); assertEquals("Rash: dermatitis associated with radiation", ctcTerm.getTerm()); } public void testGetCtcTerm_4() { CtcTerm ctcTerm = getDao().getCtcTerm(new String[] { "1_Rash: dermatitis associated with radiation" },new Integer(3),new Integer(301)); assertNull(ctcTerm); } /* * Get the list of Ctc Term providing term name, category name and ctcae version * */ public void testGetCtcTermByNameCategoryCtcVersion() { List<CtcTerm> terms = getDao().getCtcTerm("DERMATOLOGY/SKIN", 2, "Burn"); assertEquals(1, terms.size()); assertEquals("Burn", terms.get(0).getTerm()); assertEquals("DERMATOLOGY/SKIN", terms.get(0).getCategory().getName()); assertEquals(2, terms.get(0).getCategory().getCtc().getId().intValue()); } }
SVN-Revision: 14912
caAERS/software/core/src/test/java/gov/nih/nci/cabig/caaers/dao/CtcTermDaoTest.java
Java
bsd-3-clause
d41e09f522b5426d92eafc3f1ec168cdde39963d
0
wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy,wdv4758h/ZipPy
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.common.cfg; import java.util.*; public interface AbstractControlFlowGraph<T extends AbstractBlock<T>> { static final int BLOCK_ID_INITIAL = -1; static final int BLOCK_ID_VISITED = -2; /** * Returns the list blocks contained in this control flow graph. * * It is {@linkplain CFGVerifier guaranteed} that the blocks are numbered according to a reverse * post order traversal of the control flow graph. * * @see CFGVerifier */ List<T> getBlocks(); Collection<Loop<T>> getLoops(); T getStartBlock(); /** * Calculates the common dominator of two blocks. * * Note that this algorithm makes use of special properties regarding the numbering of blocks. * * @see #getBlocks() * @see CFGVerifier */ public static AbstractBlock<?> commonDominator(AbstractBlock<?> a, AbstractBlock<?> b) { if (a == null) { return b; } if (b == null) { return a; } AbstractBlock<?> iterA = a; AbstractBlock<?> iterB = b; while (iterA != iterB) { if (iterA.getId() > iterB.getId()) { iterA = iterA.getDominator(); } else { assert iterB.getId() > iterA.getId(); iterB = iterB.getDominator(); } } return iterA; } /** * @see AbstractControlFlowGraph#commonDominator(AbstractBlock, AbstractBlock) */ @SuppressWarnings("unchecked") public static <T extends AbstractBlock<T>> T commonDominatorTyped(T a, T b) { return (T) commonDominator(a, b); } }
graal/com.oracle.graal.compiler.common/src/com/oracle/graal/compiler/common/cfg/AbstractControlFlowGraph.java
/* * Copyright (c) 2014, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.compiler.common.cfg; import java.util.*; public interface AbstractControlFlowGraph<T extends AbstractBlock<T>> { static final int BLOCK_ID_INITIAL = -1; static final int BLOCK_ID_VISITED = -2; List<T> getBlocks(); Collection<Loop<T>> getLoops(); T getStartBlock(); public static AbstractBlock<?> commonDominator(AbstractBlock<?> a, AbstractBlock<?> b) { if (a == null) { return b; } if (b == null) { return a; } AbstractBlock<?> iterA = a; AbstractBlock<?> iterB = b; while (iterA != iterB) { if (iterA.getId() > iterB.getId()) { iterA = iterA.getDominator(); } else { assert iterB.getId() > iterA.getId(); iterB = iterB.getDominator(); } } return iterA; } @SuppressWarnings("unchecked") public static <T extends AbstractBlock<T>> T commonDominatorTyped(T a, T b) { return (T) commonDominator(a, b); } }
Document invariants of AbstractControlFlowGraph.getBlocks().
graal/com.oracle.graal.compiler.common/src/com/oracle/graal/compiler/common/cfg/AbstractControlFlowGraph.java
Document invariants of AbstractControlFlowGraph.getBlocks().
Java
mit
046aa406e1d97a21a08e7c7b61e7c1971fa2d351
0
aifa-gov-it/invoices-processor,aifa-gov-it/invoices-processor
package it.gov.aifa.invoice_processor.entity.movement; import java.time.LocalDate; import java.time.LocalDateTime; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Transient; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.reflect.FieldUtils; import org.hibernate.validator.constraints.NotBlank; import org.springframework.validation.annotation.Validated; @Access(AccessType.FIELD) @Entity @Validated public class Movement { private String accountHolderCode; private String accountHolderTypeCode; @NotBlank private String aic; @NotBlank private String customerCode; @NotBlank private String customerTypeCode; @NotBlank private String documentNumber; @NotBlank private String documentTypeCode; private LocalDate expirationDate; // This field is mapped via it's property private String id; private LocalDateTime importDate = LocalDateTime.now(); private String lot; @NotBlank private String movementCode; private Double quantity; @Transient private String rawExpirationDate; @NotBlank private String recipientCode; @NotBlank private String recipientTypeCode; @NotBlank private String senderCode; @NotBlank private String senderTypeCode; @Transient private String transmissionDate; @NotNull private LocalDateTime transmissionDateTime; @Transient private String transmissionTime; private Double value; @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Movement) == false) { return false; } Movement rhs = ((Movement) other); return new EqualsBuilder() .append(accountHolderCode, rhs.accountHolderCode) .append(accountHolderTypeCode, rhs.accountHolderTypeCode) .append(aic, rhs.aic) .append(customerCode, rhs.customerCode) .append(customerTypeCode, rhs.customerTypeCode) .append(documentNumber, rhs.documentNumber) .append(documentTypeCode, rhs.documentTypeCode) .append(expirationDate, rhs.expirationDate) .append(id, rhs.id) .append(importDate, rhs.importDate) .append(lot, rhs.lot) .append(movementCode, rhs.movementCode) .append(quantity, rhs.quantity) .append(recipientCode, rhs.recipientCode) .append(recipientTypeCode, rhs.recipientTypeCode) .append(senderCode, rhs.senderCode) .append(senderTypeCode, rhs.senderTypeCode) .append(transmissionDateTime, rhs.transmissionDateTime) .append(value, rhs.value) .isEquals(); } public String getAccountHolderCode() { return accountHolderCode; } public String getAccountHolderTypeCode() { return accountHolderTypeCode; } public String getAic() { return aic; } public String getCustomerCode() { return customerCode; } public String getCustomerTypeCode() { return customerTypeCode; } public String getDocumentNumber() { return documentNumber; } public String getDocumentTypeCode() { return documentTypeCode; } public LocalDate getExpirationDate() { return expirationDate; } @Access(AccessType.PROPERTY) @Id @NotBlank public String getId() { if(StringUtils.isBlank(id)) { StringBuilder builder = new StringBuilder(); FieldUtils.getAllFieldsList(this.getClass()).stream() .forEach(f -> { try { Object value = FieldUtils.readField(f, this, true); if(value != null) builder.append(value.toString()); } catch (IllegalAccessException e) { // Let's reuse the StringBuilder builder.setLength(0); builder.append("Cannot build id for "); builder.append(this.toString()); throw new RuntimeException(builder.toString(), e); } }); id = builder.toString(); } return id; } public LocalDateTime getImportDate() { return importDate; } public String getLot() { return lot; } public String getMovementCode() { return movementCode; } public double getQuantity() { return quantity; } public String getRawExpirationDate() { return rawExpirationDate; } public String getRecipientCode() { return recipientCode; } public String getRecipientTypeCode() { return recipientTypeCode; } public String getSenderCode() { return senderCode; } public String getSenderTypeCode() { return senderTypeCode; } public String getTransmissionDate() { return transmissionDate; } public LocalDateTime getTransmissionDateTime() { return transmissionDateTime; } public String getTransmissionTime() { return transmissionTime; } public Double getValue() { return value; } @Override public int hashCode() { return new HashCodeBuilder() .append(accountHolderCode) .append(accountHolderTypeCode) .append(aic) .append(customerCode) .append(customerTypeCode) .append(documentNumber) .append(documentTypeCode) .append(expirationDate) .append(id) .append(importDate) .append(lot) .append(movementCode) .append(quantity) .append(recipientCode) .append(recipientTypeCode) .append(senderCode) .append(senderTypeCode) .append(transmissionDateTime) .append(value) .toHashCode(); } public void setAccountHolderCode(String accountHolderCode) { this.accountHolderCode = accountHolderCode; } public void setAccountHolderTypeCode(String accountHolderTypeCode) { this.accountHolderTypeCode = accountHolderTypeCode; } public void setAic(String aic) { this.aic = aic; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public void setCustomerTypeCode(String customerTypeCode) { this.customerTypeCode = customerTypeCode; } public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } public void setDocumentTypeCode(String documentTypeCode) { this.documentTypeCode = documentTypeCode; } public void setExpirationDate(LocalDate expirationDate) { this.expirationDate = expirationDate; } public void setId(String id) { this.id = id; } public void setImportDate(LocalDateTime importDate) { this.importDate = importDate; } public void setLot(String lot) { this.lot = lot; } public void setMovementCode(String movementCode) { this.movementCode = movementCode; } public void setQuantity(double quantity) { this.quantity = quantity; } public void setRawExpirationDate(String rawExpirationDate) { this.rawExpirationDate = rawExpirationDate; } public void setRecipientCode(String recipientCode) { this.recipientCode = recipientCode; } public void setRecipientTypeCode(String recipientTypeCode) { this.recipientTypeCode = recipientTypeCode; } public void setSenderCode(String senderCode) { this.senderCode = senderCode; } public void setSenderTypeCode(String senderTypeCode) { this.senderTypeCode = senderTypeCode; } public void setTransmissionDate(String transmissionDate) { this.transmissionDate = transmissionDate; } public void setTransmissionDateTime(LocalDateTime transmissionDateTime) { this.transmissionDateTime = transmissionDateTime; } public void setTransmissionTime(String transmissionTime) { this.transmissionTime = transmissionTime; } public void setValue(Double value) { this.value = value; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
json-invoice-processor/src/main/java/it/gov/aifa/invoice_processor/entity/movement/Movement.java
package it.gov.aifa.invoice_processor.entity.movement; import java.time.LocalDate; import java.time.LocalDateTime; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Transient; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotNull; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.reflect.FieldUtils; import org.hibernate.validator.constraints.NotBlank; import org.springframework.validation.annotation.Validated; @Access(AccessType.FIELD) @Entity @Validated public class Movement { private String accountHolderCode; private String accountHolderTypeCode; @NotBlank private String aic; @NotBlank private String customerCode; @NotBlank private String customerTypeCode; @NotBlank private String documentNumber; @NotBlank private String documentTypeCode; private LocalDate expirationDate; // This field is mapped via it's property private String id; private LocalDateTime importDate = LocalDateTime.now(); private String lot; @NotBlank private String movementCode; @DecimalMin(inclusive = false, value = "0") private double quantity; @Transient private String rawExpirationDate; @NotBlank private String recipientCode; @NotBlank private String recipientTypeCode; @NotBlank private String senderCode; @NotBlank private String senderTypeCode; @Transient private String transmissionDate; @NotNull private LocalDateTime transmissionDateTime; @Transient private String transmissionTime; private Double value; @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Movement) == false) { return false; } Movement rhs = ((Movement) other); return new EqualsBuilder() .append(accountHolderCode, rhs.accountHolderCode) .append(accountHolderTypeCode, rhs.accountHolderTypeCode) .append(aic, rhs.aic) .append(customerCode, rhs.customerCode) .append(customerTypeCode, rhs.customerTypeCode) .append(documentNumber, rhs.documentNumber) .append(documentTypeCode, rhs.documentTypeCode) .append(expirationDate, rhs.expirationDate) .append(id, rhs.id) .append(importDate, rhs.importDate) .append(lot, rhs.lot) .append(movementCode, rhs.movementCode) .append(quantity, rhs.quantity) .append(recipientCode, rhs.recipientCode) .append(recipientTypeCode, rhs.recipientTypeCode) .append(senderCode, rhs.senderCode) .append(senderTypeCode, rhs.senderTypeCode) .append(transmissionDateTime, rhs.transmissionDateTime) .append(value, rhs.value) .isEquals(); } public String getAccountHolderCode() { return accountHolderCode; } public String getAccountHolderTypeCode() { return accountHolderTypeCode; } public String getAic() { return aic; } public String getCustomerCode() { return customerCode; } public String getCustomerTypeCode() { return customerTypeCode; } public String getDocumentNumber() { return documentNumber; } public String getDocumentTypeCode() { return documentTypeCode; } public LocalDate getExpirationDate() { return expirationDate; } @Access(AccessType.PROPERTY) @Id @NotBlank public String getId() { if(StringUtils.isBlank(id)) { StringBuilder builder = new StringBuilder(); FieldUtils.getAllFieldsList(this.getClass()).stream() .forEach(f -> { try { Object value = FieldUtils.readField(f, this, true); if(value != null) builder.append(value.toString()); } catch (IllegalAccessException e) { // Let's reuse the StringBuilder builder.setLength(0); builder.append("Cannot build id for "); builder.append(this.toString()); throw new RuntimeException(builder.toString(), e); } }); id = builder.toString(); } return id; } public LocalDateTime getImportDate() { return importDate; } public String getLot() { return lot; } public String getMovementCode() { return movementCode; } public double getQuantity() { return quantity; } public String getRawExpirationDate() { return rawExpirationDate; } public String getRecipientCode() { return recipientCode; } public String getRecipientTypeCode() { return recipientTypeCode; } public String getSenderCode() { return senderCode; } public String getSenderTypeCode() { return senderTypeCode; } public String getTransmissionDate() { return transmissionDate; } public LocalDateTime getTransmissionDateTime() { return transmissionDateTime; } public String getTransmissionTime() { return transmissionTime; } public Double getValue() { return value; } @Override public int hashCode() { return new HashCodeBuilder() .append(accountHolderCode) .append(accountHolderTypeCode) .append(aic) .append(customerCode) .append(customerTypeCode) .append(documentNumber) .append(documentTypeCode) .append(expirationDate) .append(id) .append(importDate) .append(lot) .append(movementCode) .append(quantity) .append(recipientCode) .append(recipientTypeCode) .append(senderCode) .append(senderTypeCode) .append(transmissionDateTime) .append(value) .toHashCode(); } public void setAccountHolderCode(String accountHolderCode) { this.accountHolderCode = accountHolderCode; } public void setAccountHolderTypeCode(String accountHolderTypeCode) { this.accountHolderTypeCode = accountHolderTypeCode; } public void setAic(String aic) { this.aic = aic; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public void setCustomerTypeCode(String customerTypeCode) { this.customerTypeCode = customerTypeCode; } public void setDocumentNumber(String documentNumber) { this.documentNumber = documentNumber; } public void setDocumentTypeCode(String documentTypeCode) { this.documentTypeCode = documentTypeCode; } public void setExpirationDate(LocalDate expirationDate) { this.expirationDate = expirationDate; } public void setId(String id) { this.id = id; } public void setImportDate(LocalDateTime importDate) { this.importDate = importDate; } public void setLot(String lot) { this.lot = lot; } public void setMovementCode(String movementCode) { this.movementCode = movementCode; } public void setQuantity(double quantity) { this.quantity = quantity; } public void setRawExpirationDate(String rawExpirationDate) { this.rawExpirationDate = rawExpirationDate; } public void setRecipientCode(String recipientCode) { this.recipientCode = recipientCode; } public void setRecipientTypeCode(String recipientTypeCode) { this.recipientTypeCode = recipientTypeCode; } public void setSenderCode(String senderCode) { this.senderCode = senderCode; } public void setSenderTypeCode(String senderTypeCode) { this.senderTypeCode = senderTypeCode; } public void setTransmissionDate(String transmissionDate) { this.transmissionDate = transmissionDate; } public void setTransmissionDateTime(LocalDateTime transmissionDateTime) { this.transmissionDateTime = transmissionDateTime; } public void setTransmissionTime(String transmissionTime) { this.transmissionTime = transmissionTime; } public void setValue(Double value) { this.value = value; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
Movement.quantity should not be validated
json-invoice-processor/src/main/java/it/gov/aifa/invoice_processor/entity/movement/Movement.java
Movement.quantity should not be validated
Java
mit
67f5e4665d82363453357aa09c58331a32ce9b59
0
McJty/RFTools,ReneMuetti/RFTools,Adaptivity/RFTools,Elecs-Mods/RFTools
package com.mcjty.rftools.crafting; import com.mcjty.rftools.blocks.ModBlocks; import com.mcjty.rftools.blocks.dimletconstruction.DimletConstructionConfiguration; import com.mcjty.rftools.items.ModItems; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.RecipeSorter; import java.util.HashMap; import java.util.Map; public final class ModCrafting { static { RecipeSorter.register("rftools:shapedpreserving", PreservingShapedRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); RecipeSorter.register("rftools:shapedknowndimlet", KnownDimletShapedRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); RecipeSorter.register("rftools:nbtmatchingrecipe", NBTMatchingRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); } public static void init() { Object inkSac = Item.itemRegistry.getObjectById(351); GameRegistry.addRecipe(new ItemStack(ModItems.networkMonitorItem), "rlr", "iri", "rlr", 'r', Items.redstone, 'i', Items.iron_ingot, 'l', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.rfToolsManualItem), " r ", "rbr", " r ", 'r', Items.redstone, 'b', Items.book); GameRegistry.addRecipe(new ItemStack(ModItems.rfToolsManualDimensionItem), "r r", " b ", "r r", 'r', Items.redstone, 'b', Items.book); ItemStack lapisStack = new ItemStack(Items.dye, 1, 4); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineFrame), "ili", "g g", "ili", 'i', Items.iron_ingot, 'g', Items.gold_nugget, 'l', lapisStack); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineBase), " ", "ggg", "sss", 'g', Items.gold_nugget, 's', Blocks.stone); Object redstoneTorch = Item.itemRegistry.getObject("redstone_torch"); GameRegistry.addRecipe(new ItemStack(ModBlocks.monitorBlock), " T ", "rMr", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.liquidMonitorBlock), " T ", "bMb", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'b', Items.bucket); GameRegistry.addRecipe(new ItemStack(ModBlocks.crafterBlock1), " T ", "cMc", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'c', Blocks.crafting_table); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack((Item) redstoneTorch), null, new ItemStack(Blocks.crafting_table), new ItemStack(ModBlocks.crafterBlock1), new ItemStack(Blocks.crafting_table), null, new ItemStack((Item) redstoneTorch), null }, new ItemStack(ModBlocks.crafterBlock2), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack((Item) redstoneTorch), null, new ItemStack(Blocks.crafting_table), new ItemStack(ModBlocks.crafterBlock2), new ItemStack(Blocks.crafting_table), null, new ItemStack((Item) redstoneTorch), null }, new ItemStack(ModBlocks.crafterBlock3), 4)); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineInfuserBlock), "srs", "dMd", "srs", 'M', ModBlocks.machineFrame, 's', ModItems.dimensionalShard, 'r', Items.redstone, 'd', Items.diamond); GameRegistry.addRecipe(new ItemStack(ModBlocks.storageScannerBlock), "ToT", "gMg", "ToT", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'o', Items.ender_pearl, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.relayBlock), "gTg", "gMg", "gTg", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.itemFilterBlock), "pcp", "rMr", "pTp", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'p', Items.paper, 'r', Items.redstone, 'c', Blocks.chest); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletFilterBlock), " u ", "rMr", " r ", 'M', ModBlocks.itemFilterBlock, 'u', ModItems.unknownDimlet, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterTransmitterBlock), "ooo", "rMr", "iii", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterReceiverBlock), "iii", "rMr", "ooo", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dialingDeviceBlock), "rrr", "TMT", "rrr", 'M', ModBlocks.machineFrame, 'r', Items.redstone, 'T', redstoneTorch); GameRegistry.addRecipe(new ItemStack(ModBlocks.destinationAnalyzerBlock), "o o", " M ", "o o", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterBoosterBlock), " B ", "BMB", " B ", 'M', ModBlocks.destinationAnalyzerBlock, 'B', Blocks.redstone_block); GameRegistry.addRecipe(new ItemStack(ModItems.chargedPorterItem), " e ", "eRe", "iei", 'e', Items.ender_pearl, 'R', Blocks.redstone_block, 'i', Items.iron_ingot); initLogicBlockCrafting(); GameRegistry.addRecipe(new ItemStack(ModBlocks.endergenicBlock), "DoD", "oMo", "DoD", 'M', ModBlocks.machineFrame, 'D', Items.diamond, 'o', Items.ender_pearl); GameRegistry.addRecipe(new ItemStack(ModBlocks.pearlInjectorBlock), " C ", "rMr", " H ", 'C', Blocks.chest, 'r', Items.redstone, 'M', ModBlocks.machineFrame, 'H', Blocks.hopper); GameRegistry.addRecipe(new ItemStack(ModBlocks.shieldBlock), "gTg", "rMr", "ooo", 'M', ModBlocks.machineFrame, 'o', Blocks.obsidian, 'r', Items.redstone, 'T', redstoneTorch, 'g', Items.gold_ingot); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(ModBlocks.shieldBlock), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block) }, new ItemStack(ModBlocks.shieldBlock2), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModBlocks.shieldBlock2), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard) }, new ItemStack(ModBlocks.shieldBlock3), 4)); GameRegistry.addRecipe(new ItemStack(ModBlocks.shieldTemplateBlock, 8), "www", "lgl", "www", 'w', Blocks.wool, 'l', lapisStack, 'g', Blocks.glass); GameRegistry.addSmelting(ModBlocks.dimensionalShardBlock, new ItemStack(ModItems.dimensionalShard, 4), 1.0f); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletResearcherBlock), "rur", "cMc", "iii", 'r', Items.redstone, 'u', ModItems.unknownDimlet, 'c', Items.comparator, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletScramblerBlock), "uru", "cMc", "iii", 'r', Items.redstone, 'u', ModItems.unknownDimlet, 'c', Items.repeater, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionEnscriberBlock), "rpr", "bMb", "iii", 'r', Items.redstone, 'p', Items.paper, 'b', inkSac, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionBuilderBlock), "oEo", "DMD", "ggg", 'o', Items.ender_pearl, 'E', Items.emerald, 'D', Items.diamond, 'M', ModBlocks.machineFrame, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionEditorBlock), "oEo", "DMD", "ggg", 'o', Items.redstone, 'E', Items.emerald, 'D', Items.diamond, 'M', ModBlocks.machineFrame, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.activityProbeBlock), "sss", "oMo", "sss", 'o', Items.ender_pearl, 's', ModItems.dimensionalShard, 'M', ModBlocks.machineFrame); GameRegistry.addRecipe(new ItemStack(ModBlocks.energyExtractorBlock), "RoR", "sMs", "RsR", 'o', Items.ender_pearl, 's', ModItems.dimensionalShard, 'M', ModBlocks.machineFrame, 'R', Blocks.redstone_block); GameRegistry.addRecipe(new ItemStack(ModBlocks.environmentalControllerBlock), "oDo", "GMI", "oEo", 'o', Items.ender_pearl, 'M', ModBlocks.machineFrame, 'D', Blocks.diamond_block, 'E', Blocks.emerald_block, 'G', Blocks.gold_block, 'I', Blocks.iron_block); GameRegistry.addRecipe(new ItemStack(ModBlocks.spawnerBlock), "rzr", "eMl", "rbr", 'M', ModBlocks.machineFrame, 'z', Items.rotten_flesh, 'e', Items.ender_pearl, 'l', Items.blaze_rod, 'b', Items.bone, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterBeamerBlock), "RGR", "GMG", "RGR", 'M', ModBlocks.machineFrame, 'R', Blocks.redstone_block, 'G', Blocks.glowstone); GameRegistry.addRecipe(new ItemStack(ModItems.emptyDimensionTab), "prp", "rpr", "prp", 'p', Items.paper, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModItems.dimensionMonitorItem), " u ", "rCr", " u ", 'u', ModItems.unknownDimlet, 'r', Items.redstone, 'C', Items.comparator); GameRegistry.addRecipe(new ItemStack(ModItems.phasedFieldGeneratorItem), "rsr", "sEs", "rsr", 'E', Items.ender_eye, 'r', Items.redstone, 's', ModItems.dimensionalShard); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalBlankBlock, 8), "bbb", "b*b", "bbb", 'b', Blocks.stone, '*', ModItems.dimensionalShard); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.dimensionalBlock), new ItemStack(ModBlocks.dimensionalBlankBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalSmallBlocks, 4), "bb ", "bb ", " ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCrossBlock, 5), " b ", "bbb", " b ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCross2Block, 5), "b b", " b ", "b b", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern1Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', inkSac); ItemStack bonemealStack = new ItemStack(Items.dye, 1, 15); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern2Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', bonemealStack); initScreenCrafting(); GameRegistry.addRecipe(new ItemStack(ModItems.dimletTemplate), "sss", "sps", "sss", 's', ModItems.dimensionalShard, 'p', Items.paper); initDimletConstructionCrafting(); initEnvModuleCrafting(); } private static void initEnvModuleCrafting() { Object inkSac = Item.itemRegistry.getObjectById(351); String[] syringeMatcher = new String[] { "level", "mobName" }; String[] pickMatcher = new String[] { "ench" }; ItemStack ironGolemSyringe = createMobSyringe("Iron Golem"); ItemStack ghastSyringe = createMobSyringe("Ghast"); ItemStack chickenSyringe = createMobSyringe("Chicken"); ItemStack batSyringe = createMobSyringe("Bat"); ItemStack horseSyringe = createMobSyringe("Horse"); ItemStack zombieSyringe = createMobSyringe("Zombie"); ItemStack diamondPick = createEnchantedItem(Items.diamond_pickaxe, Enchantment.efficiency.effectId, 3); ItemStack reds = new ItemStack(Items.redstone); ItemStack gold = new ItemStack(Items.gold_ingot); ItemStack ink = new ItemStack((Item) inkSac); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, chickenSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.featherFallingEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ironGolemSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.regenerationEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, horseSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.speedEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, diamondPick, null, reds, gold, reds, null, ink, null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.hasteEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, zombieSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.saturationEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ghastSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.flightEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.regenerationEModuleItem), ironGolemSyringe, ironGolemSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.regenerationPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.speedEModuleItem), horseSyringe, horseSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.speedPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.hasteEModuleItem), diamondPick, null, null}, new String[][] {null, pickMatcher, null, null}, new ItemStack(ModItems.hastePlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.saturationEModuleItem), zombieSyringe, zombieSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.saturationPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.featherFallingEModuleItem), chickenSyringe, batSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.featherFallingPlusEModuleItem))); GameRegistry.addRecipe(new ItemStack(ModItems.peacefulEModuleItem, 1), " p ", "rgr", " i ", 'p', ModItems.peaceEssenceItem, 'r', reds, 'g', gold, 'i', ink); } private static void initLogicBlockCrafting() { Object redstoneTorch = Item.itemRegistry.getObject("redstone_torch"); GameRegistry.addRecipe(new ItemStack(ModBlocks.sequencerBlock), "rTr", "TMT", "rTr", 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.counterBlock), "gcg", "TMT", "rTr", 'c', Items.clock, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase, 'g', Items.gold_nugget); GameRegistry.addRecipe(new ItemStack(ModBlocks.timerBlock), "rcr", "TMT", "rTr", 'c', Items.clock, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.enderMonitorBlock), "ror", "TMT", "rTr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionMonitorBlock), " u ", "TMT", "rCr", 'u', ModItems.unknownDimlet, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase, 'C', Items.comparator); GameRegistry.addRecipe(new ItemStack(ModBlocks.redstoneTransmitterBlock), "ror", "TMT", "rRr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', redstoneTorch, 'R', Blocks.redstone_block, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.redstoneReceiverBlock), "ror", "TMT", "rRr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', Items.comparator, 'R', Blocks.redstone_block, 'M', ModBlocks.machineBase); } private static void initDimletConstructionCrafting() { String[] syringeMatcher = new String[] { "level", "mobName" }; String[] pickMatcher = new String[] { "ench" }; GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[]{createMobSyringe("Iron Golem"), createMobSyringe("Enderman"), createMobSyringe("Snowman"), createMobSyringe("Bat"), createMobSyringe("Ocelot"), createMobSyringe("Squid"), createMobSyringe("Wolf"), createMobSyringe("Zombie Pigman"), createMobSyringe("Mooshroom")}, new String[][]{syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher}, new ItemStack(ModItems.peaceEssenceItem))); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletWorkbenchBlock), "gug", "cMc", "grg", 'M', ModBlocks.machineFrame, 'u', ModItems.unknownDimlet, 'c', Blocks.crafting_table, 'r', Items.redstone, 'g', Items.gold_nugget); GameRegistry.addRecipe(new ItemStack(ModBlocks.biomeAbsorberBlock), "dws", "wMw", "swd", 'M', ModBlocks.machineFrame, 'd', Blocks.dirt, 's', Blocks.sapling, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.biomeAbsorberBlock), new ItemStack(ModBlocks.biomeAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.materialAbsorberBlock), "dwc", "wMw", "swg", 'M', ModBlocks.machineFrame, 'd', Blocks.dirt, 'c', Blocks.cobblestone, 's', Blocks.sand, 'g', Blocks.gravel, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.materialAbsorberBlock), new ItemStack(ModBlocks.materialAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.liquidAbsorberBlock), "bwb", "wMw", "bwb", 'M', ModBlocks.machineFrame, 'b', Items.bucket, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.liquidAbsorberBlock), new ItemStack(ModBlocks.liquidAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.timeAbsorberBlock), "cwc", "wMw", "cwc", 'M', ModBlocks.machineFrame, 'c', Items.clock, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.timeAbsorberBlock), new ItemStack(ModBlocks.timeAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModItems.syringeItem), "i ", " i ", " b", 'i', Items.iron_ingot, 'b', Items.glass_bottle); ItemStack diamondPick = createEnchantedItem(Items.diamond_pickaxe, Enchantment.efficiency.effectId, 3); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, diamondPick, null, new ItemStack(Items.ender_eye), new ItemStack(Items.nether_star), new ItemStack(Items.ender_eye), null, new ItemStack(Items.ender_eye), null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.efficiencyEssenceItem))); ItemStack ironPick = createEnchantedItem(Items.iron_pickaxe, Enchantment.efficiency.effectId, 2); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ironPick, null, new ItemStack(Items.ender_eye), new ItemStack(Items.ghast_tear), new ItemStack(Items.ender_eye), null, new ItemStack(Items.ender_eye), null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.mediocreEfficiencyEssenceItem))); } private static ItemStack createEnchantedItem(Item item, int effectId, int amount) { ItemStack stack = new ItemStack(item); Map enchant = new HashMap(); enchant.put(effectId, amount); EnchantmentHelper.setEnchantments(enchant, stack); return stack; } private static void initScreenCrafting() { GameRegistry.addRecipe(new ItemStack(ModBlocks.screenControllerBlock), "ror", "gMg", "rgr", 'r', Items.redstone, 'o', Items.ender_pearl, 'M', ModBlocks.machineFrame, 'g', Blocks.glass); GameRegistry.addRecipe(new ItemStack(ModBlocks.screenBlock), "ggg", "gMg", "iii", 'M', ModBlocks.machineBase, 'g', Blocks.glass, 'i', Items.iron_ingot); initScreenModuleCrafting(); } private static void initScreenModuleCrafting() { Object inkSac = Item.itemRegistry.getObjectById(351); GameRegistry.addRecipe(new ItemStack(ModItems.textModuleItem), " p ", "rir", " b ", 'p', Items.paper, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.clockModuleItem), " c ", "rir", " b ", 'c', Items.clock, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.energyModuleItem), " r ", "rir", " b ", 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.dimensionModuleItem), " c ", "rir", " b ", 'c', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.fluidModuleItem), " c ", "rir", " b ", 'c', Items.bucket, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.inventoryModuleItem), " c ", "rir", " b ", 'c', Blocks.chest, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.counterModuleItem), " c ", "rir", " b ", 'c', Items.comparator, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.redstoneModuleItem), " c ", "rir", " b ", 'c', Items.repeater, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.machineInformationModuleItem), " f ", "rir", " b ", 'f', Blocks.furnace, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.computerModuleItem), " f ", "rir", " b ", 'f', Blocks.quartz_block, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.energyModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.energyPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.fluidModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.fluidPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.inventoryModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.inventoryPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.counterModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.counterPlusModuleItem), 4)); } private static ItemStack createMobSyringe(String mobName) { ItemStack syringe = new ItemStack(ModItems.syringeItem); NBTTagCompound tagCompound = new NBTTagCompound(); tagCompound.setString("mobName", mobName); tagCompound.setInteger("level", DimletConstructionConfiguration.maxMobInjections); syringe.setTagCompound(tagCompound); return syringe; } }
src/main/java/com/mcjty/rftools/crafting/ModCrafting.java
package com.mcjty.rftools.crafting; import com.mcjty.rftools.blocks.ModBlocks; import com.mcjty.rftools.blocks.dimletconstruction.DimletConstructionConfiguration; import com.mcjty.rftools.items.ModItems; import cpw.mods.fml.common.registry.GameRegistry; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.oredict.RecipeSorter; import java.util.HashMap; import java.util.Map; public final class ModCrafting { static { RecipeSorter.register("rftools:shapedpreserving", PreservingShapedRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); RecipeSorter.register("rftools:shapedknowndimlet", KnownDimletShapedRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); RecipeSorter.register("rftools:nbtmatchingrecipe", NBTMatchingRecipe.class, RecipeSorter.Category.SHAPED, "after:minecraft:shaped"); } public static void init() { Object inkSac = Item.itemRegistry.getObjectById(351); GameRegistry.addRecipe(new ItemStack(ModItems.networkMonitorItem), "rlr", "iri", "rlr", 'r', Items.redstone, 'i', Items.iron_ingot, 'l', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.rfToolsManualItem), " r ", "rbr", " r ", 'r', Items.redstone, 'b', Items.book); GameRegistry.addRecipe(new ItemStack(ModItems.rfToolsManualDimensionItem), "r r", " b ", "r r", 'r', Items.redstone, 'b', Items.book); ItemStack lapisStack = new ItemStack(Items.dye, 1, 4); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineFrame), "ili", "g g", "ili", 'i', Items.iron_ingot, 'g', Items.gold_nugget, 'l', lapisStack); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineBase), " ", "ggg", "sss", 'g', Items.gold_nugget, 's', Blocks.stone); Object redstoneTorch = Item.itemRegistry.getObject("redstone_torch"); GameRegistry.addRecipe(new ItemStack(ModBlocks.monitorBlock), " T ", "rMr", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.liquidMonitorBlock), " T ", "bMb", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'b', Items.bucket); GameRegistry.addRecipe(new ItemStack(ModBlocks.crafterBlock1), " T ", "cMc", " T ", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'c', Blocks.crafting_table); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack((Item) redstoneTorch), null, new ItemStack(Blocks.crafting_table), new ItemStack(ModBlocks.crafterBlock1), new ItemStack(Blocks.crafting_table), null, new ItemStack((Item) redstoneTorch), null }, new ItemStack(ModBlocks.crafterBlock2), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack((Item) redstoneTorch), null, new ItemStack(Blocks.crafting_table), new ItemStack(ModBlocks.crafterBlock2), new ItemStack(Blocks.crafting_table), null, new ItemStack((Item) redstoneTorch), null }, new ItemStack(ModBlocks.crafterBlock3), 4)); GameRegistry.addRecipe(new ItemStack(ModBlocks.machineInfuserBlock), "srs", "dMd", "srs", 'M', ModBlocks.machineFrame, 's', ModItems.dimensionalShard, 'r', Items.redstone, 'd', Items.diamond); GameRegistry.addRecipe(new ItemStack(ModBlocks.storageScannerBlock), "ToT", "gMg", "ToT", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'o', Items.ender_pearl, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.relayBlock), "gTg", "gMg", "gTg", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.itemFilterBlock), "pcp", "rMr", "pTp", 'M', ModBlocks.machineFrame, 'T', redstoneTorch, 'p', Items.paper, 'r', Items.redstone, 'c', Blocks.chest); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletFilterBlock), " u ", "rMr", " r ", 'M', ModBlocks.itemFilterBlock, 'y', ModItems.unknownDimlet, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterTransmitterBlock), "ooo", "rMr", "iii", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterReceiverBlock), "iii", "rMr", "ooo", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dialingDeviceBlock), "rrr", "TMT", "rrr", 'M', ModBlocks.machineFrame, 'r', Items.redstone, 'T', redstoneTorch); GameRegistry.addRecipe(new ItemStack(ModBlocks.destinationAnalyzerBlock), "o o", " M ", "o o", 'M', ModBlocks.machineFrame, 'o', Items.ender_pearl); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterBoosterBlock), " B ", "BMB", " B ", 'M', ModBlocks.destinationAnalyzerBlock, 'B', Blocks.redstone_block); GameRegistry.addRecipe(new ItemStack(ModItems.chargedPorterItem), " e ", "eRe", "iei", 'e', Items.ender_pearl, 'R', Blocks.redstone_block, 'i', Items.iron_ingot); initLogicBlockCrafting(); GameRegistry.addRecipe(new ItemStack(ModBlocks.endergenicBlock), "DoD", "oMo", "DoD", 'M', ModBlocks.machineFrame, 'D', Items.diamond, 'o', Items.ender_pearl); GameRegistry.addRecipe(new ItemStack(ModBlocks.pearlInjectorBlock), " C ", "rMr", " H ", 'C', Blocks.chest, 'r', Items.redstone, 'M', ModBlocks.machineFrame, 'H', Blocks.hopper); GameRegistry.addRecipe(new ItemStack(ModBlocks.shieldBlock), "gTg", "rMr", "ooo", 'M', ModBlocks.machineFrame, 'o', Blocks.obsidian, 'r', Items.redstone, 'T', redstoneTorch, 'g', Items.gold_ingot); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(ModBlocks.shieldBlock), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block), new ItemStack(Blocks.obsidian), new ItemStack(Blocks.redstone_block) }, new ItemStack(ModBlocks.shieldBlock2), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModBlocks.shieldBlock2), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard), new ItemStack(Blocks.obsidian), new ItemStack(ModItems.dimensionalShard) }, new ItemStack(ModBlocks.shieldBlock3), 4)); GameRegistry.addRecipe(new ItemStack(ModBlocks.shieldTemplateBlock, 8), "www", "lgl", "www", 'w', Blocks.wool, 'l', lapisStack, 'g', Blocks.glass); GameRegistry.addSmelting(ModBlocks.dimensionalShardBlock, new ItemStack(ModItems.dimensionalShard, 4), 1.0f); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletResearcherBlock), "rur", "cMc", "iii", 'r', Items.redstone, 'u', ModItems.unknownDimlet, 'c', Items.comparator, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletScramblerBlock), "uru", "cMc", "iii", 'r', Items.redstone, 'u', ModItems.unknownDimlet, 'c', Items.repeater, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionEnscriberBlock), "rpr", "bMb", "iii", 'r', Items.redstone, 'p', Items.paper, 'b', inkSac, 'M', ModBlocks.machineFrame, 'i', Items.iron_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionBuilderBlock), "oEo", "DMD", "ggg", 'o', Items.ender_pearl, 'E', Items.emerald, 'D', Items.diamond, 'M', ModBlocks.machineFrame, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionEditorBlock), "oEo", "DMD", "ggg", 'o', Items.redstone, 'E', Items.emerald, 'D', Items.diamond, 'M', ModBlocks.machineFrame, 'g', Items.gold_ingot); GameRegistry.addRecipe(new ItemStack(ModBlocks.activityProbeBlock), "sss", "oMo", "sss", 'o', Items.ender_pearl, 's', ModItems.dimensionalShard, 'M', ModBlocks.machineFrame); GameRegistry.addRecipe(new ItemStack(ModBlocks.energyExtractorBlock), "RoR", "sMs", "RsR", 'o', Items.ender_pearl, 's', ModItems.dimensionalShard, 'M', ModBlocks.machineFrame, 'R', Blocks.redstone_block); GameRegistry.addRecipe(new ItemStack(ModBlocks.environmentalControllerBlock), "oDo", "GMI", "oEo", 'o', Items.ender_pearl, 'M', ModBlocks.machineFrame, 'D', Blocks.diamond_block, 'E', Blocks.emerald_block, 'G', Blocks.gold_block, 'I', Blocks.iron_block); GameRegistry.addRecipe(new ItemStack(ModBlocks.spawnerBlock), "rzr", "eMl", "rbr", 'M', ModBlocks.machineFrame, 'z', Items.rotten_flesh, 'e', Items.ender_pearl, 'l', Items.blaze_rod, 'b', Items.bone, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModBlocks.matterBeamerBlock), "RGR", "GMG", "RGR", 'M', ModBlocks.machineFrame, 'R', Blocks.redstone_block, 'G', Blocks.glowstone); GameRegistry.addRecipe(new ItemStack(ModItems.emptyDimensionTab), "prp", "rpr", "prp", 'p', Items.paper, 'r', Items.redstone); GameRegistry.addRecipe(new ItemStack(ModItems.dimensionMonitorItem), " u ", "rCr", " u ", 'u', ModItems.unknownDimlet, 'r', Items.redstone, 'C', Items.comparator); GameRegistry.addRecipe(new ItemStack(ModItems.phasedFieldGeneratorItem), "rsr", "sEs", "rsr", 'E', Items.ender_eye, 'r', Items.redstone, 's', ModItems.dimensionalShard); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalBlankBlock, 8), "bbb", "b*b", "bbb", 'b', Blocks.stone, '*', ModItems.dimensionalShard); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.dimensionalBlock), new ItemStack(ModBlocks.dimensionalBlankBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalSmallBlocks, 4), "bb ", "bb ", " ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCrossBlock, 5), " b ", "bbb", " b ", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalCross2Block, 5), "b b", " b ", "b b", 'b', ModBlocks.dimensionalBlankBlock); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern1Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', inkSac); ItemStack bonemealStack = new ItemStack(Items.dye, 1, 15); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionalPattern2Block, 7), "bxb", "bbb", "bxb", 'b', ModBlocks.dimensionalBlankBlock, 'x', bonemealStack); initScreenCrafting(); GameRegistry.addRecipe(new ItemStack(ModItems.dimletTemplate), "sss", "sps", "sss", 's', ModItems.dimensionalShard, 'p', Items.paper); initDimletConstructionCrafting(); initEnvModuleCrafting(); } private static void initEnvModuleCrafting() { Object inkSac = Item.itemRegistry.getObjectById(351); String[] syringeMatcher = new String[] { "level", "mobName" }; String[] pickMatcher = new String[] { "ench" }; ItemStack ironGolemSyringe = createMobSyringe("Iron Golem"); ItemStack ghastSyringe = createMobSyringe("Ghast"); ItemStack chickenSyringe = createMobSyringe("Chicken"); ItemStack batSyringe = createMobSyringe("Bat"); ItemStack horseSyringe = createMobSyringe("Horse"); ItemStack zombieSyringe = createMobSyringe("Zombie"); ItemStack diamondPick = createEnchantedItem(Items.diamond_pickaxe, Enchantment.efficiency.effectId, 3); ItemStack reds = new ItemStack(Items.redstone); ItemStack gold = new ItemStack(Items.gold_ingot); ItemStack ink = new ItemStack((Item) inkSac); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, chickenSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.featherFallingEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ironGolemSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.regenerationEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, horseSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.speedEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, diamondPick, null, reds, gold, reds, null, ink, null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.hasteEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, zombieSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.saturationEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ghastSyringe, null, reds, gold, reds, null, ink, null}, new String[][] {null, syringeMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.flightEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.regenerationEModuleItem), ironGolemSyringe, ironGolemSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.regenerationPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.speedEModuleItem), horseSyringe, horseSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.speedPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.hasteEModuleItem), diamondPick, null, null}, new String[][] {null, pickMatcher, null, null}, new ItemStack(ModItems.hastePlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.saturationEModuleItem), zombieSyringe, zombieSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.saturationPlusEModuleItem))); GameRegistry.addRecipe(new NBTMatchingRecipe(2, 2, new ItemStack[]{new ItemStack(ModItems.featherFallingEModuleItem), chickenSyringe, batSyringe, null}, new String[][] {null, syringeMatcher, syringeMatcher, null}, new ItemStack(ModItems.featherFallingPlusEModuleItem))); GameRegistry.addRecipe(new ItemStack(ModItems.peacefulEModuleItem, 1), " p ", "rgr", " i ", 'p', ModItems.peaceEssenceItem, 'r', reds, 'g', gold, 'i', ink); } private static void initLogicBlockCrafting() { Object redstoneTorch = Item.itemRegistry.getObject("redstone_torch"); GameRegistry.addRecipe(new ItemStack(ModBlocks.sequencerBlock), "rTr", "TMT", "rTr", 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.counterBlock), "gcg", "TMT", "rTr", 'c', Items.clock, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase, 'g', Items.gold_nugget); GameRegistry.addRecipe(new ItemStack(ModBlocks.timerBlock), "rcr", "TMT", "rTr", 'c', Items.clock, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.enderMonitorBlock), "ror", "TMT", "rTr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimensionMonitorBlock), " u ", "TMT", "rCr", 'u', ModItems.unknownDimlet, 'r', Items.redstone, 'T', redstoneTorch, 'M', ModBlocks.machineBase, 'C', Items.comparator); GameRegistry.addRecipe(new ItemStack(ModBlocks.redstoneTransmitterBlock), "ror", "TMT", "rRr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', redstoneTorch, 'R', Blocks.redstone_block, 'M', ModBlocks.machineBase); GameRegistry.addRecipe(new ItemStack(ModBlocks.redstoneReceiverBlock), "ror", "TMT", "rRr", 'o', Items.ender_pearl, 'r', Items.redstone, 'T', Items.comparator, 'R', Blocks.redstone_block, 'M', ModBlocks.machineBase); } private static void initDimletConstructionCrafting() { String[] syringeMatcher = new String[] { "level", "mobName" }; String[] pickMatcher = new String[] { "ench" }; GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[]{createMobSyringe("Iron Golem"), createMobSyringe("Enderman"), createMobSyringe("Snowman"), createMobSyringe("Bat"), createMobSyringe("Ocelot"), createMobSyringe("Squid"), createMobSyringe("Wolf"), createMobSyringe("Zombie Pigman"), createMobSyringe("Mooshroom")}, new String[][]{syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher, syringeMatcher}, new ItemStack(ModItems.peaceEssenceItem))); GameRegistry.addRecipe(new ItemStack(ModBlocks.dimletWorkbenchBlock), "gug", "cMc", "grg", 'M', ModBlocks.machineFrame, 'u', ModItems.unknownDimlet, 'c', Blocks.crafting_table, 'r', Items.redstone, 'g', Items.gold_nugget); GameRegistry.addRecipe(new ItemStack(ModBlocks.biomeAbsorberBlock), "dws", "wMw", "swd", 'M', ModBlocks.machineFrame, 'd', Blocks.dirt, 's', Blocks.sapling, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.biomeAbsorberBlock), new ItemStack(ModBlocks.biomeAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.materialAbsorberBlock), "dwc", "wMw", "swg", 'M', ModBlocks.machineFrame, 'd', Blocks.dirt, 'c', Blocks.cobblestone, 's', Blocks.sand, 'g', Blocks.gravel, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.materialAbsorberBlock), new ItemStack(ModBlocks.materialAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.liquidAbsorberBlock), "bwb", "wMw", "bwb", 'M', ModBlocks.machineFrame, 'b', Items.bucket, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.liquidAbsorberBlock), new ItemStack(ModBlocks.liquidAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModBlocks.timeAbsorberBlock), "cwc", "wMw", "cwc", 'M', ModBlocks.machineFrame, 'c', Items.clock, 'w', Blocks.wool); GameRegistry.addShapelessRecipe(new ItemStack(ModBlocks.timeAbsorberBlock), new ItemStack(ModBlocks.timeAbsorberBlock)); GameRegistry.addRecipe(new ItemStack(ModItems.syringeItem), "i ", " i ", " b", 'i', Items.iron_ingot, 'b', Items.glass_bottle); ItemStack diamondPick = createEnchantedItem(Items.diamond_pickaxe, Enchantment.efficiency.effectId, 3); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, diamondPick, null, new ItemStack(Items.ender_eye), new ItemStack(Items.nether_star), new ItemStack(Items.ender_eye), null, new ItemStack(Items.ender_eye), null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.efficiencyEssenceItem))); ItemStack ironPick = createEnchantedItem(Items.iron_pickaxe, Enchantment.efficiency.effectId, 2); GameRegistry.addRecipe(new NBTMatchingRecipe(3, 3, new ItemStack[] {null, ironPick, null, new ItemStack(Items.ender_eye), new ItemStack(Items.ghast_tear), new ItemStack(Items.ender_eye), null, new ItemStack(Items.ender_eye), null}, new String[][] {null, pickMatcher, null, null, null, null, null, null, null}, new ItemStack(ModItems.mediocreEfficiencyEssenceItem))); } private static ItemStack createEnchantedItem(Item item, int effectId, int amount) { ItemStack stack = new ItemStack(item); Map enchant = new HashMap(); enchant.put(effectId, amount); EnchantmentHelper.setEnchantments(enchant, stack); return stack; } private static void initScreenCrafting() { GameRegistry.addRecipe(new ItemStack(ModBlocks.screenControllerBlock), "ror", "gMg", "rgr", 'r', Items.redstone, 'o', Items.ender_pearl, 'M', ModBlocks.machineFrame, 'g', Blocks.glass); GameRegistry.addRecipe(new ItemStack(ModBlocks.screenBlock), "ggg", "gMg", "iii", 'M', ModBlocks.machineBase, 'g', Blocks.glass, 'i', Items.iron_ingot); initScreenModuleCrafting(); } private static void initScreenModuleCrafting() { Object inkSac = Item.itemRegistry.getObjectById(351); GameRegistry.addRecipe(new ItemStack(ModItems.textModuleItem), " p ", "rir", " b ", 'p', Items.paper, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.clockModuleItem), " c ", "rir", " b ", 'c', Items.clock, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.energyModuleItem), " r ", "rir", " b ", 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.dimensionModuleItem), " c ", "rir", " b ", 'c', Items.ender_pearl, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.fluidModuleItem), " c ", "rir", " b ", 'c', Items.bucket, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.inventoryModuleItem), " c ", "rir", " b ", 'c', Blocks.chest, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.counterModuleItem), " c ", "rir", " b ", 'c', Items.comparator, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.redstoneModuleItem), " c ", "rir", " b ", 'c', Items.repeater, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.machineInformationModuleItem), " f ", "rir", " b ", 'f', Blocks.furnace, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new ItemStack(ModItems.computerModuleItem), " f ", "rir", " b ", 'f', Blocks.quartz_block, 'r', Items.redstone, 'i', Items.iron_ingot, 'b', inkSac); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.energyModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.energyPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.fluidModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.fluidPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.inventoryModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.inventoryPlusModuleItem), 4)); GameRegistry.addRecipe(new PreservingShapedRecipe(3, 3, new ItemStack[] { null, new ItemStack(Items.ender_pearl), null, new ItemStack(Items.gold_ingot), new ItemStack(ModItems.counterModuleItem), new ItemStack(Items.gold_ingot), null, new ItemStack(Items.ender_pearl), null }, new ItemStack(ModItems.counterPlusModuleItem), 4)); } private static ItemStack createMobSyringe(String mobName) { ItemStack syringe = new ItemStack(ModItems.syringeItem); NBTTagCompound tagCompound = new NBTTagCompound(); tagCompound.setString("mobName", mobName); tagCompound.setInteger("level", DimletConstructionConfiguration.maxMobInjections); syringe.setTagCompound(tagCompound); return syringe; } }
Fixed crafting recipe for the dimlet filter. The unknown dimlet was missing.
src/main/java/com/mcjty/rftools/crafting/ModCrafting.java
Fixed crafting recipe for the dimlet filter. The unknown dimlet was missing.
Java
mit
c87f83bfd53741e2f781c7b7733d31d34fce8f11
0
ddouglascarr/liquidcanon-api,ddouglascarr/liquidcanon-api,ddouglascarr/liquidcanon-api
package org.ddouglascarr.models; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.data.annotation.ReadOnlyProperty; import java.util.Date; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="member") public class Member { @Id @GeneratedValue private Long id; @Column(name="password_liquidcanon") @JsonIgnore private String password; private String login; private String name; private Boolean admin; private String notify_email; private Boolean active; private Date last_activity; @ReadOnlyProperty @ManyToMany @JoinTable( name = "privilege", joinColumns = @JoinColumn(name = "member_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "unit_id", referencedColumnName = "id") ) private List<Unit> units; public Member() {} public Member(Member member) { this.id = member.id; this.login = member.login; this.name = member.name; this.admin = member.admin; this.last_activity = member.last_activity; this.active = member.active; this.password = member.password; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getAdmin() { return admin; } public void setAdmin(Boolean admin) { this.admin = admin; } public String getNotify_email() { return notify_email; } public void setNotify_email(String notify_email) { this.notify_email = notify_email; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Date getLast_activity() { return last_activity; } public void setLast_activity(Date last_activity) { this.last_activity = last_activity; } public List<Unit> getUnits() { return units; } public void setUnits(List<Unit> units) { this.units = units; } }
src/main/java/org/ddouglascarr/models/Member.java
package org.ddouglascarr.models; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="member") public class Member { @Id @GeneratedValue private Long id; @Column(name="password_liquidcanon") @JsonIgnore private String password; private String login; private String name; private Boolean admin; private String notify_email; private Boolean active; private Date last_activity; @JsonIgnore @ManyToMany @JoinTable( name = "privilege", joinColumns = @JoinColumn(name = "member_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "unit_id", referencedColumnName = "id") ) private List<Unit> units; public Member() {} public Member(Member member) { this.id = member.id; this.login = member.login; this.name = member.name; this.admin = member.admin; this.last_activity = member.last_activity; this.active = member.active; this.password = member.password; } // Getters and Setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getLogin() { return login; } public void setLogin(String login) { this.login = login; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getAdmin() { return admin; } public void setAdmin(Boolean admin) { this.admin = admin; } public String getNotify_email() { return notify_email; } public void setNotify_email(String notify_email) { this.notify_email = notify_email; } public Boolean getActive() { return active; } public void setActive(Boolean active) { this.active = active; } public Date getLast_activity() { return last_activity; } public void setLast_activity(Date last_activity) { this.last_activity = last_activity; } public List<Unit> getUnits() { return units; } public void setUnits(List<Unit> units) { this.units = units; } }
List units in GET /members/{memberId}
src/main/java/org/ddouglascarr/models/Member.java
List units in GET /members/{memberId}
Java
mit
fc08d9b88b5c0bbf9be46f61212da9b192155ded
0
samphippen/spe,samphippen/spe,samphippen/spe,samphippen/spe
package uk.me.graphe.client; import java.util.Collection; import com.google.gwt.widgetideas.graphics.client.Color; import com.google.gwt.widgetideas.graphics.client.GWTCanvas; public class DrawingImpl implements Drawing { //used for panning public int offsetX, offsetY; public double zoom; // JSNI method for webgl, comments omitted because it is one big comment... private static native void drawGraph3D(String verticesString, String edgesString) /*-{ var circleCoords = new Array(1000); for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000); var gl; var shaderProgram; var mvMatrix; var mvMatrixStack = []; var colors = [[0.0, 0.0, 0.0], // BLACK 0 [1.0, 1.0, 1.0], // WHITE 1 [1.0, 0.0, 0.0], // RED 2 [0.0, 1.0, 0.0], // GREEN 3 [0.0, 0.0, 1.0], // BLUE 4 [1.0, 1.0, 0.0], // YELLOW 5 [1.0, 0.317, 1.0], // PINK 6 [0.5, 0.5, 0.5], // GREY 7 ]; // Sylvester.js Libary eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{})) // gtUtils.js Libary Matrix.Translation = function (v) { if (v.elements.length == 2) { var r = Matrix.I(3); r.elements[2][0] = v.elements[0]; r.elements[2][1] = v.elements[1]; return r; } if (v.elements.length == 3) { var r = Matrix.I(4); r.elements[0][3] = v.elements[0]; r.elements[1][3] = v.elements[1]; r.elements[2][3] = v.elements[2]; return r; } throw "Invalid length for Translation"; } Matrix.prototype.flatten = function () { var result = []; if (this.elements.length == 0) return []; for (var j = 0; j < this.elements[0].length; j++) for (var i = 0; i < this.elements.length; i++) result.push(this.elements[i][j]); return result; } Matrix.prototype.ensure4x4 = function() { if (this.elements.length == 4 && this.elements[0].length == 4) return this; if (this.elements.length > 4 || this.elements[0].length > 4) return null; for (var i = 0; i < this.elements.length; i++) { for (var j = this.elements[i].length; j < 4; j++) { if (i == j) this.elements[i].push(1); else this.elements[i].push(0); } } for (var i = this.elements.length; i < 4; i++) { if (i == 0) this.elements.push([1, 0, 0, 0]); else if (i == 1) this.elements.push([0, 1, 0, 0]); else if (i == 2) this.elements.push([0, 0, 1, 0]); else if (i == 3) this.elements.push([0, 0, 0, 1]); } return this; }; Matrix.prototype.make3x3 = function() { if (this.elements.length != 4 || this.elements[0].length != 4) return null; return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], [this.elements[1][0], this.elements[1][1], this.elements[1][2]], [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); }; Vector.prototype.flatten = function () { return this.elements; }; function mht(m) { var s = ""; if (m.length == 16) { for (var i = 0; i < 4; i++) { s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>"; } } else if (m.length == 9) { for (var i = 0; i < 3; i++) { s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>"; } } else { return m.toString(); } return s; } function makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz) { var eye = $V([ex, ey, ez]); var center = $V([cx, cy, cz]); var up = $V([ux, uy, uz]); var mag; var z = eye.subtract(center).toUnitVector(); var x = up.cross(z).toUnitVector(); var y = z.cross(x).toUnitVector(); var m = $M([[x.e(1), x.e(2), x.e(3), 0], [y.e(1), y.e(2), y.e(3), 0], [z.e(1), z.e(2), z.e(3), 0], [0, 0, 0, 1]]); var t = $M([[1, 0, 0, -ex], [0, 1, 0, -ey], [0, 0, 1, -ez], [0, 0, 0, 1]]); return m.x(t); } function makePerspective(fovy, aspect, znear, zfar) { var ymax = znear * Math.tan(fovy * Math.PI / 360.0); var ymin = -ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); } function makeFrustum(left, right, bottom, top, znear, zfar) { var X = 2*znear/(right-left); var Y = 2*znear/(top-bottom); var A = (right+left)/(right-left); var B = (top+bottom)/(top-bottom); var C = -(zfar+znear)/(zfar-znear); var D = -2*zfar*znear/(zfar-znear); return $M([[X, 0, A, 0], [0, Y, B, 0], [0, 0, C, D], [0, 0, -1, 0]]); } function makeOrtho(left, right, bottom, top, znear, zfar) { var tx = - (right + left) / (right - left); var ty = - (top + bottom) / (top - bottom); var tz = - (zfar + znear) / (zfar - znear); return $M([[2 / (right - left), 0, 0, tx], [0, 2 / (top - bottom), 0, ty], [0, 0, -2 / (zfar - znear), tz], [0, 0, 0, 1]]); } // End of Libaries function initGL(canvas) { try { gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(e) { } if (!gl) { alert("Could not initialise WebGL"); } } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var str = ""; var k = shaderScript.firstChild; while (k) { if (k.nodeType == 3) { str += k.textContent; } k = k.nextSibling; } var shader; if (shaderScript.type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, str); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } function mvPushMatrix(m) { if (m) { mvMatrixStack.push(m.dup()); mvMatrix = m.dup(); } else { mvMatrixStack.push(mvMatrix.dup()); } } function mvPopMatrix() { if (mvMatrixStack.length == 0) { throw "Invalid popMatrix!"; } mvMatrix = mvMatrixStack.pop(); return mvMatrix; } function loadIdentity() { mvMatrix = Matrix.I(4); } function multMatrix(m) { mvMatrix = mvMatrix.x(m); } function mvTranslate(v) { var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } function mvRotate(ang, v) { var arad = ang * Math.PI / 180.0; var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } var pMatrix; function perspective(fovy, aspect, znear, zfar) { pMatrix = makePerspective(fovy, aspect, znear, zfar); } function setMatrixUniforms() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); } function compareXValue(array1, array2) { var value1 = array1[0]; var value2 = array2[0]; if (value1 > value2) return 1; if (value1 < value2) return -1; return 0; } function setupShaders(){ var headID = document.getElementsByTagName("head")[0]; var fsScript = document.createElement('script'); fsScript.id="shader-fs"; fsScript.type = 'x-shader/x-fragment'; fsScript.text = "#ifdef GL_ES\n\ precision highp float;\n\ #endif\n\ varying vec4 vColor;\n\ void main(void) {\n\ gl_FragColor = vColor;\n\ }"; var vsScript = document.createElement('script'); vsScript.id="shader-vs"; vsScript.type = 'x-shader/x-vertex'; vsScript.text = "attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ uniform mat4 uMVMatrix;\n\ uniform mat4 uPMatrix;\n\ \n\ varying vec4 vColor;\n\ \n\ void main(void) {\n\ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\ vColor = aVertexColor;\n\ }"; headID.appendChild(vsScript); headID.appendChild(fsScript); initShaders(); } function setupCanvas(){ canvas1 = document.getElementsByTagName("canvas")[1]; canvas1.style.position = "absolute"; canvas1.style.zIndex = 10; canvas1.style.opacity = 0.5; canvas = document.getElementsByTagName("canvas")[0]; canvas.style.zIndex = 0; initGL(canvas); } function setupGL(){ setupCanvas(); setupShaders(); gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0); loadIdentity(); var uTop = 2.478; var uLeft = -uTop; mvTranslate([uLeft,uTop, -10.0]) mvPushMatrix(); } // Drawing functions function drawPolygon(pixelVertices,colorNum) { var factor; var glWidth = 4.92; var vertices = new Float32Array(1000); var polygonColors = new Float32Array(1000); var vl = 0; if(canvas.width>=canvas.height) factor = glWidth/canvas.height; else factor = glWidth/canvas.width; for(var i=0;i<pixelVertices.length;i++){ pixelVertices[i] = (pixelVertices[i])*factor; if (i%2){ vertices[vl] = -pixelVertices[i]; vl++; vertices[vl] = (4.0); } else { vertices[vl] = (pixelVertices[i]); } vl++; } vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = vl / 3.0; vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); for(var i=0;i<(vl / 3.0)*4;i+=4){ polygonColors[i] = colors[colorNum][0]; polygonColors[i+1] = colors[colorNum][1]; polygonColors[i+2] = colors[colorNum][2]; polygonColors[i+3] = 1.0; } gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = vl / 3.0; gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0); } function drawLine(left1,top1,left2,top2,width,color) { if(top1 <= top2){ var temp1 = left1; var temp2 = top1; left1 = left2; top1 = top2; left2 = temp1; top2 = temp2; } var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1))); var vHeight = top1-top2; var hWidth = left1-left2; var deg = 180/Math.PI; var angle = Math.atan(vHeight/hWidth); var angle2 = ((Math.PI/2)-angle); var height2 = Math.sin(angle2)*(width/2); var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2)); if(angle*deg<0) { var topRightX = left1-(width2); var topRightY = top1-height2; var topLeftX = left1+(width2); var topLeftY = top1+height2; var bottomRightX = left2-(width2); var bottomRightY = top2-height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2+height2; } else { var topRightX = left1-(width2); var topRightY = top1+height2; var topLeftX = left1+(width2); var topLeftY = top1-height2; var bottomRightX = left2-(width2); var bottomRightY = top2+height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2-height2; } var pvertices = new Float32Array([ topRightX, topRightY, topLeftX, topLeftY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY ]); drawPolygon(pvertices,color); } function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);} function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){ var diam = width/2; var topOffset = Math.round(Math.sin(rotation)*diam); var leftOffset = Math.round(Math.cos(rotation)*diam); drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color); } function drawDiamond(left,top,width,height,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(8); pvertices[0] = left; pvertices[1] = top-halfHeight; pvertices[2] = left-halfWidth; pvertices[3] = top; pvertices[4] = left+halfWidth; pvertices[5] = top; pvertices[6] = left; pvertices[7] = top+halfHeight; drawPolygon(pvertices,color); } function drawTriang(left,top,width,height,rotation,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(6); pvertices[0] = 0; pvertices[1] = 0-halfHeight; pvertices[2] = 0-halfWidth; pvertices[3] = 0+halfHeight; pvertices[4] = 0+halfWidth; pvertices[5] = 0+halfHeight; var j = 0; for (i=0;i<3;i++) { var tempX = pvertices[j]; var tempY = pvertices[j+1]; pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+left); j++; pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+top); j++; } drawPolygon(pvertices,color); } function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)}; function drawCircleDim(left,top,width,height,color){ left = Math.round(left); top = Math.round(top); width = Math.round(width); height = Math.round(height); var w = Math.round(width/2); var h = Math.round(height/2); var numSections; if(width>height)numSections = width*2; else numSections = height*2; if(numSections>33)numSections = 33; if(numSections<10)numSections = 10; var delta_theta = 2.0 * Math.PI / numSections var theta = 0 if(circleCoords[w][h]==undefined) { //alert("make circle "+r); circleCoords[w][h] = new Array(numSections); circleCoords[w][h] = new Array(numSections); for (i = 0; i < numSections ; i++) { circleCoords[w][h][i] = new Array(2); x = (w * Math.cos(theta)); y = (h * Math.sin(theta)); x = Math.round(x*1000)/1000 y = Math.round(y*1000)/1000 circleCoords[w][h][i][1] = x; circleCoords[w][h][i][0] = y; theta += delta_theta } circleCoords[w][h].sort(compareXValue); for(var i = 0;i<numSections-1;i++) { if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1]) { temp = circleCoords[w][h][i]; circleCoords[w][h][i] = circleCoords[w][h][i+1]; circleCoords[w][h][i+1] = temp; } } } var j = 0; var pvertices = new Float32Array(numSections*2); for (i=0;i<numSections;i++) { pvertices[j] = circleCoords[w][h][i][1]+left; j++; pvertices[j] = circleCoords[w][h][i][0]+top; j++; } drawPolygon(pvertices,color); } function drawLineArrow(left1,top1,left2,top2,width,color) { var opp = top1-top2; var adj = left1-left2; var angle = Math.atan(opp/adj)+Math.PI/2; if(left1>left2 )angle+=Math.PI; drawLine(left1,top1,left2,top2,width,color); var triLeft = left1-Math.round(adj/2); var triTop = top1-Math.round(opp/2); drawTriang(triLeft,triTop,20,20,angle,color); } //Styling functions // BLACK 0 // WHITE 1 // RED 2 // GREEN 3 // BLUE 4 // YELLOW 5 // PINK 6 // GREY 7 function drawEdge(left1,top1, left2,top2,style){ switch(style){ case 100: // FLOW CHART // Draw line with Arrow at end drawLineArrow(left1,top1,left2,top2,2,0); break; case -100: // Draw line with Arrow at end - HIGHLIGHTED drawLineArrow(left1,top1,left2,top2,2,6); break; case -10: drawLine(left1,top1,left2,top2,2,6); break; default: //Default edge style: black line drawLine(left1,top1,left2,top2,2,0); } } function flowTerminator(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; flowTerminatorNoStroke(left,top,width,height,strokeColor); flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color); } function flowTerminatorNoStroke(left,top,width,height,color) { var cWidth = height; var cOff = (width/2)-(cWidth/2); drawCircle(left-cOff,top,cWidth,color); drawCircle(left+cOff,top,cWidth,color); drawSquare(left,top,cOff*2,height,0,color); } function flowProcess(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawSquare(left,top,width,height,0,strokeColor); drawSquare(left,top,width-sOff,height-sOff,0,color); } function flowDecision(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawDiamond(left,top,width,height,strokeColor); drawDiamond(left,top,width-sOff,height-(sOff*1.8),color); } function drawVertex(left,top,width,height,style) { var flowStrokeHighColor = 5; var flowStrokeColor = 0; var flowColor = 7; var flowStrokeSize = 2; switch(style){ case 100: // (100 - 199) FLOW CHART SYMBOLS // Terminator, start stop flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); break; case -100: // Terminator, start stop - HIGHLIGHTED flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); break; case 101: // Process, process or action step flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); break; case -101: // Process, process or action step - HIGHLIGHTED flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); break; case 102: // Decision, question or branch flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor) break; case -102: // Decision, question or branch - HIGHLIGHTED flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor) break; case 1: // Smiley Face drawCircle(left,top,width,5); drawCircle(left,top,width*0.7,0); drawCircle(left,top,width*0.5,5); drawSquare(left,top,width*0.7,width*0.2,0,5); drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5); drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5); drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5); drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0); drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0); break; case 2: // Bart Simpson drawSquare(left,top,width*0.9,width*1.1,0,0); drawSquare(left,top,width*0.85,width*1.05,0,5); drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0); drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5); drawCircle(left+width*0.15,top+width*0.45,width*0.6,0); drawCircle(left+width*0.15,top+width*0.45,width*0.545,5); drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5); drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5); drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5); drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0) drawCircle(left+width*0.3,top-width*0.1,width*0.4,0); drawCircle(left+width*0.3,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top+width*0.1,width*0.2,0); drawCircle(left+width*0.3,top+width*0.1,width*0.15,5); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5); drawCircle(left+width*0.05,top-width*0.1,width*0.4,0); drawCircle(left+width*0.05,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top-width*0.1,width*0.05,0); drawCircle(left+width*0.05,top-width*0.1,width*0.05,0); break; case -10: drawCircleDim(left,top,width,height,6); break; default: // Default vertex style: black circle drawCircleDim(left,top,width,height,0); } } function drawGraph(vertices,edges) { setupGL(); var numEdgeOpt = 5; var numVertOpt = 5; var edgesArray=edges.split(","); for(var i=0;i<edgesArray.length-numEdgeOpt;i+=numEdgeOpt) { var left1 = parseInt(edgesArray[i]); var top1 = parseInt(edgesArray[i+1]); var left2 = parseInt(edgesArray[i+2]); var top2 = parseInt(edgesArray[i+3]); var style = parseInt(edgesArray[i+4]); drawEdge( left1,top1,left2,top2,style); } var verticesArray=vertices.split(","); for(var i=0;i<verticesArray.length-numVertOpt;i+=numVertOpt) { var left = parseInt(verticesArray[i]); var top = parseInt(verticesArray[i+1]); var width = parseInt(verticesArray[i+2]); var height = parseInt(verticesArray[i+3]); var style = parseInt(verticesArray[i+4]); drawVertex(left,top,width,height,style); } } drawGraph(verticesString,edgesString) }-*/; private static native int webglCheck()/*-{ if (typeof Float32Array != "undefined")return 1; return 0; }-*/; public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { // Do a (kind of reliable) check for webgl if (webglCheck() == 1) { // Can do WebGL // At the moment coordinates are passed to JavaScript as comma // separated strings // This will most probably change in the // future. String edgesString = ""; String veticesString = ""; String separator = ","; int vertexStyle; int edgeStyle; for (EdgeDrawable thisEdge : edges) { double startX = (thisEdge.getStartX() + offsetX)*zoom; double startY = (thisEdge.getStartY() + offsetY)*zoom; double endX = (thisEdge.getEndX() + offsetX)*zoom; double endY = (thisEdge.getEndY() + offsetY)*zoom; //edgeStyle = thisEdge.getStyle(); edgeStyle = 100; if(thisEdge.isHilighted())edgeStyle = -100; edgesString += startX + separator + startY + separator + endX + separator + endY + separator + edgeStyle + separator; } for (VertexDrawable thisVertex : vertices) { double centreX = (thisVertex.getCenterX() + offsetX)*zoom; double centreY = (thisVertex.getCenterY() + offsetY)*zoom; double width = (0.5 * thisVertex.getWidth())*zoom; double height = (0.5 * thisVertex.getWidth())*zoom; //vertexStyle = thisVertex.getStyle(); vertexStyle = 100; if(thisVertex.isHilighted())vertexStyle = -100; veticesString += centreX + separator + centreY + separator + width + separator+ height + separator + vertexStyle + separator; } // JSNI method used to draw webGL graph version drawGraph3D(veticesString, edgesString); } else { // Cant do webGL so draw on 2d Canvas renderGraph2d(canvas, edges, vertices); } } public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { canvas.setLineWidth(1); canvas.setStrokeStyle(Color.BLACK); canvas.setFillStyle(Color.BLACK); canvas.setFillStyle(Color.WHITE); canvas.fillRect(0, 0, 2000, 2000); canvas.setFillStyle(Color.BLACK); drawGraph(edges, vertices, canvas); } // Draws a single vertex, currently only draws circular nodes private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) { double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom; double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom; double radius = (0.5 * vertex.getWidth()) * zoom; canvas.moveTo(centreX, centreY); canvas.beginPath(); canvas.arc(centreX, centreY, radius, 0, 360, false); canvas.closePath(); canvas.stroke(); canvas.fill(); } // Draws a line from coordinates to other coordinates private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) { double startX = (edge.getStartX() + offsetX)*zoom; double startY = (edge.getStartY() + offsetY)*zoom; double endX = (edge.getEndX() + offsetX)*zoom; double endY = (edge.getEndY() + offsetY)*zoom; canvas.beginPath(); canvas.moveTo(startX, startY); canvas.lineTo(endX, endY); canvas.closePath(); canvas.stroke(); } // Takes collections of edges and vertices and draws a graph on a specified // canvas. private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices, GWTCanvas canvas) { for (EdgeDrawable thisEdge : edges) { drawEdge(thisEdge, canvas); } for (VertexDrawable thisVertex : vertices) { drawVertex(thisVertex, canvas); } } // set offset in the event of a pan public void setOffset(int x, int y) { offsetX = x; offsetY = y; } // getters for offsets public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } //set zoom public void setZoom(double z) { zoom = z; } public double getZoom(){ return zoom; } }
src/uk/me/graphe/client/DrawingImpl.java
package uk.me.graphe.client; import java.util.Collection; import com.google.gwt.widgetideas.graphics.client.Color; import com.google.gwt.widgetideas.graphics.client.GWTCanvas; public class DrawingImpl implements Drawing { //used for panning public int offsetX, offsetY; public double zoom; // JSNI method for webgl, comments omitted because it is one big comment... private static native void drawGraph3D(String verticesString, String edgesString) /*-{ var circleCoords = new Array(1000); for(i=0;i<circleCoords.length;i++)circleCoords[i] = new Array(1000); var gl; var shaderProgram; var mvMatrix; var mvMatrixStack = []; var colors = [[0.0, 0.0, 0.0], // BLACK 0 [1.0, 1.0, 1.0], // WHITE 1 [1.0, 0.0, 0.0], // RED 2 [0.0, 1.0, 0.0], // GREEN 3 [0.0, 0.0, 1.0], // BLUE 4 [1.0, 1.0, 0.0], // YELLOW 5 [1.0, 0.317, 1.0], // PINK 6 [0.5, 0.5, 0.5], // GREY 7 ]; // Sylvester.js Libary eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('9 17={3i:\'0.1.3\',16:1e-6};l v(){}v.23={e:l(i){8(i<1||i>7.4.q)?w:7.4[i-1]},2R:l(){8 7.4.q},1u:l(){8 F.1x(7.2u(7))},24:l(a){9 n=7.4.q;9 V=a.4||a;o(n!=V.q){8 1L}J{o(F.13(7.4[n-1]-V[n-1])>17.16){8 1L}}H(--n);8 2x},1q:l(){8 v.u(7.4)},1b:l(a){9 b=[];7.28(l(x,i){b.19(a(x,i))});8 v.u(b)},28:l(a){9 n=7.4.q,k=n,i;J{i=k-n;a(7.4[i],i+1)}H(--n)},2q:l(){9 r=7.1u();o(r===0){8 7.1q()}8 7.1b(l(x){8 x/r})},1C:l(a){9 V=a.4||a;9 n=7.4.q,k=n,i;o(n!=V.q){8 w}9 b=0,1D=0,1F=0;7.28(l(x,i){b+=x*V[i-1];1D+=x*x;1F+=V[i-1]*V[i-1]});1D=F.1x(1D);1F=F.1x(1F);o(1D*1F===0){8 w}9 c=b/(1D*1F);o(c<-1){c=-1}o(c>1){c=1}8 F.37(c)},1m:l(a){9 b=7.1C(a);8(b===w)?w:(b<=17.16)},34:l(a){9 b=7.1C(a);8(b===w)?w:(F.13(b-F.1A)<=17.16)},2k:l(a){9 b=7.2u(a);8(b===w)?w:(F.13(b)<=17.16)},2j:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x+V[i-1]})},2C:l(a){9 V=a.4||a;o(7.4.q!=V.q){8 w}8 7.1b(l(x,i){8 x-V[i-1]})},22:l(k){8 7.1b(l(x){8 x*k})},x:l(k){8 7.22(k)},2u:l(a){9 V=a.4||a;9 i,2g=0,n=7.4.q;o(n!=V.q){8 w}J{2g+=7.4[n-1]*V[n-1]}H(--n);8 2g},2f:l(a){9 B=a.4||a;o(7.4.q!=3||B.q!=3){8 w}9 A=7.4;8 v.u([(A[1]*B[2])-(A[2]*B[1]),(A[2]*B[0])-(A[0]*B[2]),(A[0]*B[1])-(A[1]*B[0])])},2A:l(){9 m=0,n=7.4.q,k=n,i;J{i=k-n;o(F.13(7.4[i])>F.13(m)){m=7.4[i]}}H(--n);8 m},2Z:l(x){9 a=w,n=7.4.q,k=n,i;J{i=k-n;o(a===w&&7.4[i]==x){a=i+1}}H(--n);8 a},3g:l(){8 S.2X(7.4)},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(y){8(F.13(y-x)<=17.16)?x:y})},1o:l(a){o(a.K){8 a.1o(7)}9 V=a.4||a;o(V.q!=7.4.q){8 w}9 b=0,2b;7.28(l(x,i){2b=x-V[i-1];b+=2b*2b});8 F.1x(b)},3a:l(a){8 a.1h(7)},2T:l(a){8 a.1h(7)},1V:l(t,a){9 V,R,x,y,z;2S(7.4.q){27 2:V=a.4||a;o(V.q!=2){8 w}R=S.1R(t).4;x=7.4[0]-V[0];y=7.4[1]-V[1];8 v.u([V[0]+R[0][0]*x+R[0][1]*y,V[1]+R[1][0]*x+R[1][1]*y]);1I;27 3:o(!a.U){8 w}9 C=a.1r(7).4;R=S.1R(t,a.U).4;x=7.4[0]-C[0];y=7.4[1]-C[1];z=7.4[2]-C[2];8 v.u([C[0]+R[0][0]*x+R[0][1]*y+R[0][2]*z,C[1]+R[1][0]*x+R[1][1]*y+R[1][2]*z,C[2]+R[2][0]*x+R[2][1]*y+R[2][2]*z]);1I;2P:8 w}},1t:l(a){o(a.K){9 P=7.4.2O();9 C=a.1r(P).4;8 v.u([C[0]+(C[0]-P[0]),C[1]+(C[1]-P[1]),C[2]+(C[2]-(P[2]||0))])}1d{9 Q=a.4||a;o(7.4.q!=Q.q){8 w}8 7.1b(l(x,i){8 Q[i-1]+(Q[i-1]-x)})}},1N:l(){9 V=7.1q();2S(V.4.q){27 3:1I;27 2:V.4.19(0);1I;2P:8 w}8 V},2n:l(){8\'[\'+7.4.2K(\', \')+\']\'},26:l(a){7.4=(a.4||a).2O();8 7}};v.u=l(a){9 V=25 v();8 V.26(a)};v.i=v.u([1,0,0]);v.j=v.u([0,1,0]);v.k=v.u([0,0,1]);v.2J=l(n){9 a=[];J{a.19(F.2F())}H(--n);8 v.u(a)};v.1j=l(n){9 a=[];J{a.19(0)}H(--n);8 v.u(a)};l S(){}S.23={e:l(i,j){o(i<1||i>7.4.q||j<1||j>7.4[0].q){8 w}8 7.4[i-1][j-1]},33:l(i){o(i>7.4.q){8 w}8 v.u(7.4[i-1])},2E:l(j){o(j>7.4[0].q){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][j-1])}H(--n);8 v.u(a)},2R:l(){8{2D:7.4.q,1p:7.4[0].q}},2D:l(){8 7.4.q},1p:l(){8 7.4[0].q},24:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(7.4.q!=M.q||7.4[0].q!=M[0].q){8 1L}9 b=7.4.q,15=b,i,G,10=7.4[0].q,j;J{i=15-b;G=10;J{j=10-G;o(F.13(7.4[i][j]-M[i][j])>17.16){8 1L}}H(--G)}H(--b);8 2x},1q:l(){8 S.u(7.4)},1b:l(a){9 b=[],12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;b[i]=[];J{j=10-G;b[i][j]=a(7.4[i][j],i+1,j+1)}H(--G)}H(--12);8 S.u(b)},2i:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4.q==M.q&&7.4[0].q==M[0].q)},2j:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x+M[i-1][j-1]})},2C:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2i(M)){8 w}8 7.1b(l(x,i,j){8 x-M[i-1][j-1]})},2B:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}8(7.4[0].q==M.q)},22:l(a){o(!a.4){8 7.1b(l(x){8 x*a})}9 b=a.1u?2x:1L;9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}o(!7.2B(M)){8 w}9 d=7.4.q,15=d,i,G,10=M[0].q,j;9 e=7.4[0].q,4=[],21,20,c;J{i=15-d;4[i]=[];G=10;J{j=10-G;21=0;20=e;J{c=e-20;21+=7.4[i][c]*M[c][j]}H(--20);4[i][j]=21}H(--G)}H(--d);9 M=S.u(4);8 b?M.2E(1):M},x:l(a){8 7.22(a)},32:l(a,b,c,d){9 e=[],12=c,i,G,j;9 f=7.4.q,1p=7.4[0].q;J{i=c-12;e[i]=[];G=d;J{j=d-G;e[i][j]=7.4[(a+i-1)%f][(b+j-1)%1p]}H(--G)}H(--12);8 S.u(e)},31:l(){9 a=7.4.q,1p=7.4[0].q;9 b=[],12=1p,i,G,j;J{i=1p-12;b[i]=[];G=a;J{j=a-G;b[i][j]=7.4[j][i]}H(--G)}H(--12);8 S.u(b)},1y:l(){8(7.4.q==7.4[0].q)},2A:l(){9 m=0,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(F.13(7.4[i][j])>F.13(m)){m=7.4[i][j]}}H(--G)}H(--12);8 m},2Z:l(x){9 a=w,12=7.4.q,15=12,i,G,10=7.4[0].q,j;J{i=15-12;G=10;J{j=10-G;o(7.4[i][j]==x){8{i:i+1,j:j+1}}}H(--G)}H(--12);8 w},30:l(){o(!7.1y){8 w}9 a=[],n=7.4.q,k=n,i;J{i=k-n;a.19(7.4[i][i])}H(--n);8 v.u(a)},1K:l(){9 M=7.1q(),1c;9 n=7.4.q,k=n,i,1s,1n=7.4[0].q,p;J{i=k-n;o(M.4[i][i]==0){2e(j=i+1;j<k;j++){o(M.4[j][i]!=0){1c=[];1s=1n;J{p=1n-1s;1c.19(M.4[i][p]+M.4[j][p])}H(--1s);M.4[i]=1c;1I}}}o(M.4[i][i]!=0){2e(j=i+1;j<k;j++){9 a=M.4[j][i]/M.4[i][i];1c=[];1s=1n;J{p=1n-1s;1c.19(p<=i?0:M.4[j][p]-M.4[i][p]*a)}H(--1s);M.4[j]=1c}}}H(--n);8 M},3h:l(){8 7.1K()},2z:l(){o(!7.1y()){8 w}9 M=7.1K();9 a=M.4[0][0],n=M.4.q-1,k=n,i;J{i=k-n+1;a=a*M.4[i][i]}H(--n);8 a},3f:l(){8 7.2z()},2y:l(){8(7.1y()&&7.2z()===0)},2Y:l(){o(!7.1y()){8 w}9 a=7.4[0][0],n=7.4.q-1,k=n,i;J{i=k-n+1;a+=7.4[i][i]}H(--n);8 a},3e:l(){8 7.2Y()},1Y:l(){9 M=7.1K(),1Y=0;9 a=7.4.q,15=a,i,G,10=7.4[0].q,j;J{i=15-a;G=10;J{j=10-G;o(F.13(M.4[i][j])>17.16){1Y++;1I}}H(--G)}H(--a);8 1Y},3d:l(){8 7.1Y()},2W:l(a){9 M=a.4||a;o(1g(M[0][0])==\'1f\'){M=S.u(M).4}9 T=7.1q(),1p=T.4[0].q;9 b=T.4.q,15=b,i,G,10=M[0].q,j;o(b!=M.q){8 w}J{i=15-b;G=10;J{j=10-G;T.4[i][1p+j]=M[i][j]}H(--G)}H(--b);8 T},2w:l(){o(!7.1y()||7.2y()){8 w}9 a=7.4.q,15=a,i,j;9 M=7.2W(S.I(a)).1K();9 b,1n=M.4[0].q,p,1c,2v;9 c=[],2c;J{i=a-1;1c=[];b=1n;c[i]=[];2v=M.4[i][i];J{p=1n-b;2c=M.4[i][p]/2v;1c.19(2c);o(p>=15){c[i].19(2c)}}H(--b);M.4[i]=1c;2e(j=0;j<i;j++){1c=[];b=1n;J{p=1n-b;1c.19(M.4[j][p]-M.4[i][p]*M.4[j][i])}H(--b);M.4[j]=1c}}H(--a);8 S.u(c)},3c:l(){8 7.2w()},2d:l(){8 7.1b(l(x){8 F.2d(x)})},2V:l(x){8 7.1b(l(p){8(F.13(p-x)<=17.16)?x:p})},2n:l(){9 a=[];9 n=7.4.q,k=n,i;J{i=k-n;a.19(v.u(7.4[i]).2n())}H(--n);8 a.2K(\'\\n\')},26:l(a){9 i,4=a.4||a;o(1g(4[0][0])!=\'1f\'){9 b=4.q,15=b,G,10,j;7.4=[];J{i=15-b;G=4[i].q;10=G;7.4[i]=[];J{j=10-G;7.4[i][j]=4[i][j]}H(--G)}H(--b);8 7}9 n=4.q,k=n;7.4=[];J{i=k-n;7.4.19([4[i]])}H(--n);8 7}};S.u=l(a){9 M=25 S();8 M.26(a)};S.I=l(n){9 a=[],k=n,i,G,j;J{i=k-n;a[i]=[];G=k;J{j=k-G;a[i][j]=(i==j)?1:0}H(--G)}H(--n);8 S.u(a)};S.2X=l(a){9 n=a.q,k=n,i;9 M=S.I(n);J{i=k-n;M.4[i][i]=a[i]}H(--n);8 M};S.1R=l(b,a){o(!a){8 S.u([[F.1H(b),-F.1G(b)],[F.1G(b),F.1H(b)]])}9 d=a.1q();o(d.4.q!=3){8 w}9 e=d.1u();9 x=d.4[0]/e,y=d.4[1]/e,z=d.4[2]/e;9 s=F.1G(b),c=F.1H(b),t=1-c;8 S.u([[t*x*x+c,t*x*y-s*z,t*x*z+s*y],[t*x*y+s*z,t*y*y+c,t*y*z-s*x],[t*x*z-s*y,t*y*z+s*x,t*z*z+c]])};S.3b=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[1,0,0],[0,c,-s],[0,s,c]])};S.39=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,0,s],[0,1,0],[-s,0,c]])};S.38=l(t){9 c=F.1H(t),s=F.1G(t);8 S.u([[c,-s,0],[s,c,0],[0,0,1]])};S.2J=l(n,m){8 S.1j(n,m).1b(l(){8 F.2F()})};S.1j=l(n,m){9 a=[],12=n,i,G,j;J{i=n-12;a[i]=[];G=m;J{j=m-G;a[i][j]=0}H(--G)}H(--12);8 S.u(a)};l 14(){}14.23={24:l(a){8(7.1m(a)&&7.1h(a.K))},1q:l(){8 14.u(7.K,7.U)},2U:l(a){9 V=a.4||a;8 14.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.U)},1m:l(a){o(a.W){8 a.1m(7)}9 b=7.U.1C(a.U);8(F.13(b)<=17.16||F.13(b-F.1A)<=17.16)},1o:l(a){o(a.W){8 a.1o(7)}o(a.U){o(7.1m(a)){8 7.1o(a.K)}9 N=7.U.2f(a.U).2q().4;9 A=7.K.4,B=a.K.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,D=7.U.4;9 b=P[0]-A[0],2a=P[1]-A[1],29=(P[2]||0)-A[2];9 c=F.1x(b*b+2a*2a+29*29);o(c===0)8 0;9 d=(b*D[0]+2a*D[1]+29*D[2])/c;9 e=1-d*d;8 F.13(c*F.1x(e<0?0:e))}},1h:l(a){9 b=7.1o(a);8(b!==w&&b<=17.16)},2T:l(a){8 a.1h(7)},1v:l(a){o(a.W){8 a.1v(7)}8(!7.1m(a)&&7.1o(a)<=17.16)},1U:l(a){o(a.W){8 a.1U(7)}o(!7.1v(a)){8 w}9 P=7.K.4,X=7.U.4,Q=a.K.4,Y=a.U.4;9 b=X[0],1z=X[1],1B=X[2],1T=Y[0],1S=Y[1],1M=Y[2];9 c=P[0]-Q[0],2s=P[1]-Q[1],2r=P[2]-Q[2];9 d=-b*c-1z*2s-1B*2r;9 e=1T*c+1S*2s+1M*2r;9 f=b*b+1z*1z+1B*1B;9 g=1T*1T+1S*1S+1M*1M;9 h=b*1T+1z*1S+1B*1M;9 k=(d*g/f+h*e)/(g-h*h);8 v.u([P[0]+k*b,P[1]+k*1z,P[2]+k*1B])},1r:l(a){o(a.U){o(7.1v(a)){8 7.1U(a)}o(7.1m(a)){8 w}9 D=7.U.4,E=a.U.4;9 b=D[0],1l=D[1],1k=D[2],1P=E[0],1O=E[1],1Q=E[2];9 x=(1k*1P-b*1Q),y=(b*1O-1l*1P),z=(1l*1Q-1k*1O);9 N=v.u([x*1Q-y*1O,y*1P-z*1Q,z*1O-x*1P]);9 P=11.u(a.K,N);8 P.1U(7)}1d{9 P=a.4||a;o(7.1h(P)){8 v.u(P)}9 A=7.K.4,D=7.U.4;9 b=D[0],1l=D[1],1k=D[2],1w=A[0],18=A[1],1a=A[2];9 x=b*(P[1]-18)-1l*(P[0]-1w),y=1l*((P[2]||0)-1a)-1k*(P[1]-18),z=1k*(P[0]-1w)-b*((P[2]||0)-1a);9 V=v.u([1l*x-1k*z,1k*y-b*x,b*z-1l*y]);9 k=7.1o(P)/V.1u();8 v.u([P[0]+V.4[0]*k,P[1]+V.4[1]*k,(P[2]||0)+V.4[2]*k])}},1V:l(t,a){o(1g(a.U)==\'1f\'){a=14.u(a.1N(),v.k)}9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,D=7.U.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 14.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*D[0]+R[0][1]*D[1]+R[0][2]*D[2],R[1][0]*D[0]+R[1][1]*D[1]+R[1][2]*D[2],R[2][0]*D[0]+R[2][1]*D[1]+R[2][2]*D[2]])},1t:l(a){o(a.W){9 A=7.K.4,D=7.U.4;9 b=A[0],18=A[1],1a=A[2],2N=D[0],1l=D[1],1k=D[2];9 c=7.K.1t(a).4;9 d=b+2N,2h=18+1l,2o=1a+1k;9 Q=a.1r([d,2h,2o]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2h)-c[1],Q[2]+(Q[2]-2o)-c[2]];8 14.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 14.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.U)}},1Z:l(a,b){a=v.u(a);b=v.u(b);o(a.4.q==2){a.4.19(0)}o(b.4.q==2){b.4.19(0)}o(a.4.q>3||b.4.q>3){8 w}9 c=b.1u();o(c===0){8 w}7.K=a;7.U=v.u([b.4[0]/c,b.4[1]/c,b.4[2]/c]);8 7}};14.u=l(a,b){9 L=25 14();8 L.1Z(a,b)};14.X=14.u(v.1j(3),v.i);14.Y=14.u(v.1j(3),v.j);14.Z=14.u(v.1j(3),v.k);l 11(){}11.23={24:l(a){8(7.1h(a.K)&&7.1m(a))},1q:l(){8 11.u(7.K,7.W)},2U:l(a){9 V=a.4||a;8 11.u([7.K.4[0]+V[0],7.K.4[1]+V[1],7.K.4[2]+(V[2]||0)],7.W)},1m:l(a){9 b;o(a.W){b=7.W.1C(a.W);8(F.13(b)<=17.16||F.13(F.1A-b)<=17.16)}1d o(a.U){8 7.W.2k(a.U)}8 w},2k:l(a){9 b=7.W.1C(a.W);8(F.13(F.1A/2-b)<=17.16)},1o:l(a){o(7.1v(a)||7.1h(a)){8 0}o(a.K){9 A=7.K.4,B=a.K.4,N=7.W.4;8 F.13((A[0]-B[0])*N[0]+(A[1]-B[1])*N[1]+(A[2]-B[2])*N[2])}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;8 F.13((A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2])}},1h:l(a){o(a.W){8 w}o(a.U){8(7.1h(a.K)&&7.1h(a.K.2j(a.U)))}1d{9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=F.13(N[0]*(A[0]-P[0])+N[1]*(A[1]-P[1])+N[2]*(A[2]-(P[2]||0)));8(b<=17.16)}},1v:l(a){o(1g(a.U)==\'1f\'&&1g(a.W)==\'1f\'){8 w}8!7.1m(a)},1U:l(a){o(!7.1v(a)){8 w}o(a.U){9 A=a.K.4,D=a.U.4,P=7.K.4,N=7.W.4;9 b=(N[0]*(P[0]-A[0])+N[1]*(P[1]-A[1])+N[2]*(P[2]-A[2]))/(N[0]*D[0]+N[1]*D[1]+N[2]*D[2]);8 v.u([A[0]+D[0]*b,A[1]+D[1]*b,A[2]+D[2]*b])}1d o(a.W){9 c=7.W.2f(a.W).2q();9 N=7.W.4,A=7.K.4,O=a.W.4,B=a.K.4;9 d=S.1j(2,2),i=0;H(d.2y()){i++;d=S.u([[N[i%3],N[(i+1)%3]],[O[i%3],O[(i+1)%3]]])}9 e=d.2w().4;9 x=N[0]*A[0]+N[1]*A[1]+N[2]*A[2];9 y=O[0]*B[0]+O[1]*B[1]+O[2]*B[2];9 f=[e[0][0]*x+e[0][1]*y,e[1][0]*x+e[1][1]*y];9 g=[];2e(9 j=1;j<=3;j++){g.19((i==j)?0:f[(j+(5-i)%3)%3])}8 14.u(g,c)}},1r:l(a){9 P=a.4||a;9 A=7.K.4,N=7.W.4;9 b=(A[0]-P[0])*N[0]+(A[1]-P[1])*N[1]+(A[2]-(P[2]||0))*N[2];8 v.u([P[0]+N[0]*b,P[1]+N[1]*b,(P[2]||0)+N[2]*b])},1V:l(t,a){9 R=S.1R(t,a.U).4;9 C=a.1r(7.K).4;9 A=7.K.4,N=7.W.4;9 b=C[0],1E=C[1],1J=C[2],1w=A[0],18=A[1],1a=A[2];9 x=1w-b,y=18-1E,z=1a-1J;8 11.u([b+R[0][0]*x+R[0][1]*y+R[0][2]*z,1E+R[1][0]*x+R[1][1]*y+R[1][2]*z,1J+R[2][0]*x+R[2][1]*y+R[2][2]*z],[R[0][0]*N[0]+R[0][1]*N[1]+R[0][2]*N[2],R[1][0]*N[0]+R[1][1]*N[1]+R[1][2]*N[2],R[2][0]*N[0]+R[2][1]*N[1]+R[2][2]*N[2]])},1t:l(a){o(a.W){9 A=7.K.4,N=7.W.4;9 b=A[0],18=A[1],1a=A[2],2M=N[0],2L=N[1],2Q=N[2];9 c=7.K.1t(a).4;9 d=b+2M,2p=18+2L,2m=1a+2Q;9 Q=a.1r([d,2p,2m]).4;9 e=[Q[0]+(Q[0]-d)-c[0],Q[1]+(Q[1]-2p)-c[1],Q[2]+(Q[2]-2m)-c[2]];8 11.u(c,e)}1d o(a.U){8 7.1V(F.1A,a)}1d{9 P=a.4||a;8 11.u(7.K.1t([P[0],P[1],(P[2]||0)]),7.W)}},1Z:l(a,b,c){a=v.u(a);a=a.1N();o(a===w){8 w}b=v.u(b);b=b.1N();o(b===w){8 w}o(1g(c)==\'1f\'){c=w}1d{c=v.u(c);c=c.1N();o(c===w){8 w}}9 d=a.4[0],18=a.4[1],1a=a.4[2];9 e=b.4[0],1W=b.4[1],1X=b.4[2];9 f,1i;o(c!==w){9 g=c.4[0],2l=c.4[1],2t=c.4[2];f=v.u([(1W-18)*(2t-1a)-(1X-1a)*(2l-18),(1X-1a)*(g-d)-(e-d)*(2t-1a),(e-d)*(2l-18)-(1W-18)*(g-d)]);1i=f.1u();o(1i===0){8 w}f=v.u([f.4[0]/1i,f.4[1]/1i,f.4[2]/1i])}1d{1i=F.1x(e*e+1W*1W+1X*1X);o(1i===0){8 w}f=v.u([b.4[0]/1i,b.4[1]/1i,b.4[2]/1i])}7.K=a;7.W=f;8 7}};11.u=l(a,b,c){9 P=25 11();8 P.1Z(a,b,c)};11.2I=11.u(v.1j(3),v.k);11.2H=11.u(v.1j(3),v.i);11.2G=11.u(v.1j(3),v.j);11.36=11.2I;11.35=11.2H;11.3j=11.2G;9 $V=v.u;9 $M=S.u;9 $L=14.u;9 $P=11.u;',62,206,'||||elements|||this|return|var||||||||||||function|||if||length||||create|Vector|null|||||||||Math|nj|while||do|anchor||||||||Matrix||direction||normal||||kj|Plane|ni|abs|Line|ki|precision|Sylvester|A2|push|A3|map|els|else||undefined|typeof|contains|mod|Zero|D3|D2|isParallelTo|kp|distanceFrom|cols|dup|pointClosestTo|np|reflectionIn|modulus|intersects|A1|sqrt|isSquare|X2|PI|X3|angleFrom|mod1|C2|mod2|sin|cos|break|C3|toRightTriangular|false|Y3|to3D|E2|E1|E3|Rotation|Y2|Y1|intersectionWith|rotate|v12|v13|rank|setVectors|nc|sum|multiply|prototype|eql|new|setElements|case|each|PA3|PA2|part|new_element|round|for|cross|product|AD2|isSameSizeAs|add|isPerpendicularTo|v22|AN3|inspect|AD3|AN2|toUnitVector|PsubQ3|PsubQ2|v23|dot|divisor|inverse|true|isSingular|determinant|max|canMultiplyFromLeft|subtract|rows|col|random|ZX|YZ|XY|Random|join|N2|N1|D1|slice|default|N3|dimensions|switch|liesIn|translate|snapTo|augment|Diagonal|trace|indexOf|diagonal|transpose|minor|row|isAntiparallelTo|ZY|YX|acos|RotationZ|RotationY|liesOn|RotationX|inv|rk|tr|det|toDiagonalMatrix|toUpperTriangular|version|XZ'.split('|'),0,{})) // gtUtils.js Libary Matrix.Translation = function (v) { if (v.elements.length == 2) { var r = Matrix.I(3); r.elements[2][0] = v.elements[0]; r.elements[2][1] = v.elements[1]; return r; } if (v.elements.length == 3) { var r = Matrix.I(4); r.elements[0][3] = v.elements[0]; r.elements[1][3] = v.elements[1]; r.elements[2][3] = v.elements[2]; return r; } throw "Invalid length for Translation"; } Matrix.prototype.flatten = function () { var result = []; if (this.elements.length == 0) return []; for (var j = 0; j < this.elements[0].length; j++) for (var i = 0; i < this.elements.length; i++) result.push(this.elements[i][j]); return result; } Matrix.prototype.ensure4x4 = function() { if (this.elements.length == 4 && this.elements[0].length == 4) return this; if (this.elements.length > 4 || this.elements[0].length > 4) return null; for (var i = 0; i < this.elements.length; i++) { for (var j = this.elements[i].length; j < 4; j++) { if (i == j) this.elements[i].push(1); else this.elements[i].push(0); } } for (var i = this.elements.length; i < 4; i++) { if (i == 0) this.elements.push([1, 0, 0, 0]); else if (i == 1) this.elements.push([0, 1, 0, 0]); else if (i == 2) this.elements.push([0, 0, 1, 0]); else if (i == 3) this.elements.push([0, 0, 0, 1]); } return this; }; Matrix.prototype.make3x3 = function() { if (this.elements.length != 4 || this.elements[0].length != 4) return null; return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], [this.elements[1][0], this.elements[1][1], this.elements[1][2]], [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); }; Vector.prototype.flatten = function () { return this.elements; }; function mht(m) { var s = ""; if (m.length == 16) { for (var i = 0; i < 4; i++) { s += "<span style='font-family: monospace'>[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]</span><br>"; } } else if (m.length == 9) { for (var i = 0; i < 3; i++) { s += "<span style='font-family: monospace'>[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]</font><br>"; } } else { return m.toString(); } return s; } function makeLookAt(ex, ey, ez, cx, cy, cz, ux, uy, uz) { var eye = $V([ex, ey, ez]); var center = $V([cx, cy, cz]); var up = $V([ux, uy, uz]); var mag; var z = eye.subtract(center).toUnitVector(); var x = up.cross(z).toUnitVector(); var y = z.cross(x).toUnitVector(); var m = $M([[x.e(1), x.e(2), x.e(3), 0], [y.e(1), y.e(2), y.e(3), 0], [z.e(1), z.e(2), z.e(3), 0], [0, 0, 0, 1]]); var t = $M([[1, 0, 0, -ex], [0, 1, 0, -ey], [0, 0, 1, -ez], [0, 0, 0, 1]]); return m.x(t); } function makePerspective(fovy, aspect, znear, zfar) { var ymax = znear * Math.tan(fovy * Math.PI / 360.0); var ymin = -ymax; var xmin = ymin * aspect; var xmax = ymax * aspect; return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); } function makeFrustum(left, right, bottom, top, znear, zfar) { var X = 2*znear/(right-left); var Y = 2*znear/(top-bottom); var A = (right+left)/(right-left); var B = (top+bottom)/(top-bottom); var C = -(zfar+znear)/(zfar-znear); var D = -2*zfar*znear/(zfar-znear); return $M([[X, 0, A, 0], [0, Y, B, 0], [0, 0, C, D], [0, 0, -1, 0]]); } function makeOrtho(left, right, bottom, top, znear, zfar) { var tx = - (right + left) / (right - left); var ty = - (top + bottom) / (top - bottom); var tz = - (zfar + znear) / (zfar - znear); return $M([[2 / (right - left), 0, 0, tx], [0, 2 / (top - bottom), 0, ty], [0, 0, -2 / (zfar - znear), tz], [0, 0, 0, 1]]); } // End of Libaries function initGL(canvas) { try { gl = canvas.getContext("experimental-webgl"); gl.viewportWidth = canvas.width; gl.viewportHeight = canvas.height; } catch(e) { } if (!gl) { alert("Could not initialise WebGL"); } } function getShader(gl, id) { var shaderScript = document.getElementById(id); if (!shaderScript) { return null; } var str = ""; var k = shaderScript.firstChild; while (k) { if (k.nodeType == 3) { str += k.textContent; } k = k.nextSibling; } var shader; if (shaderScript.type == "x-shader/x-fragment") { shader = gl.createShader(gl.FRAGMENT_SHADER); } else if (shaderScript.type == "x-shader/x-vertex") { shader = gl.createShader(gl.VERTEX_SHADER); } else { return null; } gl.shaderSource(shader, str); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { alert(gl.getShaderInfoLog(shader)); return null; } return shader; } function initShaders() { var fragmentShader = getShader(gl, "shader-fs"); var vertexShader = getShader(gl, "shader-vs"); shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert("Could not initialise shaders"); } gl.useProgram(shaderProgram); shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition"); gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute); shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor"); gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute); shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix"); shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix"); } function mvPushMatrix(m) { if (m) { mvMatrixStack.push(m.dup()); mvMatrix = m.dup(); } else { mvMatrixStack.push(mvMatrix.dup()); } } function mvPopMatrix() { if (mvMatrixStack.length == 0) { throw "Invalid popMatrix!"; } mvMatrix = mvMatrixStack.pop(); return mvMatrix; } function loadIdentity() { mvMatrix = Matrix.I(4); } function multMatrix(m) { mvMatrix = mvMatrix.x(m); } function mvTranslate(v) { var m = Matrix.Translation($V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } function mvRotate(ang, v) { var arad = ang * Math.PI / 180.0; var m = Matrix.Rotation(arad, $V([v[0], v[1], v[2]])).ensure4x4(); multMatrix(m); } var pMatrix; function perspective(fovy, aspect, znear, zfar) { pMatrix = makePerspective(fovy, aspect, znear, zfar); } function setMatrixUniforms() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, new Float32Array(pMatrix.flatten())); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, new Float32Array(mvMatrix.flatten())); } function compareXValue(array1, array2) { var value1 = array1[0]; var value2 = array2[0]; if (value1 > value2) return 1; if (value1 < value2) return -1; return 0; } function setupShaders(){ var headID = document.getElementsByTagName("head")[0]; var fsScript = document.createElement('script'); fsScript.id="shader-fs"; fsScript.type = 'x-shader/x-fragment'; fsScript.text = "#ifdef GL_ES\n\ precision highp float;\n\ #endif\n\ varying vec4 vColor;\n\ void main(void) {\n\ gl_FragColor = vColor;\n\ }"; var vsScript = document.createElement('script'); vsScript.id="shader-vs"; vsScript.type = 'x-shader/x-vertex'; vsScript.text = "attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ uniform mat4 uMVMatrix;\n\ uniform mat4 uPMatrix;\n\ \n\ varying vec4 vColor;\n\ \n\ void main(void) {\n\ gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);\n\ vColor = aVertexColor;\n\ }"; headID.appendChild(vsScript); headID.appendChild(fsScript); initShaders(); } function setupCanvas(){ canvas1 = document.getElementsByTagName("canvas")[1]; canvas1.style.position = "absolute"; canvas1.style.zIndex = 10; canvas1.style.opacity = 0.5; canvas = document.getElementsByTagName("canvas")[0]; canvas.style.zIndex = 0; initGL(canvas); } function setupGL(){ setupCanvas(); setupShaders(); gl.clearColor(1.0, 1.0, 1.0, 1.0); gl.clearDepth(1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 100.0); loadIdentity(); var uTop = 2.478; var uLeft = -uTop; mvTranslate([uLeft,uTop, -10.0]) mvPushMatrix(); } // Drawing functions function drawPolygon(pixelVertices,colorNum) { var factor; var glWidth = 4.92; var vertices = new Float32Array(1000); var polygonColors = new Float32Array(1000); var vl = 0; if(canvas.width>=canvas.height) factor = glWidth/canvas.height; else factor = glWidth/canvas.width; for(var i=0;i<pixelVertices.length;i++){ pixelVertices[i] = (pixelVertices[i])*factor; if (i%2){ vertices[vl] = -pixelVertices[i]; vl++; vertices[vl] = (4.0); } else { vertices[vl] = (pixelVertices[i]); } vl++; } vertexPositionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW); vertexPositionBuffer.itemSize = 3; vertexPositionBuffer.numItems = vl / 3.0; vertexColorBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); for(var i=0;i<(vl / 3.0)*4;i+=4){ polygonColors[i] = colors[colorNum][0]; polygonColors[i+1] = colors[colorNum][1]; polygonColors[i+2] = colors[colorNum][2]; polygonColors[i+3] = 1.0; } gl.bufferData(gl.ARRAY_BUFFER, polygonColors, gl.STATIC_DRAW); vertexColorBuffer.itemSize = 4; vertexColorBuffer.numItems = vl / 3.0; gl.bindBuffer(gl.ARRAY_BUFFER, vertexPositionBuffer); gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, vertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer); gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, vertexColorBuffer.itemSize, gl.FLOAT, false, 0, 0); setMatrixUniforms(); gl.drawArrays(gl.TRIANGLE_STRIP, 0, vl / 3.0); } function drawLine(left1,top1,left2,top2,width,color) { if(top1 <= top2){ var temp1 = left1; var temp2 = top1; left1 = left2; top1 = top2; left2 = temp1; top2 = temp2; } var length = Math.sqrt(((top2-top1)*(top2-top1))+((left2-left1)*(left2-left1))); var vHeight = top1-top2; var hWidth = left1-left2; var deg = 180/Math.PI; var angle = Math.atan(vHeight/hWidth); var angle2 = ((Math.PI/2)-angle); var height2 = Math.sin(angle2)*(width/2); var width2 = Math.sqrt(((width/2)*(width/2))-(height2*height2)); if(angle*deg<0) { var topRightX = left1-(width2); var topRightY = top1-height2; var topLeftX = left1+(width2); var topLeftY = top1+height2; var bottomRightX = left2-(width2); var bottomRightY = top2-height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2+height2; } else { var topRightX = left1-(width2); var topRightY = top1+height2; var topLeftX = left1+(width2); var topLeftY = top1-height2; var bottomRightX = left2-(width2); var bottomRightY = top2+height2; var bottomLeftX = left2+(width2); var bottomLeftY = top2-height2; } var pvertices = new Float32Array([ topRightX, topRightY, topLeftX, topLeftY, bottomRightX, bottomRightY, bottomLeftX, bottomLeftY ]); drawPolygon(pvertices,color); } function drawSquare(left,top,width,height,rotation,color){drawSquareComplex(left,top,width,height,rotation,height,width,color);} function drawSquareComplex(left,top,width,height,rotation,vHeight,hWidth,color){ var diam = width/2; var topOffset = Math.round(Math.sin(rotation)*diam); var leftOffset = Math.round(Math.cos(rotation)*diam); drawLine(left-leftOffset,top-topOffset,left+leftOffset,top+topOffset,height,color); } function drawDiamond(left,top,width,height,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(8); pvertices[0] = left; pvertices[1] = top-halfHeight; pvertices[2] = left-halfWidth; pvertices[3] = top; pvertices[4] = left+halfWidth; pvertices[5] = top; pvertices[6] = left; pvertices[7] = top+halfHeight; drawPolygon(pvertices,color); } function drawTriang(left,top,width,height,rotation,color) { var halfWidth = width/2; var halfHeight = height/2; var pvertices = new Float32Array(6); pvertices[0] = 0; pvertices[1] = 0-halfHeight; pvertices[2] = 0-halfWidth; pvertices[3] = 0+halfHeight; pvertices[4] = 0+halfWidth; pvertices[5] = 0+halfHeight; var j = 0; for (i=0;i<3;i++) { var tempX = pvertices[j]; var tempY = pvertices[j+1]; pvertices[j] = (Math.cos(rotation)*tempX)-(Math.sin(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+left); j++; pvertices[j] = (Math.sin(rotation)*tempX)+(Math.cos(rotation)*tempY) pvertices[j] = Math.round(pvertices[j]+top); j++; } drawPolygon(pvertices,color); } function drawCircle(left,top,width,color){drawCircleDim(left,top,width,width,color)}; function drawCircleDim(left,top,width,height,color){ left = Math.round(left); top = Math.round(top); width = Math.round(width); height = Math.round(height); var w = Math.round(width/2); var h = Math.round(height/2); var numSections; if(width>height)numSections = width*2; else numSections = height*2; if(numSections>33)numSections = 33; if(numSections<10)numSections = 10; var delta_theta = 2.0 * Math.PI / numSections var theta = 0 if(circleCoords[w][h]==undefined) { //alert("make circle "+r); circleCoords[w][h] = new Array(numSections); circleCoords[w][h] = new Array(numSections); for (i = 0; i < numSections ; i++) { circleCoords[w][h][i] = new Array(2); x = (w * Math.cos(theta)); y = (h * Math.sin(theta)); x = Math.round(x*1000)/1000 y = Math.round(y*1000)/1000 circleCoords[w][h][i][1] = x; circleCoords[w][h][i][0] = y; theta += delta_theta } circleCoords[w][h].sort(compareXValue); for(var i = 0;i<numSections-1;i++) { if(circleCoords[w][h][i][0] == circleCoords[w][h][i+1][0] && circleCoords[w][h][i][1]<circleCoords[w][h][i+1][1]) { temp = circleCoords[w][h][i]; circleCoords[w][h][i] = circleCoords[w][h][i+1]; circleCoords[w][h][i+1] = temp; } } } var j = 0; var pvertices = new Float32Array(numSections*2); for (i=0;i<numSections;i++) { pvertices[j] = circleCoords[w][h][i][1]+left; j++; pvertices[j] = circleCoords[w][h][i][0]+top; j++; } drawPolygon(pvertices,color); } //Styling functions // BLACK 0 // WHITE 1 // RED 2 // GREEN 3 // BLUE 4 // YELLOW 5 // PINK 6 // GREY 7 function drawEdge(left1,top1, left2,top2,style){ switch(style){ case 100: // FLOW CHART // Draw line with Arrow at end drawLine(left1,top1,left2,top2,2,2); //drawTriang(left,top,width,height,Math.PI/2,0); // TO DO: math to work out where arrow goes break; case -10: drawLine(left1,top1,left2,top2,2,6); break; default: //Default edge style: black line drawLine(left1,top1,left2,top2,2,0); } } function flowTerminator(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; flowTerminatorNoStroke(left,top,width,height,strokeColor); flowTerminatorNoStroke(left,top,width-sOff,height-sOff,color); } function flowTerminatorNoStroke(left,top,width,height,color) { var cWidth = height; var cOff = (width/2)-(cWidth/2); drawCircle(left-cOff,top,cWidth,color); drawCircle(left+cOff,top,cWidth,color); drawSquare(left,top,cOff*2,height,0,color); } function flowProcess(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2; drawSquare(left,top,width,height,0,strokeColor); drawSquare(left,top,width-sOff,height-sOff,0,color); } function flowDecision(left,top,width,height,color,strokeSize,strokeColor) { var sOff = strokeSize*2+1; drawDiamond(left,top,width,height,strokeColor); drawDiamond(left,top,width-sOff-1,height-sOff,color); } function drawVertex(left,top,width,height,style) { var flowStrokeHighColor = 5; var flowStrokeColor = 0; var flowColor = 7; var flowStrokeSize = 2; switch(style){ case 100: // (100 - 199) FLOW CHART SYMBOLS // Terminator, start stop flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); break; case -100: // Terminator, start stop - HIGHLIGHTED flowTerminator(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); break; case 101: // Process, process or action step flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor); break; case -101: // Process, process or action step - HIGHLIGHTED flowProcess(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor); break; case 102: // Decision, question or branch flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeColor) break; case -102: // Decision, question or branch - HIGHLIGHTED flowDecision(left,top,width,height,flowColor,flowStrokeSize,flowStrokeHighColor) break; case 1: // Smiley Face drawCircle(left,top,width,5); drawCircle(left,top,width*0.7,0); drawCircle(left,top,width*0.5,5); drawSquare(left,top,width*0.7,width*0.2,0,5); drawSquare(left,top-width*0.1,width*0.70,width*0.2,0,5); drawSquare(left,top-width*0.2,width*0.60,width*0.2,0,5); drawSquare(left,top-width*0.3,width*0.40,width*0.1,0,5); drawCircle(left-(width*0.20),top-(width*0.2),width*0.2,0); drawCircle(left+(width*0.20),top-(width*0.2),width*0.2,0); break; case 2: // Bart Simpson drawSquare(left,top,width*0.9,width*1.1,0,0); drawSquare(left,top,width*0.85,width*1.05,0,5); drawSquare(left-width*0.27,top+width*0.2,width*0.35,width*1.2,0,0); drawSquare(left-width*0.27,top+width*0.2,width*0.31,width*1.16,0,5); drawCircle(left+width*0.15,top+width*0.45,width*0.6,0); drawCircle(left+width*0.15,top+width*0.45,width*0.545,5); drawSquare(left,top+width*0.27,width*0.85,width*0.5,0,5); drawSquare(left-width*0.31,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.31,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left-width*0.06,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left-width*0.06,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.19,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.19,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left+width*0.32,top-width*0.55,width*0.2,width*0.2,(Math.PI/4),0) drawSquare(left+width*0.32,top-width*0.55,width*0.16,width*0.16,(Math.PI/4),5) drawSquare(left,top-width*0.3,width*0.85,width*0.5,0,5); drawSquare(left,top-width*0.23,width*0.85,width*0.5,0,5); drawSquare(left-width*0.15,top+width*0.53,width*0.15,width*0.02,-(Math.PI/5),0) drawCircle(left+width*0.3,top-width*0.1,width*0.4,0); drawCircle(left+width*0.3,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top+width*0.1,width*0.2,0); drawCircle(left+width*0.3,top+width*0.1,width*0.15,5); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.2,0,0); drawSquare(left+width*0.2,top+width*0.1,width*0.2,width*0.15,0,5); drawCircle(left+width*0.05,top-width*0.1,width*0.4,0); drawCircle(left+width*0.05,top-width*0.1,width*0.35,1); drawCircle(left+width*0.3,top-width*0.1,width*0.05,0); drawCircle(left+width*0.05,top-width*0.1,width*0.05,0); break; case -10: drawCircleDim(left,top,width,height,6); break; default: // Default vertex style: black circle drawCircleDim(left,top,width,height,0); } } function drawGraph(vertices,edges) { setupGL(); var numEdgeOpt = 5; var numVertOpt = 5; var edgesArray=edges.split(","); for(var i=0;i<edgesArray.length-numEdgeOpt;i+=numEdgeOpt) { var left1 = parseInt(edgesArray[i]); var top1 = parseInt(edgesArray[i+1]); var left2 = parseInt(edgesArray[i+2]); var top2 = parseInt(edgesArray[i+3]); var style = parseInt(edgesArray[i+4]); drawEdge( left1,top1,left2,top2,style); } var verticesArray=vertices.split(","); for(var i=0;i<verticesArray.length-numVertOpt;i+=numVertOpt) { var left = parseInt(verticesArray[i]); var top = parseInt(verticesArray[i+1]); var width = parseInt(verticesArray[i+2]); var height = parseInt(verticesArray[i+3]); var style = parseInt(verticesArray[i+4]); drawVertex(left,top,width,height,style); } } drawGraph(verticesString,edgesString) }-*/; private static native int webglCheck()/*-{ if (typeof Float32Array != "undefined")return 1; return 0; }-*/; public void renderGraph(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { // Do a (kind of reliable) check for webgl if (webglCheck() == 1) { // Can do WebGL // At the moment coordinates are passed to JavaScript as comma // separated strings // This will most probably change in the // future. String edgesString = ""; String veticesString = ""; String separator = ","; int vertexStyle; int edgeStyle; for (EdgeDrawable thisEdge : edges) { double startX = (thisEdge.getStartX() + offsetX)*zoom; double startY = (thisEdge.getStartY() + offsetY)*zoom; double endX = (thisEdge.getEndX() + offsetX)*zoom; double endY = (thisEdge.getEndY() + offsetY)*zoom; //edgeStyle = thisEdge.getStyle(); edgeStyle = -1; if(thisEdge.isHilighted())edgeStyle = -10; edgesString += startX + separator + startY + separator + endX + separator + endY + separator + edgeStyle + separator; } for (VertexDrawable thisVertex : vertices) { double centreX = (thisVertex.getCenterX() + offsetX)*zoom; double centreY = (thisVertex.getCenterY() + offsetY)*zoom; double width = (0.5 * thisVertex.getWidth())*zoom; double height = (0.5 * thisVertex.getWidth())*zoom; //vertexStyle = thisVertex.getStyle(); vertexStyle = 100; if(thisVertex.isHilighted())vertexStyle = -100; veticesString += centreX + separator + centreY + separator + width + separator+ height + separator + vertexStyle + separator; } // JSNI method used to draw webGL graph version drawGraph3D(veticesString, edgesString); } else { // Cant do webGL so draw on 2d Canvas renderGraph2d(canvas, edges, vertices); } } public void renderGraph2d(GWTCanvas canvas, Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices) { canvas.setLineWidth(1); canvas.setStrokeStyle(Color.BLACK); canvas.setFillStyle(Color.BLACK); canvas.setFillStyle(Color.WHITE); canvas.fillRect(0, 0, 2000, 2000); canvas.setFillStyle(Color.BLACK); drawGraph(edges, vertices, canvas); } // Draws a single vertex, currently only draws circular nodes private void drawVertex(VertexDrawable vertex, GWTCanvas canvas) { double centreX = (vertex.getLeft() + 0.5 * vertex.getWidth() + offsetX) * zoom; double centreY = (vertex.getTop() + 0.5 * vertex.getHeight() + offsetY) * zoom; double radius = (0.5 * vertex.getWidth()) * zoom; canvas.moveTo(centreX, centreY); canvas.beginPath(); canvas.arc(centreX, centreY, radius, 0, 360, false); canvas.closePath(); canvas.stroke(); canvas.fill(); } // Draws a line from coordinates to other coordinates private void drawEdge(EdgeDrawable edge, GWTCanvas canvas) { double startX = (edge.getStartX() + offsetX)*zoom; double startY = (edge.getStartY() + offsetY)*zoom; double endX = (edge.getEndX() + offsetX)*zoom; double endY = (edge.getEndY() + offsetY)*zoom; canvas.beginPath(); canvas.moveTo(startX, startY); canvas.lineTo(endX, endY); canvas.closePath(); canvas.stroke(); } // Takes collections of edges and vertices and draws a graph on a specified // canvas. private void drawGraph(Collection<EdgeDrawable> edges, Collection<VertexDrawable> vertices, GWTCanvas canvas) { for (EdgeDrawable thisEdge : edges) { drawEdge(thisEdge, canvas); } for (VertexDrawable thisVertex : vertices) { drawVertex(thisVertex, canvas); } } // set offset in the event of a pan public void setOffset(int x, int y) { offsetX = x; offsetY = y; } // getters for offsets public int getOffsetX() { return offsetX; } public int getOffsetY() { return offsetY; } //set zoom public void setZoom(double z) { zoom = z; } public double getZoom(){ return zoom; } }
Added arrows to edges. Flow chart styles now ready. Woop, Woop
src/uk/me/graphe/client/DrawingImpl.java
Added arrows to edges. Flow chart styles now ready. Woop, Woop
Java
mit
0783dc33b46a71c2daba04752c94119d7dc21b87
0
xSke/Pxls,xSke/Pxls,xSke/Pxls,xSke/Pxls
package space.pxls.server; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import io.undertow.websockets.core.WebSocketChannel; import space.pxls.App; import space.pxls.data.DBPixelPlacement; import space.pxls.user.Role; import space.pxls.user.User; import space.pxls.util.PxlsTimer; import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; import java.util.Collections; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.lang.Math; import java.time.Instant; public class PacketHandler { private UndertowServer server; private PxlsTimer userData = new PxlsTimer(5); private int numAllCons = 0; public int getCooldown() { // TODO: make these parameters somehow configurable // exponential function of form a*exp(-b*(x - d)) + c double a = -8.04044740e+01; double b = 2.73880499e-03; double c = 9.63956320e+01; double d = -2.14065886e+00; double x = (double)server.getAuthedUsers().size(); return (int)Math.ceil(a*Math.exp(-b*(x - d)) + c); } public PacketHandler(UndertowServer server) { this.server = server; } public void userdata(WebSocketChannel channel, User user) { if (user != null) { server.send(channel, new ServerUserInfo( user.getName(), user.getRole().name().equals("SHADOWBANNED") ? "USER" : user.getRole().name(), user.isBanned(), user.isBanned() ? user.getBanExpiryTime() : 0, user.isBanned() ? user.getBanReason() : "", user.getLogin().split(":")[0] )); } } public void connect(WebSocketChannel channel, User user) { if (user != null) { userdata(channel, user); sendCooldownData(channel, user); sendStackedCount(channel, user); user.flagForCaptcha(); server.addAuthedUser(user); user.setInitialAuthTime(Instant.now().toEpochMilli()); } numAllCons++; updateUserData(); } public void disconnect(WebSocketChannel channel, User user) { if (user != null && user.getConnections().size() == 0) { server.removeAuthedUser(user); } numAllCons--; updateUserData(); } public void accept(WebSocketChannel channel, User user, Object obj, String ip) { if (user != null) { if (obj instanceof ClientPlace) { handlePlace(channel, user, ((ClientPlace) obj), ip); } if (obj instanceof ClientUndo) handleUndo(channel, user, ((ClientUndo) obj)); if (obj instanceof ClientCaptcha) handleCaptcha(channel, user, ((ClientCaptcha) obj)); if (obj instanceof ClientShadowBanMe) handleShadowBanMe(channel, user, ((ClientShadowBanMe) obj)); if (obj instanceof ClientBanMe) handleBanMe(channel, user, ((ClientBanMe) obj)); if (user.getRole().greaterEqual(Role.MODERATOR)) { if (obj instanceof ClientAdminCooldownOverride) handleCooldownOverride(channel, user, ((ClientAdminCooldownOverride) obj)); if (obj instanceof ClientAdminMessage) handleAdminMessage(channel, user, ((ClientAdminMessage) obj)); } } } private void handleAdminMessage(WebSocketChannel channel, User user, ClientAdminMessage obj) { User u = App.getUserManager().getByName(obj.getUsername()); if (u != null) { ServerAlert msg = new ServerAlert(escapeHtml4(obj.getMessage())); for (WebSocketChannel ch : u.getConnections()) { server.send(ch, msg); } } } private void handleShadowBanMe(WebSocketChannel channel, User user, ClientShadowBanMe obj) { if (user.getRole().greaterEqual(Role.USER)) { App.getDatabase().adminLog("self-shadowban via script", user.getId()); user.shadowban("auto-ban via script", 999*24*3600); } } private void handleBanMe(WebSocketChannel channel, User user, ClientBanMe obj) { App.getDatabase().adminLog("self-ban via script", user.getId()); user.ban(86400, "auto-ban via script"); } private void handleCooldownOverride(WebSocketChannel channel, User user, ClientAdminCooldownOverride obj) { user.setOverrideCooldown(obj.getOverride()); sendCooldownData(user); } private void handleUndo(WebSocketChannel channel, User user, ClientUndo cu){ if (!user.canUndoNow()) { return; } if (user.isShadowBanned()) { user.setLastUndoTime(); user.setCooldown(0); sendCooldownData(user); return; } DBPixelPlacement thisPixel = App.getDatabase().getUserUndoPixel(user); DBPixelPlacement recentPixel = App.getDatabase().getPixelAt(thisPixel.x, thisPixel.y); if (thisPixel.id != recentPixel.id) return; if (user.lastPlaceWasStack()) { user.setStacked(Math.min(user.getStacked() + 1, App.getConfig().getInt("stacking.maxStacked"))); sendStackedCount(user); } user.setLastUndoTime(); user.setCooldown(0); DBPixelPlacement lastPixel = App.getDatabase().getPixelByID(thisPixel.secondaryId); if (lastPixel != null) { App.getDatabase().putUserUndoPixel(lastPixel, user, thisPixel.id); App.putPixel(lastPixel.x, lastPixel.y, lastPixel.color, user, false, "(user undo)", false); broadcastPixelUpdate(lastPixel.x, lastPixel.y, lastPixel.color); } else { byte defaultColor = App.getDefaultColor(thisPixel.x, thisPixel.y); App.getDatabase().putUserUndoPixel(thisPixel.x, thisPixel.y, defaultColor, user, thisPixel.id); App.putPixel(thisPixel.x, thisPixel.y, defaultColor, user, false, "(user undo)", false); broadcastPixelUpdate(thisPixel.x, thisPixel.y, defaultColor); } sendCooldownData(user); } private void handlePlace(WebSocketChannel channel, User user, ClientPlace cp, String ip) { if (!cp.getType().equals("pixel")) { handlePlaceMaybe(channel, user, cp, ip); } if (cp.getX() < 0 || cp.getX() >= App.getWidth() || cp.getY() < 0 || cp.getY() >= App.getHeight()) return; if (cp.getColor() < 0 || cp.getColor() >= App.getConfig().getStringList("board.palette").size()) return; if (user.isBanned()) return; if (user.canPlace()) { if (user.updateCaptchaFlagPrePlace() && App.isCaptchaEnabled()) { server.send(channel, new ServerCaptchaRequired()); } else { int c = App.getPixel(cp.getX(), cp.getY()); boolean canPlace = c != cp.getColor() && c != 0xFF && c != -1; int c_old = c; /*if (!canPlace && (c == 0xFF || c == -1)) { // tendril expansion! if (!canPlace && cp.getX() + 1 < App.getWidth()) { c = App.getPixel(cp.getX() + 1, cp.getY()); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getX() - 1 >= 0) { c = App.getPixel(cp.getX() - 1, cp.getY()); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getY() + 1 < App.getHeight()) { c = App.getPixel(cp.getX(), cp.getY() + 1); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getY() - 1 >= 0) { c = App.getPixel(cp.getX(), cp.getY() - 1); canPlace = c != 0xFF && c != -1; } }*/ if (canPlace) { int seconds = getCooldown(); if (c_old != 0xFF && c_old != -1 && App.getDatabase().didPixelChange(cp.getX(), cp.getY())) { seconds = (int)Math.round(seconds * 1.6); } if (user.isShadowBanned()) { // ok let's just pretend to set a pixel... System.out.println("shadowban pixel!"); ServerPlace msg = new ServerPlace(Collections.singleton(new ServerPlace.Pixel(cp.getX(), cp.getY(), cp.getColor()))); for (WebSocketChannel ch : user.getConnections()) { server.send(ch, msg); } if (user.canUndo()) { server.send(channel, new ServerCanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } else { boolean mod_action = user.isOverridingCooldown(); App.putPixel(cp.getX(), cp.getY(), cp.getColor(), user, mod_action, ip, true); App.saveMap(); broadcastPixelUpdate(cp.getX(), cp.getY(), cp.getColor()); } if (!user.isOverridingCooldown()) { user.setLastPixelTime(); if (user.getStacked() > 0) { user.setLastPlaceWasStack(true); user.setStacked(user.getStacked()-1); sendStackedCount(user); } else { user.setLastPlaceWasStack(false); user.setCooldown(seconds); App.getDatabase().updateUserTime(user.getId(), seconds); } if (user.canUndo()) { server.send(channel, new ServerCanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } } } } sendCooldownData(user); } private void handlePlaceMaybe(WebSocketChannel channel, User user, ClientPlace cp, String ip) { } private void handleCaptcha(WebSocketChannel channel, User user, ClientCaptcha cc) { if (!user.isFlaggedForCaptcha()) return; if (user.isBanned()) return; Unirest .post("https://www.google.com/recaptcha/api/siteverify") .field("secret", App.getConfig().getString("captcha.secret")) .field("response", cc.getToken()) //.field("remoteip", "null") .asJsonAsync(new Callback<JsonNode>() { @Override public void completed(HttpResponse<JsonNode> response) { JsonNode body = response.getBody(); String hostname = App.getConfig().getString("host"); boolean success = body.getObject().getBoolean("success") && body.getObject().getString("hostname").equals(hostname); if (success) { user.validateCaptcha(); } server.send(channel, new ServerCaptchaStatus(success)); } @Override public void failed(UnirestException e) { } @Override public void cancelled() { } }); } private void updateUserData() { userData.run(() -> { server.broadcast(new ServerUsers(server.getAuthedUsers().size())); }); } private void sendCooldownData(WebSocketChannel channel, User user) { server.send(channel, new ServerCooldown(user.getRemainingCooldown())); } private void sendCooldownData(User user) { for (WebSocketChannel ch: user.getConnections()) { sendCooldownData(ch, user); } } private void broadcastPixelUpdate(int x, int y, int color) { server.broadcast(new ServerPlace(Collections.singleton(new ServerPlace.Pixel(x, y, color)))); } public void sendStackedCount(WebSocketChannel ch, User user) { server.send(ch, new ServerStack(user.getStacked())); } public void sendStackedCount(User user) { for (WebSocketChannel ch : user.getConnections()) { sendStackedCount(ch, user); } } public int getNumAllCons() { return numAllCons; } }
src/main/java/space/pxls/server/PacketHandler.java
package space.pxls.server; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.async.Callback; import com.mashape.unirest.http.exceptions.UnirestException; import io.undertow.websockets.core.WebSocketChannel; import space.pxls.App; import space.pxls.data.DBPixelPlacement; import space.pxls.user.Role; import space.pxls.user.User; import space.pxls.util.PxlsTimer; import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4; import java.util.Collections; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.lang.Math; import java.time.Instant; public class PacketHandler { private UndertowServer server; private PxlsTimer userData = new PxlsTimer(5); private int numAllCons = 0; public int getCooldown() { // TODO: make these parameters somehow configurable // exponential function of form a*exp(-b*(x - d)) + c double a = -8.04044740e+01; double b = 2.73880499e-03; double c = 9.63956320e+01; double d = -2.14065886e+00; double x = (double)server.getAuthedUsers().size(); return (int)Math.ceil(a*Math.exp(-b*(x - d)) + c); } public PacketHandler(UndertowServer server) { this.server = server; } public void userdata(WebSocketChannel channel, User user) { if (user != null) { server.send(channel, new ServerUserInfo( user.getName(), user.getRole().name().equals("SHADOWBANNED") ? "USER" : user.getRole().name(), user.isBanned(), user.isBanned() ? user.getBanExpiryTime() : 0, user.isBanned() ? user.getBanReason() : "", user.getLogin().split(":")[0] )); } } public void connect(WebSocketChannel channel, User user) { if (user != null) { userdata(channel, user); sendCooldownData(channel, user); sendStackedCount(channel, user); user.flagForCaptcha(); server.addAuthedUser(user); user.setInitialAuthTime(Instant.now().toEpochMilli()); } numAllCons++; updateUserData(); } public void disconnect(WebSocketChannel channel, User user) { if (user != null && user.getConnections().size() == 0) { server.removeAuthedUser(user); } numAllCons--; updateUserData(); } public void accept(WebSocketChannel channel, User user, Object obj, String ip) { if (user != null) { if (obj instanceof ClientPlace) { handlePlace(channel, user, ((ClientPlace) obj), ip); } if (obj instanceof ClientUndo) handleUndo(channel, user, ((ClientUndo) obj)); if (obj instanceof ClientCaptcha) handleCaptcha(channel, user, ((ClientCaptcha) obj)); if (obj instanceof ClientShadowBanMe) handleShadowBanMe(channel, user, ((ClientShadowBanMe) obj)); if (obj instanceof ClientBanMe) handleBanMe(channel, user, ((ClientBanMe) obj)); if (user.getRole().greaterEqual(Role.MODERATOR)) { if (obj instanceof ClientAdminCooldownOverride) handleCooldownOverride(channel, user, ((ClientAdminCooldownOverride) obj)); if (obj instanceof ClientAdminMessage) handleAdminMessage(channel, user, ((ClientAdminMessage) obj)); } } } private void handleAdminMessage(WebSocketChannel channel, User user, ClientAdminMessage obj) { User u = App.getUserManager().getByName(obj.getUsername()); if (u != null) { ServerAlert msg = new ServerAlert(escapeHtml4(obj.getMessage())); for (WebSocketChannel ch : u.getConnections()) { server.send(ch, msg); } } } private void handleShadowBanMe(WebSocketChannel channel, User user, ClientShadowBanMe obj) { if (user.getRole().greaterEqual(Role.USER)) { App.getDatabase().adminLog("self-shadowban via script", user.getId()); user.shadowban("auto-ban via script", 999*24*3600); } } private void handleBanMe(WebSocketChannel channel, User user, ClientBanMe obj) { App.getDatabase().adminLog("self-ban via script", user.getId()); user.ban(86400, "auto-ban via script"); } private void handleCooldownOverride(WebSocketChannel channel, User user, ClientAdminCooldownOverride obj) { user.setOverrideCooldown(obj.getOverride()); sendCooldownData(user); } private void handleUndo(WebSocketChannel channel, User user, ClientUndo cu){ if (!user.canUndoNow()) { return; } if (user.isShadowBanned()) { user.setLastUndoTime(); user.setCooldown(0); sendCooldownData(user); return; } DBPixelPlacement thisPixel = App.getDatabase().getUserUndoPixel(user); DBPixelPlacement recentPixel = App.getDatabase().getPixelAt(thisPixel.x, thisPixel.y); if (thisPixel.id != recentPixel.id) return; if (user.lastPlaceWasStack()) { user.setStacked(Math.max(user.getStacked() + 1, App.getConfig().getInt("stacking.maxStacked"))); sendStackedCount(user); } user.setLastUndoTime(); user.setCooldown(0); DBPixelPlacement lastPixel = App.getDatabase().getPixelByID(thisPixel.secondaryId); if (lastPixel != null) { App.getDatabase().putUserUndoPixel(lastPixel, user, thisPixel.id); App.putPixel(lastPixel.x, lastPixel.y, lastPixel.color, user, false, "(user undo)", false); broadcastPixelUpdate(lastPixel.x, lastPixel.y, lastPixel.color); } else { byte defaultColor = App.getDefaultColor(thisPixel.x, thisPixel.y); App.getDatabase().putUserUndoPixel(thisPixel.x, thisPixel.y, defaultColor, user, thisPixel.id); App.putPixel(thisPixel.x, thisPixel.y, defaultColor, user, false, "(user undo)", false); broadcastPixelUpdate(thisPixel.x, thisPixel.y, defaultColor); } sendCooldownData(user); } private void handlePlace(WebSocketChannel channel, User user, ClientPlace cp, String ip) { if (!cp.getType().equals("pixel")) { handlePlaceMaybe(channel, user, cp, ip); } if (cp.getX() < 0 || cp.getX() >= App.getWidth() || cp.getY() < 0 || cp.getY() >= App.getHeight()) return; if (cp.getColor() < 0 || cp.getColor() >= App.getConfig().getStringList("board.palette").size()) return; if (user.isBanned()) return; if (user.canPlace()) { if (user.updateCaptchaFlagPrePlace() && App.isCaptchaEnabled()) { server.send(channel, new ServerCaptchaRequired()); } else { int c = App.getPixel(cp.getX(), cp.getY()); boolean canPlace = c != cp.getColor() && c != 0xFF && c != -1; int c_old = c; /*if (!canPlace && (c == 0xFF || c == -1)) { // tendril expansion! if (!canPlace && cp.getX() + 1 < App.getWidth()) { c = App.getPixel(cp.getX() + 1, cp.getY()); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getX() - 1 >= 0) { c = App.getPixel(cp.getX() - 1, cp.getY()); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getY() + 1 < App.getHeight()) { c = App.getPixel(cp.getX(), cp.getY() + 1); canPlace = c != 0xFF && c != -1; } if (!canPlace && cp.getY() - 1 >= 0) { c = App.getPixel(cp.getX(), cp.getY() - 1); canPlace = c != 0xFF && c != -1; } }*/ if (canPlace) { int seconds = getCooldown(); if (c_old != 0xFF && c_old != -1 && App.getDatabase().didPixelChange(cp.getX(), cp.getY())) { seconds = (int)Math.round(seconds * 1.6); } if (user.isShadowBanned()) { // ok let's just pretend to set a pixel... System.out.println("shadowban pixel!"); ServerPlace msg = new ServerPlace(Collections.singleton(new ServerPlace.Pixel(cp.getX(), cp.getY(), cp.getColor()))); for (WebSocketChannel ch : user.getConnections()) { server.send(ch, msg); } if (user.canUndo()) { server.send(channel, new ServerCanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } else { boolean mod_action = user.isOverridingCooldown(); App.putPixel(cp.getX(), cp.getY(), cp.getColor(), user, mod_action, ip, true); App.saveMap(); broadcastPixelUpdate(cp.getX(), cp.getY(), cp.getColor()); } if (!user.isOverridingCooldown()) { user.setLastPixelTime(); if (user.getStacked() > 0) { user.setLastPlaceWasStack(true); user.setStacked(user.getStacked()-1); sendStackedCount(user); } else { user.setLastPlaceWasStack(false); user.setCooldown(seconds); App.getDatabase().updateUserTime(user.getId(), seconds); } if (user.canUndo()) { server.send(channel, new ServerCanUndo(App.getConfig().getDuration("undo.window", TimeUnit.SECONDS))); } } } } } sendCooldownData(user); } private void handlePlaceMaybe(WebSocketChannel channel, User user, ClientPlace cp, String ip) { } private void handleCaptcha(WebSocketChannel channel, User user, ClientCaptcha cc) { if (!user.isFlaggedForCaptcha()) return; if (user.isBanned()) return; Unirest .post("https://www.google.com/recaptcha/api/siteverify") .field("secret", App.getConfig().getString("captcha.secret")) .field("response", cc.getToken()) //.field("remoteip", "null") .asJsonAsync(new Callback<JsonNode>() { @Override public void completed(HttpResponse<JsonNode> response) { JsonNode body = response.getBody(); String hostname = App.getConfig().getString("host"); boolean success = body.getObject().getBoolean("success") && body.getObject().getString("hostname").equals(hostname); if (success) { user.validateCaptcha(); } server.send(channel, new ServerCaptchaStatus(success)); } @Override public void failed(UnirestException e) { } @Override public void cancelled() { } }); } private void updateUserData() { userData.run(() -> { server.broadcast(new ServerUsers(server.getAuthedUsers().size())); }); } private void sendCooldownData(WebSocketChannel channel, User user) { server.send(channel, new ServerCooldown(user.getRemainingCooldown())); } private void sendCooldownData(User user) { for (WebSocketChannel ch: user.getConnections()) { sendCooldownData(ch, user); } } private void broadcastPixelUpdate(int x, int y, int color) { server.broadcast(new ServerPlace(Collections.singleton(new ServerPlace.Pixel(x, y, color)))); } public void sendStackedCount(WebSocketChannel ch, User user) { server.send(ch, new ServerStack(user.getStacked())); } public void sendStackedCount(User user) { for (WebSocketChannel ch : user.getConnections()) { sendStackedCount(ch, user); } } public int getNumAllCons() { return numAllCons; } }
Fix undo giving a max stack
src/main/java/space/pxls/server/PacketHandler.java
Fix undo giving a max stack
Java
mit
38edbaa5caef6939b43400909844785766894817
0
villeteam/ville-standardutils,villeteam/ville-standardutils
package edu.vserver.ville.JSXGraph; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaScriptMathValidator { private static final String reserved = "PI" + "|" + "E" + "|" + "LN2|LN10" + "|" + "SQRT2|SQRT1_2" + "|" + "LOG2E|LOG10E" + "|" + "sin" + "|" + "cos" + "|" + "tan" + "|" + "atan" + "|" + "atan2" + "|" + "acos" + "|" + "asin" + "|" + "pow" + "|" + "sqrt" + "|" + "abs" + "|" + "exp" + "|" + "log" + "|" + "ceil" + "|" + "floor" + "|" + "max" + "|" + "min"; private static final Pattern whitelist = Pattern.compile( reserved + "|" + // numbers "[0-9]+(\\.[0-9]*)?" + "|" + // 1 character length variables "[a-z](?![a-zA-Z0-9])" + "|" + // whitespace "\\s" + "|" + "Math" + "|" + "," + "|" + "\\." + "|" + "\\+" + "|" + "\\-" + "|" + "\\*" + "|" + "\\/" + "|" + "\\(" + "|" + "\\)" ); public static String validate(String str) { str = str.replaceAll(reserved, "Math\\.$0"); System.out.println(str); Matcher matcher = whitelist.matcher(str); String consumed = matcher.replaceAll(""); if(consumed.isEmpty()) return str; else return ""; } }
src/main/java/edu/vserver/ville/JSXGraph/JavaScriptMathValidator.java
package edu.vserver.ville.JSXGraph; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaScriptMathValidator { private static final Pattern whitelist = Pattern.compile( // numbers "[0-9]+(\\.[0-9]*)?" + "|" + // 1 character length variables "[a-z](?![a-zA-Z0-9])" + "|" + // whitespace "\\s" + "|" + "Math" + "|" + "PI" + "|" + "E" + "|" + "LN2|LN10" + "|" + "SQRT2|SQRT1_2" + "|" + "LOG2E|LOG10E" + "|" + "sin" + "|" + "cos" + "|" + "tan" + "|" + "atan" + "|" + "atan2" + "|" + "acos" + "|" + "asin" + "|" + "pow" + "|" + "sqrt" + "|" + "abs" + "|" + "exp" + "|" + "log" + "|" + "ceil" + "|" + "floor" + "|" + "max" + "|" + "min" + "|" + "," + "|" + "\\." + "|" + "\\+" + "|" + "\\-" + "|" + "\\*" + "|" + "\\/" + "|" + "\\(" + "|" + "\\)" ); public static String validate(String str) { Matcher matcher = whitelist.matcher(str); String consumed = matcher.replaceAll(""); if(consumed.isEmpty()) return str; else return ""; } }
Validator now prepends Math. to reserved functions
src/main/java/edu/vserver/ville/JSXGraph/JavaScriptMathValidator.java
Validator now prepends Math. to reserved functions
Java
mit
e16c6d5e49424647a843479db5381d3acb488aa1
0
RITJBF/JBioFramework,RITJBF/JBioFramework,RITJBF/JBioFramework
/* * A 2D simulation of electrophoresis using Swing components. */ /** * @author Jill Zapoticznyj * @author Adam Bazinet * @author Amanda Fisher */ import javax.swing.*; import java.awt.event.*; import java.util.*; import java.awt.*; public class GelCanvasSwingVersion extends JPanel implements MouseListener { private Electro2D electro2D; private Vector barProteins; private Vector dotProteins; private Vector barProteins2; private Vector dotProteins2; private double maxPH = -1; private double minPH = -1; private double lowAcrylamide; private double highAcrylamide; private CompIEF comp; private static final int VOLTAGE = 50; private Graphics graphic; private Rectangle gelCanvasRectangle; private Image bufferImage; private Graphics bufferImageGraphics; private boolean pHLinesNeedToBeDrawn; private boolean mWLinesNeedToBeDrawn; private boolean redrawPHAndMWLines; private boolean indicateProteinPosition; private double tenK = 48; private double twentyfiveK = 48; private double fiftyK = 48; private double hundredK = 48; private int genDotsRepeats; private boolean calculateMW = true; private boolean reMWLabel = false; private boolean barProteinsStillMoving = true; /** * Constructs a gel canvas and adds itself as a mouse listener * * @param e Used to link back to the electro2D that will use the gel canvas */ public GelCanvasSwingVersion(Electro2D e) { super(); electro2D = e; addMouseListener(this); } /** * The different mouse listener methods that must be overridden * in order to implement mouse listener */ public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } /** * Sets up the gel canvas for animating the electrophoresis simulation */ public void prepare() { /** * Make two vectors that will contain the objects that are the image * representations of the proteins in gel canvas */ barProteins = new Vector(); dotProteins = new Vector(); /** * Set up the static variables in IEFProtein so it knows the pH range */ maxPH = electro2D.getMaxRange(); minPH = electro2D.getMinRange(); IEFProteinSwingVersion.setRange( maxPH, minPH ); /** * Create the CompIEF object that later will help sort the proteins */ comp = new CompIEF( maxPH, minPH ); /** * Call the next method, which will handle setting up the barProtein * vector */ fillBarProteinVector(); } public void fillBarProteinVector() { /** * Get all the information barProtein vector will need from electro2D * into local variable vectors. */ Vector sequenceTitles = electro2D.getSequenceTitles(); Vector molecularWeights = electro2D.getMolecularWeights(); Vector pIValues = electro2D.getPiValues(); Vector sequences = electro2D.getSequences(); Vector functions = electro2D.getFunctions(); /** * Fill up the barProteins vector */ for(int i = 0; i < sequenceTitles.size(); i++) { barProteins.addElement(new IEFProteinSwingVersion(new E2DProtein( ((String)sequenceTitles.elementAt(i)), ((Double.valueOf( (String)molecularWeights.elementAt(i)))).doubleValue(), ((Double.valueOf( (String)pIValues.elementAt(i)))).doubleValue(), (String)sequences.elementAt(i), (String)functions.elementAt(i)), this)); } /** * Call the next method, which will sort the elements in barProteins */ sortBarProteins(); } public void sortBarProteins() { /** * This nested for loop will do a sort of collapsing exercise; every * protein in the barProtein vector will be evaluated by the CompIEF * class against every other protein, and if they're the same they'll * be collapsed into the same element. * * The for loops start out with their iterators at -1 the length of * barProteins so that they can access their elements in order correctly */ for(int i = barProteins.size() - 1; i >= 0; i--) { for(int j = i-1; j >= 0; j--) { if(comp.compare((IEFProteinSwingVersion)barProteins.elementAt(i), (IEFProteinSwingVersion)barProteins.elementAt(j)) == 0) { ((IEFProteinSwingVersion)(barProteins.elementAt(i))).addProtein( ((IEFProteinSwingVersion)(barProteins.elementAt(j))).getProtein()); barProteins.remove(j); i--; j = i; } } } /** * call the next method, makeDotProteins(), which will convert the bar * proteins into dot proteins, animation wise */ makeDotProteins(); } public void makeDotProteins() { /** * this next for loop goes through each element in the vector that we * just collapsed everything in and retrieves all the proteins that * were represented by each bar in the last animation */ Vector tempProteins = new Vector(); double tempx = 0; double tempy = 0; for(int i = 0; i < barProteins.size(); i++) { /** * retrieve the coordinates and proteins of each bar protein */ tempx = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).returnX(); tempy = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).returnY(); tempProteins = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).getProtein(); for(int j = 0; j < tempProteins.size(); j++) { /** * make a protein dot animation for each protein contained in * the bar proteins */ dotProteins.addElement(new ProteinDotSwingVersion( ((E2DProtein)(tempProteins.elementAt(j))), this, tempx, tempy + 43)); } tempProteins.removeAllElements(); } } /** * The prepare2 method is called only when the user wishes to compare * two proteome files. The method performs the same basic steps as * the original prepare method cascade, as well as comparing the proteins * from the second file to those already contained in the first file. * If two proteins are the same, it colors the first file's matching * proteins green and removes the proteins from the second file's * collection of proteins. */ public void prepare2() { Vector sequenceTitles2 = electro2D.getSequenceTitles2(); Vector molecularWeights2 = electro2D.getMolecularWeights2(); Vector pIValues2 = electro2D.getPiValues2(); Vector sequences2 = electro2D.getSequences2(); Vector functions2 = electro2D.getFunctions2(); barProteins2 = new Vector(); dotProteins2 = new Vector(); /** * compare the sequences of the second file to the sequences of * the proteins in the first file */ for(int i = dotProteins.size() - 1; i >= 0; i--) { /** * color the proteins in the first file red */ ((ProteinDotSwingVersion)dotProteins.elementAt(i)).changeColor(Color.red); String tempSequence = ((ProteinDotSwingVersion)dotProteins.elementAt(i)).getPro().getSequence(); for(int j = sequences2.size() - 1; j >= 0; j--) { /** * if the sequences match, remove the sequence and its * corresponding information from the second file's list of * info and color the protein green in the vector of proteins * from the first file */ if(((String)sequences2.elementAt(j)).equals(tempSequence)){ sequences2.remove(j); sequenceTitles2.remove(j); molecularWeights2.remove(j); pIValues2.remove(j); functions2.remove(j); ((ProteinDotSwingVersion)dotProteins.elementAt(i)).changeColor(Color.green); break; } } } /** * Next, make IEF bar proteins out of the proteins on the second list * that didn't match the proteins in the first list so that their * positions on the gel field can later be determined */ for(int i = 0; i < sequences2.size(); i++) { barProteins2.addElement(new IEFProteinSwingVersion(new E2DProtein( ((String)sequenceTitles2.elementAt(i)), ((Double.valueOf( (String)molecularWeights2.elementAt(i)))).doubleValue(), ((Double.valueOf( (String)pIValues2.elementAt(i)))).doubleValue(), (String)sequences2.elementAt(i), (String)functions2.elementAt(i)), this)); } /** * Convert the bar proteins into dot proteins and color them all yello * to designate them as being the ones from the second list that did * not match. */ int tempx; int tempy; Vector tempProteins; ProteinDotSwingVersion tempDot; for(int i = 0; i < barProteins2.size(); i++) { tempx = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).returnX(); tempy = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).returnY(); tempProteins = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).getProtein(); tempDot = new ProteinDotSwingVersion((E2DProtein)tempProteins.elementAt(0), this, tempx, tempy + 43); tempDot.changeColor(Color.yellow); dotProteins2.addElement(tempDot); } } /** * The paintComponent method does the actual drawing when the System calls * for the GelCanvas to be set up. * * @override overrides the paintComponent method of JPanel */ public void paintComponent(Graphics g) { /** * We first set up the graphics object to equal an instance variable * so other methods can interact with it. */ graphic = g; /** * We then set up a buffer image area so that once we're done painting * on it we can transfer what we've drawn to the actual area that the * user can see. This reduces flickering. */ if(gelCanvasRectangle == null || bufferImage == null || bufferImageGraphics == null) { gelCanvasRectangle = getBounds(); bufferImage = this.createImage(gelCanvasRectangle.width, gelCanvasRectangle.height); bufferImageGraphics = bufferImage.getGraphics(); } /** * Next we check to see if it's time to draw the pH lines by finding if * an animation has been run by looking at whether or not the PH values * are different from their startig values of -1 as well as checking to * see if the Line boolean indicates that the lines have already been * drawn. */ if(maxPH != -1 && minPH != -1 && pHLinesNeedToBeDrawn) { drawPHLines(); } /** * Check to see if the SDS animation has been run, and if it has * draw the lines for molecular weight. */ if(mWLinesNeedToBeDrawn) { initiateMWLines(); mWLinesNeedToBeDrawn = false; redrawPHAndMWLines = true; } else if (redrawPHAndMWLines) { drawPHLines(); redoMWLines(); } /** * When the user clicks on a protein name in the protein list in * Electro2D, the drawProteinPosition method will draw a draw axis on * the gel canvas with the protein of interest at its origin. */ if (indicateProteinPosition) { drawProteinPosition(); } /** * Next, we color the buffer image with a rectangle the size of our * canvas in a sort of subdued blue color. Then we make a red * rectangle at the top of the image that's almost as long as the * image itself but only 46 pixals tall. * Then we copy it all over to our canvas. */ bufferImageGraphics.setColor(new Color(54,100,139)); bufferImageGraphics.drawRect(0,0,gelCanvasRectangle.width-1,gelCanvasRectangle.height-1); bufferImageGraphics.setColor( Color.RED ); bufferImageGraphics.drawRect( 1, 1, gelCanvasRectangle.width - 3, 46 ); graphic.drawImage(bufferImage, 0, 0, this); } /** * This method is responsible for drawing the dot proteins onto the canvas * * @param g the graphics object */ public void update(Graphics g) { // First, clear off any dots left over from the last animation bufferImageGraphics.clearRect(1, 48, gelCanvasRectangle.width - 2, gelCanvasRectangle.height - 49); // Then, draw the protein dots for(int i = 0; i < dotProteins.size(); i++) { ((ProteinDotSwingVersion)(dotProteins.elementAt(i))).draw(bufferImageGraphics); } if(dotProteins2 != null) { for(int i = 0; i < dotProteins2.size(); i++) { ((ProteinDotSwingVersion)(dotProteins2.elementAt(i))).draw(bufferImageGraphics); } } // update the background if(mWLinesNeedToBeDrawn && tenK != 48) { redoMWLines(); drawPHLines(); } // transfer the buffer image to the real canvas g.drawImage(bufferImage, 0, 0, this); paint(g); } /** * returns the graphics object used to draw on the canvas * * @return graphic */ public Graphics getGraphic() { return graphic; } /** * This method draws the dotted gray vertical lines that represent * where the different pH values are on the canvas. */ public void drawPHLines() { int length = 0; int loc = 0; bufferImageGraphics.setColor(Color.GRAY); /** * Loop through each integer that's in the range between the minPH * and the maxPH and use that integer to figure out the starting point * for the line. Then draw a dotted line down the length of the canvas. */ for(int i = (int)minPH + 1; i <= (int)maxPH; i = i + 1) { length = 0; loc =(int)((getWidth() - 4 ) * ((i - minPH)/(maxPH - minPH ))); while(length < this.getHeight()) { bufferImageGraphics.drawLine(loc, length, loc, length + 5); length = length + 10; } // Show the pH labels. electro2D.showpH(loc, i); } pHLinesNeedToBeDrawn = false; } /** * Use this method to say that the pH lines need to be redrawn, but not the * molecular weight lines. */ public void setreLine() { pHLinesNeedToBeDrawn = true; redrawPHAndMWLines = false; } /** * Use this method to say that the pH lines and the molecular wieght * lines shouldn't be redrawn. */ public void resetReLine() { pHLinesNeedToBeDrawn = false; redrawPHAndMWLines = false; } /** * This method is called by the reset button and sets all of the animation * variables back to their default values. */ public void resetRanges() { minPH = -1; maxPH = -1; tenK = 48; twentyfiveK = 48; fiftyK = 48; hundredK = 48; reMWLabel = false; calculateMW = true; redrawPHAndMWLines = false; mWLinesNeedToBeDrawn = false; barProteinsStillMoving = true; } /** * This method is used by DotThread to let the paint method know it's time * to generate the molecular weight markers. * * @param i Number of times the genDots() method was called. */ public void setMWLines(int i){ mWLinesNeedToBeDrawn = true; calculateMW = true; genDotsRepeats = i; } /** * This method initializes the lines that denote the different ranges of * molecular weight and draws them for the first time. */ public void initiateMWLines() { lowAcrylamide = electro2D.getLowPercent(); highAcrylamide = electro2D.getHighPercent(); int height = this.getHeight(); if(calculateMW) { if(lowAcrylamide == highAcrylamide) { for(int i = 0; i < genDotsRepeats; i++) { hundredK = hundredK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/100000); fiftyK = fiftyK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/50000); twentyfiveK = twentyfiveK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/25000); tenK = tenK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/10000); } } else { for(int i = 0; i < genDotsRepeats; i++) { hundredK = hundredK + (10 * 1/(((hundredK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+lowAcrylamide)) * (VOLTAGE/25)* .25 * (100000/100000); fiftyK = fiftyK + (10 * 1/(((fiftyK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+ lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/50000); twentyfiveK = twentyfiveK + (10 * 1/(((twentyfiveK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+ lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/25000); tenK = tenK + (10 * 1/(((tenK - 48)*(highAcrylamide - lowAcrylamide)/(height - 48)) + lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/10000); } } calculateMW = false; int width = 0; bufferImageGraphics.setColor(Color.LIGHT_GRAY); while (width < this.getWidth()) { bufferImageGraphics.drawLine(width, (int)hundredK, width + 5, (int)hundredK); bufferImageGraphics.drawLine(width, (int)fiftyK, width + 5, (int)fiftyK); bufferImageGraphics.drawLine(width, (int)twentyfiveK, width + 5, (int)twentyfiveK); bufferImageGraphics.drawLine(width, (int)tenK, width + 5, (int)tenK); width = width + 10; } electro2D.clearMW(); electro2D.showMW((int)hundredK, (int)fiftyK, (int)twentyfiveK, (int)tenK, reMWLabel); reMWLabel = true; graphic.drawImage(bufferImage, 0, 0, this); } } /** * This method redraws the lines that denote the different ranges of * molecular weight after the initializeMWLines method has already been * run. */ public void redoMWLines() { lowAcrylamide = electro2D.getLowPercent(); highAcrylamide = electro2D.getHighPercent(); int width = 0; bufferImageGraphics.setColor(Color.LIGHT_GRAY); while(width < this.getWidth()) { bufferImageGraphics.drawLine(width, (int)hundredK, width + 5, (int)hundredK); bufferImageGraphics.drawLine(width, (int)fiftyK, width + 5, (int)fiftyK); bufferImageGraphics.drawLine(width, (int)twentyfiveK, width + 5, (int)twentyfiveK); bufferImageGraphics.drawLine(width, (int)tenK, width + 5, (int)tenK); width = width + 10; } electro2D.clearMW(); electro2D.showMW((int)hundredK, (int)fiftyK, (int)twentyfiveK, (int)tenK, reMWLabel); reMWLabel = true; } /** * This method draws the IEF proteins, which appear as moving rectangles at * the top of the animation, to the screen. */ public void drawIEF() { for(int i = 0; i < barProteins.size(); i++){ if(barProteinsStillMoving) { ((IEFProtein)barProteins.elementAt(i)).changeX(); } else { ((IEFProtein)barProteins.elementAt(i)).setX(); } ((IEFProtein)(barProteins.elementAt(i))).draw(bufferImageGraphics); } for(int i = 0; i < barProteins2.size(); i++){ if(barProteinsStillMoving) { ((IEFProtein)barProteins2.elementAt(i)).changeX(); } else { ((IEFProtein)barProteins2.elementAt(i)).setX(); } ((IEFProtein)(barProteins2.elementAt(i))).draw(bufferImageGraphics); } graphic.drawImage(bufferImage, 0, 0, this); this.repaint(); } /** * This method gives the illusion that the barProteins are being squashed * into the lower part of the animation. */ public void shrinkIEF() { clearIEF(); drawIEF(); } /** * This method clears the IEF animation area. */ public void clearIEF() { bufferImageGraphics.setColor(Color.WHITE); bufferImageGraphics.clearRect(2, 2, gelCanvasRectangle.width - 3, 45); } public void drawProteinPosition() { } }
svnrepo/RIT_JBF_source/GelCanvasSwingVersion.java
/* * A 2D simulation of electrophoresis using Swing components. */ /** * @author Jill Zapoticznyj * @author Adam Bazinet * @author Amanda Fisher */ import javax.swing.*; import java.awt.event.*; import java.util.*; import java.awt.*; public class GelCanvasSwingVersion extends JPanel implements MouseListener { private Electro2D electro2D; private Vector barProteins; private Vector dotProteins; private Vector barProteins2; private Vector dotProteins2; private double maxPH = -1; private double minPH = -1; private double lowAcrylamide; private double highAcrylamide; private CompIEF comp; private static final int VOLTAGE = 50; private Graphics graphic; private Rectangle gelCanvasRectangle; private Image bufferImage; private Graphics bufferImageGraphics; private boolean pHLinesNeedToBeDrawn; private boolean mWLinesNeedToBeDrawn; private boolean redrawPHAndMWLines; private boolean indicateProteinPosition; private double tenK = 48; private double twentyfiveK = 48; private double fiftyK = 48; private double hundredK = 48; private int genDotsRepeats; private boolean calculateMW = true; private boolean reMWLabel = false; private boolean barProteinsStillMoving = true; /** * Constructs a gel canvas and adds itself as a mouse listener * * @param e Used to link back to the electro2D that will use the gel canvas */ public GelCanvasSwingVersion(Electro2D e) { super(); electro2D = e; addMouseListener(this); } /** * The different mouse listener methods that must be overridden * in order to implement mouse listener */ public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } /** * Sets up the gel canvas for animating the electrophoresis simulation */ public void prepare() { /** * Make two vectors that will contain the objects that are the image * representations of the proteins in gel canvas */ barProteins = new Vector(); dotProteins = new Vector(); /** * Set up the static variables in IEFProtein so it knows the pH range */ maxPH = electro2D.getMaxRange(); minPH = electro2D.getMinRange(); IEFProteinSwingVersion.setRange( maxPH, minPH ); /** * Create the CompIEF object that later will help sort the proteins */ comp = new CompIEF( maxPH, minPH ); /** * Call the next method, which will handle setting up the barProtein * vector */ fillBarProteinVector(); } public void fillBarProteinVector() { /** * Get all the information barProtein vector will need from electro2D * into local variable vectors. */ Vector sequenceTitles = electro2D.getSequenceTitles(); Vector molecularWeights = electro2D.getMolecularWeights(); Vector pIValues = electro2D.getPiValues(); Vector sequences = electro2D.getSequences(); Vector functions = electro2D.getFunctions(); /** * Fill up the barProteins vector */ for(int i = 0; i < sequenceTitles.size(); i++) { barProteins.addElement(new IEFProteinSwingVersion(new E2DProtein( ((String)sequenceTitles.elementAt(i)), ((Double.valueOf( (String)molecularWeights.elementAt(i)))).doubleValue(), ((Double.valueOf( (String)pIValues.elementAt(i)))).doubleValue(), (String)sequences.elementAt(i), (String)functions.elementAt(i)), this)); } /** * Call the next method, which will sort the elements in barProteins */ sortBarProteins(); } public void sortBarProteins() { /** * This nested for loop will do a sort of collapsing exercise; every * protein in the barProtein vector will be evaluated by the CompIEF * class against every other protein, and if they're the same they'll * be collapsed into the same element. * * The for loops start out with their iterators at -1 the length of * barProteins so that they can access their elements in order correctly */ for(int i = barProteins.size() - 1; i >= 0; i--) { for(int j = i-1; j >= 0; j--) { if(comp.compare((IEFProteinSwingVersion)barProteins.elementAt(i), (IEFProteinSwingVersion)barProteins.elementAt(j)) == 0) { ((IEFProteinSwingVersion)(barProteins.elementAt(i))).addProtein( ((IEFProteinSwingVersion)(barProteins.elementAt(j))).getProtein()); barProteins.remove(j); i--; j = i; } } } /** * call the next method, makeDotProteins(), which will convert the bar * proteins into dot proteins, animation wise */ makeDotProteins(); } public void makeDotProteins() { /** * this next for loop goes through each element in the vector that we * just collapsed everything in and retrieves all the proteins that * were represented by each bar in the last animation */ Vector tempProteins = new Vector(); double tempx = 0; double tempy = 0; for(int i = 0; i < barProteins.size(); i++) { /** * retrieve the coordinates and proteins of each bar protein */ tempx = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).returnX(); tempy = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).returnY(); tempProteins = ((IEFProteinSwingVersion)(barProteins.elementAt(i))).getProtein(); for(int j = 0; j < tempProteins.size(); j++) { /** * make a protein dot animation for each protein contained in * the bar proteins */ dotProteins.addElement(new ProteinDotSwingVersion( ((E2DProtein)(tempProteins.elementAt(j))), this, tempx, tempy + 43)); } tempProteins.removeAllElements(); } } /** * The prepare2 method is called only when the user wishes to compare * two proteome files. The method performs the same basic steps as * the original prepare method cascade, as well as comparing the proteins * from the second file to those already contained in the first file. * If two proteins are the same, it colors the first file's matching * proteins green and removes the proteins from the second file's * collection of proteins. */ public void prepare2() { Vector sequenceTitles2 = electro2D.getSequenceTitles2(); Vector molecularWeights2 = electro2D.getMolecularWeights2(); Vector pIValues2 = electro2D.getPiValues2(); Vector sequences2 = electro2D.getSequences2(); Vector functions2 = electro2D.getFunctions2(); barProteins2 = new Vector(); dotProteins2 = new Vector(); /** * compare the sequences of the second file to the sequences of * the proteins in the first file */ for(int i = dotProteins.size() - 1; i >= 0; i--) { /** * color the proteins in the first file red */ ((ProteinDotSwingVersion)dotProteins.elementAt(i)).changeColor(Color.red); String tempSequence = ((ProteinDotSwingVersion)dotProteins.elementAt(i)).getPro().getSequence(); for(int j = sequences2.size() - 1; j >= 0; j--) { /** * if the sequences match, remove the sequence and its * corresponding information from the second file's list of * info and color the protein green in the vector of proteins * from the first file */ if(((String)sequences2.elementAt(j)).equals(tempSequence)){ sequences2.remove(j); sequenceTitles2.remove(j); molecularWeights2.remove(j); pIValues2.remove(j); functions2.remove(j); ((ProteinDotSwingVersion)dotProteins.elementAt(i)).changeColor(Color.green); break; } } } /** * Next, make IEF bar proteins out of the proteins on the second list * that didn't match the proteins in the first list so that their * positions on the gel field can later be determined */ for(int i = 0; i < sequences2.size(); i++) { barProteins2.addElement(new IEFProteinSwingVersion(new E2DProtein( ((String)sequenceTitles2.elementAt(i)), ((Double.valueOf( (String)molecularWeights2.elementAt(i)))).doubleValue(), ((Double.valueOf( (String)pIValues2.elementAt(i)))).doubleValue(), (String)sequences2.elementAt(i), (String)functions2.elementAt(i)), this)); } /** * Convert the bar proteins into dot proteins and color them all yello * to designate them as being the ones from the second list that did * not match. */ int tempx; int tempy; Vector tempProteins; ProteinDotSwingVersion tempDot; for(int i = 0; i < barProteins2.size(); i++) { tempx = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).returnX(); tempy = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).returnY(); tempProteins = ((IEFProteinSwingVersion)barProteins2.elementAt(i)).getProtein(); tempDot = new ProteinDotSwingVersion((E2DProtein)tempProteins.elementAt(0), this, tempx, tempy + 43); tempDot.changeColor(Color.yellow); dotProteins2.addElement(tempDot); } } /** * The paintComponent method does the actual drawing when the System calls * for the GelCanvas to be set up. * * @override overrides the paintComponent method of JPanel */ public void paintComponent(Graphics g) { /** * We first set up the graphics object to equal an instance variable * so other methods can interact with it. */ graphic = g; /** * We then set up a buffer image area so that once we're done painting * on it we can transfer what we've drawn to the actual area that the * user can see. This reduces flickering. */ if(gelCanvasRectangle == null || bufferImage == null || bufferImageGraphics == null) { gelCanvasRectangle = getBounds(); bufferImage = this.createImage(gelCanvasRectangle.width, gelCanvasRectangle.height); bufferImageGraphics = bufferImage.getGraphics(); } /** * Next we check to see if it's time to draw the pH lines by finding if * an animation has been run by looking at whether or not the PH values * are different from their startig values of -1 as well as checking to * see if the Line boolean indicates that the lines have already been * drawn. */ if(maxPH != -1 && minPH != -1 && pHLinesNeedToBeDrawn) { drawPHLines(); } /** * Check to see if the SDS animation has been run, and if it has * draw the lines for molecular weight. */ if(mWLinesNeedToBeDrawn) { initiateMWLines(); mWLinesNeedToBeDrawn = false; redrawPHAndMWLines = true; } else if (redrawPHAndMWLines) { drawPHLines(); redoMWLines(); } /** * When the user clicks on a protein name in the protein list in * Electro2D, the drawProteinPosition method will draw a draw axis on * the gel canvas with the protein of interest at its origin. */ if (indicateProteinPosition) { drawProteinPosition(); } /** * Next, we color the buffer image with a rectangle the size of our * canvas in a sort of subdued blue color. Then we make a red * rectangle at the top of the image that's almost as long as the * image itself but only 46 pixals tall. * Then we copy it all over to our canvas. */ bufferImageGraphics.setColor(new Color(54,100,139)); bufferImageGraphics.drawRect(0,0,gelCanvasRectangle.width-1,gelCanvasRectangle.height-1); bufferImageGraphics.setColor( Color.RED ); bufferImageGraphics.drawRect( 1, 1, gelCanvasRectangle.width - 3, 46 ); graphic.drawImage(bufferImage, 0, 0, this); } /** * This method is responsible for drawing the dot proteins onto the canvas * * @param g the graphics object */ public void update(Graphics g) { // First, clear off any dots left over from the last animation bufferImageGraphics.clearRect(1, 48, gelCanvasRectangle.width - 2, gelCanvasRectangle.height - 49); // Then, draw the protein dots for(int i = 0; i < dotProteins.size(); i++) { ((ProteinDotSwingVersion)(dotProteins.elementAt(i))).draw(bufferImageGraphics); } if(dotProteins2 != null) { for(int i = 0; i < dotProteins2.size(); i++) { ((ProteinDotSwingVersion)(dotProteins2.elementAt(i))).draw(bufferImageGraphics); } } // update the background if(mWLinesNeedToBeDrawn && tenK != 48) { redoMWLines(); drawPHLines(); } // transfer the buffer image to the real canvas g.drawImage(bufferImage, 0, 0, this); paint(g); } /** * returns the graphics object used to draw on the canvas * * @return graphic */ public Graphics getGraphic() { return graphic; } /** * This method draws the dotted gray vertical lines that represent * where the different pH values are on the canvas. */ public void drawPHLines() { int length = 0; int loc = 0; bufferImageGraphics.setColor(Color.GRAY); /** * Loop through each integer that's in the range between the minPH * and the maxPH and use that integer to figure out the starting point * for the line. Then draw a dotted line down the length of the canvas. */ for(int i = (int)minPH + 1; i <= (int)maxPH; i = i + 1) { length = 0; loc =(int)((getWidth() - 4 ) * ((i - minPH)/(maxPH - minPH ))); while(length < this.getHeight()) { bufferImageGraphics.drawLine(loc, length, loc, length + 5); length = length + 10; } // Show the pH labels. electro2D.showpH(loc, i); } pHLinesNeedToBeDrawn = false; } /** * Use this method to say that the pH lines need to be redrawn, but not the * molecular weight lines. */ public void setreLine() { pHLinesNeedToBeDrawn = true; redrawPHAndMWLines = false; } /** * Use this method to say that the pH lines and the molecular wieght * lines shouldn't be redrawn. */ public void resetReLine() { pHLinesNeedToBeDrawn = false; redrawPHAndMWLines = false; } /** * This method is called by the reset button and sets all of the animation * variables back to their default values. */ public void resetRanges() { minPH = -1; maxPH = -1; tenK = 48; twentyfiveK = 48; fiftyK = 48; hundredK = 48; reMWLabel = false; calculateMW = true; redrawPHAndMWLines = false; mWLinesNeedToBeDrawn = false; barProteinsStillMoving = true; } /** * This method is used by DotThread to let the paint method know it's time * to generate the molecular weight markers. * * @param i Number of times the genDots() method was called. */ public void setMWLines(int i){ mWLinesNeedToBeDrawn = true; calculateMW = true; genDotsRepeats = i; } /** * This method initializes the lines that denote the different ranges of * molecular weight and draws them for the first time. */ public void initiateMWLines() { lowAcrylamide = electro2D.getLowPercent(); highAcrylamide = electro2D.getHighPercent(); int height = this.getHeight(); if(calculateMW) { if(lowAcrylamide == highAcrylamide) { for(int i = 0; i < genDotsRepeats; i++) { hundredK = hundredK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/100000); fiftyK = fiftyK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/50000); twentyfiveK = twentyfiveK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/25000); tenK = tenK + (10 * (1/lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/10000); } } else { for(int i = 0; i < genDotsRepeats; i++) { hundredK = hundredK + (10 * 1/(((hundredK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+lowAcrylamide)) * (VOLTAGE/25)* .25 * (100000/100000); fiftyK = fiftyK + (10 * 1/(((fiftyK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+ lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/50000); twentyfiveK = twentyfiveK + (10 * 1/(((twentyfiveK - 48) * (highAcrylamide - lowAcrylamide)/(height - 48))+ lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/25000); tenK = tenK + (10 * 1/(((tenK - 48)*(highAcrylamide - lowAcrylamide)/(height - 48)) + lowAcrylamide)) * (VOLTAGE/25) * .25 * (100000/10000); } } calculateMW = false; int width = 0; bufferImageGraphics.setColor(Color.LIGHT_GRAY); while (width < this.getWidth()) { bufferImageGraphics.drawLine(width, (int)hundredK, width + 5, (int)hundredK); } } } /** * This method redraws the lines that denote the different ranges of * molecular weight after the initializeMWLines method has already been * run. */ public void redoMWLines() { lowAcrylamide = electro2D.getLowPercent(); highAcrylamide = electro2D.getHighPercent(); int width = 0; bufferImageGraphics.setColor(Color.LIGHT_GRAY); while(width < this.getWidth()) { bufferImageGraphics.drawLine(width, (int)hundredK, width + 5, (int)hundredK); bufferImageGraphics.drawLine(width, (int)fiftyK, width + 5, (int)fiftyK); bufferImageGraphics.drawLine(width, (int)twentyfiveK, width + 5, (int)twentyfiveK); bufferImageGraphics.drawLine(width, (int)tenK, width + 5, (int)tenK); width = width + 10; } electro2D.clearMW(); electro2D.showMW((int)hundredK, (int)fiftyK, (int)twentyfiveK, (int)tenK, reMWLabel); reMWLabel = true; } public void drawProteinPosition() { } }
Finished initiateMWLines, and wrote the drawIEF, shrinkIEF, and clearIEF methods. git-svn-id: 0cc297c1ae0bcb1aeb855283c9eab5b6fcf46d39@17 2e2cb376-e6e5-444d-bc97-f30e4722beb7
svnrepo/RIT_JBF_source/GelCanvasSwingVersion.java
Finished initiateMWLines, and wrote the drawIEF, shrinkIEF, and clearIEF methods.
Java
mit
6e58abd9bd5adee40160fa51382c202e1bfeff64
0
AndrewMiTe/realm-ruler
/* * MIT License * * Copyright (c) 2016 Andrew Michael Teller(https://github.com/AndrewMiTe) * * 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 client; import java.util.ArrayDeque; import java.util.Deque; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Paint; /** * Specialized pane that accepts requests for information from the client user * in the form of another View object. Returns the scene to this view when the * request has been dismissed. * @author Andrew M. Teller(https://github.com/AndrewMiTe) */ public abstract class View extends Pane { private Pane innerPane; private final Deque<Pane> paneStack; /** * Initiates the view with the default appearance. */ public View() { this(new Node[0]); } /** * Initiates the view with the default appearance and adds child nodes. * @param children initial set of children for this pane. */ public View(Node... children) { super(); this.innerPane = new Pane(children); super.getChildren().add(this.innerPane); this.paneStack = new ArrayDeque<>(); this.paneStack.add(innerPane); applyTemplate(); } /** * Changes the scene of the view to the given view object while the previous * view goes into a stack. Calling {@link #unstack() unstack()} reverts the * scene to the View object on the top of the stack. * @param newView */ public void stack(View newView) { if ((newView != null) && !paneStack.contains(newView)) { paneStack.push(newView); innerPane = newView; super.getChildren().clear(); super.getChildren().add(innerPane); } } /** * Reverts the scene to a previous view. If the stack of previous views is * empty, then the current view remains as the child of the scene. */ public void unstack() { unstack(paneStack.peek()); } public void unstack(Pane request) { SO.o("unstack(Pane request)"); if (paneStack.contains(request) && paneStack.size() > 1) { SO.o("unstack(): inside if"); paneStack.remove(request); innerPane = paneStack.peek(); super.getChildren().clear(); super.getChildren().add(innerPane); } } /** * Configures the view to the default appearance. */ private void applyTemplate() { this.setBackground(new Background(new BackgroundFill( Paint.valueOf("black"), CornerRadii.EMPTY, Insets.EMPTY ))); } public Pane getInnerPane() { return innerPane; } }
src/client/View.java
/* * MIT License * * Copyright (c) 2016 Andrew Michael Teller(https://github.com/AndrewMiTe) * * 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 client; import java.util.ArrayDeque; import java.util.Deque; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.layout.Pane; import javafx.scene.paint.Paint; // @todo fix View so that a Pane inside the View is swapped and stacked. /** * Specialized pane that accepts requests for information from the client user * in the form of another View object. Returns the scene to this view when the * request has been dismissed. * @author Andrew M. Teller(https://github.com/AndrewMiTe) */ public abstract class View extends Pane { private Pane innerPane; private final Deque<Pane> paneStack; /** * Initiates the view with the default appearance. */ public View() { this(new Node[0]); } /** * Initiates the view with the default appearance and adds child nodes. * @param children initial set of children for this pane. */ public View(Node... children) { super(); this.innerPane = new Pane(children); super.getChildren().add(this.innerPane); this.paneStack = new ArrayDeque<>(); this.paneStack.add(innerPane); applyTemplate(); } /** * Changes the scene of the view to the given view object while the previous * view goes into a stack. Calling {@link #unstack() unstack()} reverts the * scene to the View object on the top of the stack. * @param newView */ public void stack(View newView) { if ((newView != null) && !paneStack.contains(newView)) { paneStack.push(newView); innerPane = newView; super.getChildren().clear(); super.getChildren().add(innerPane); } } /** * Reverts the scene to a previous view. If the stack of previous views is * empty, then the current view remains as the child of the scene. */ public void unstack() { unstack(paneStack.peek()); } public void unstack(Pane request) { SO.o("unstack(Pane request)"); if (paneStack.contains(request) && paneStack.size() > 1) { SO.o("unstack(): inside if"); paneStack.remove(request); innerPane = paneStack.peek(); super.getChildren().clear(); super.getChildren().add(innerPane); } } /** * Configures the view to the default appearance. */ private void applyTemplate() { this.setBackground(new Background(new BackgroundFill( Paint.valueOf("black"), CornerRadii.EMPTY, Insets.EMPTY ))); } public Pane getInnerPane() { return innerPane; } }
Removes inline comment of resolved issue.
src/client/View.java
Removes inline comment of resolved issue.
Java
mit
fd1cf9b4962ff2058598b0598eba87aac8465a8e
0
bcgit/bc-java,bcgit/bc-java,bcgit/bc-java
package org.bouncycastle.cms; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.util.Iterable; public class RecipientInformationStore implements Iterable<RecipientInformation> { private final List all; //ArrayList[RecipientInformation] private final Map table = new HashMap(); // HashMap[RecipientID, ArrayList[RecipientInformation]] /** * Create a store containing a single RecipientInformation object. * * @param recipientInformation the signer information to contain. */ public RecipientInformationStore( RecipientInformation recipientInformation) { this.all = new ArrayList(1); this.all.add(recipientInformation); RecipientId sid = recipientInformation.getRID(); table.put(sid, all); } public RecipientInformationStore( Collection<RecipientInformation> recipientInfos) { Iterator it = recipientInfos.iterator(); while (it.hasNext()) { RecipientInformation recipientInformation = (RecipientInformation)it.next(); RecipientId rid = recipientInformation.getRID(); List list = (ArrayList)table.get(rid); if (list == null) { list = new ArrayList(1); table.put(rid, list); } list.add(recipientInformation); } this.all = new ArrayList(recipientInfos); } /** * Return the first RecipientInformation object that matches the * passed in selector. Null if there are no matches. * * @param selector to identify a recipient * @return a single RecipientInformation object. Null if none matches. */ public RecipientInformation get( RecipientId selector) { Collection list = getRecipients(selector); return list.size() == 0 ? null : (RecipientInformation)list.iterator().next(); } /** * Return the number of recipients in the collection. * * @return number of recipients identified. */ public int size() { return all.size(); } /** * Return all recipients in the collection * * @return a collection of recipients. */ public Collection<RecipientInformation> getRecipients() { return new ArrayList(all); } /** * Return possible empty collection with recipients matching the passed in RecipientId * * @param selector a recipient id to select against. * @return a collection of RecipientInformation objects. */ public Collection<RecipientInformation> getRecipients( RecipientId selector) { if (selector instanceof KeyTransRecipientId) { KeyTransRecipientId keyTrans = (KeyTransRecipientId)selector; X500Name issuer = keyTrans.getIssuer(); byte[] subjectKeyId = keyTrans.getSubjectKeyIdentifier(); if (issuer != null && subjectKeyId != null) { List<RecipientInformation> results = new ArrayList(); Collection<RecipientInformation> match1 = getRecipients(new KeyTransRecipientId(issuer, keyTrans.getSerialNumber())); if (match1 != null) { results.addAll(match1); } Collection<RecipientInformation> match2 = getRecipients(new KeyTransRecipientId(subjectKeyId)); if (match2 != null) { results.addAll(match2); } return results; } } List list = (ArrayList)table.get(selector); return list == null ? new ArrayList() : new ArrayList(list); } /** * Support method for Iterable where available. */ public Iterator<RecipientInformation> iterator() { return getRecipients().iterator(); } }
pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java
package org.bouncycastle.cms; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.util.*; import org.bouncycastle.util.Iterable; public class RecipientInformationStore implements Iterable<RecipientInformation> { private final List all; //ArrayList[RecipientInformation] private final Map table = new HashMap(); // HashMap[RecipientID, ArrayList[RecipientInformation]] /** * Create a store containing a single RecipientInformation object. * * @param recipientInformation the signer information to contain. */ public RecipientInformationStore( RecipientInformation recipientInformation) { this.all = new ArrayList(1); this.all.add(recipientInformation); RecipientId sid = recipientInformation.getRID(); table.put(sid, all); } public RecipientInformationStore( Collection<RecipientInformation> recipientInfos) { Iterator it = recipientInfos.iterator(); while (it.hasNext()) { RecipientInformation recipientInformation = (RecipientInformation)it.next(); RecipientId rid = recipientInformation.getRID(); List list = (ArrayList)table.get(rid); if (list == null) { list = new ArrayList(1); table.put(rid, list); } list.add(recipientInformation); } this.all = new ArrayList(recipientInfos); } /** * Return the first RecipientInformation object that matches the * passed in selector. Null if there are no matches. * * @param selector to identify a recipient * @return a single RecipientInformation object. Null if none matches. */ public RecipientInformation get( RecipientId selector) { Collection list = getRecipients(selector); return list.size() == 0 ? null : (RecipientInformation)list.iterator().next(); } /** * Return the number of recipients in the collection. * * @return number of recipients identified. */ public int size() { return all.size(); } /** * Return all recipients in the collection * * @return a collection of recipients. */ public Collection<RecipientInformation> getRecipients() { return new ArrayList(all); } /** * Return possible empty collection with recipients matching the passed in RecipientId * * @param selector a recipient id to select against. * @return a collection of RecipientInformation objects. */ public Collection<Recipient> getRecipients( RecipientId selector) { if (selector instanceof KeyTransRecipientId) { KeyTransRecipientId keyTrans = (KeyTransRecipientId)selector; X500Name issuer = keyTrans.getIssuer(); byte[] subjectKeyId = keyTrans.getSubjectKeyIdentifier(); if (issuer != null && subjectKeyId != null) { List results = new ArrayList(); Collection match1 = getRecipients(new KeyTransRecipientId(issuer, keyTrans.getSerialNumber())); if (match1 != null) { results.addAll(match1); } Collection match2 = getRecipients(new KeyTransRecipientId(subjectKeyId)); if (match2 != null) { results.addAll(match2); } return results; } } List list = (ArrayList)table.get(selector); return list == null ? new ArrayList() : new ArrayList(list); } /** * Support method for Iterable where available. */ public Iterator<RecipientInformation> iterator() { return getRecipients().iterator(); } }
fixed generic return type.
pkix/src/main/java/org/bouncycastle/cms/RecipientInformationStore.java
fixed generic return type.
Java
mit
b4624915f6d41bc44d523f80728bf4d140d68d41
0
danbuckland/income-tax-android,danbuckland/income-tax-android
package com.blocksolid.income; public class TaxCalculator { // 2015-16 Tax constants private static final int MAX_PERSONAL_ALLOWANCE = 1060000; // ยฃ10,600 private static final int PERSONAL_ALLOWANCE_THRESHOLD = 10000000; // ยฃ100,000 private static final int TAX_BASIC_RATE_THRESHOLD = 3178500; // ยฃ31,785 private static final int TAX_HIGHER_RATE_THRESHOLD = 15000000; // ยฃ150,000 private static final double TAX_BASIC_RATE = 0.2; // 20% private static final double TAX_HIGHER_RATE = 0.4; // 40% private static final double TAX_ADDITIONAL_RATE = 0.45; // 45% // 2015-16 National Insurance constants // All values and calculations assume National Insurance Category A private static final int LEL_NI = 582400; // ยฃ5,824 Lower Earnings Limit private static final int PT_NI = 806000; // ยฃ8,060 Primary Threshold private static final int ST_NI = 811200; // ยฃ8,112 Secondary Threshold private static final int UAP_NI = 4004000; // ยฃ40,040 Upper Accrual Point private static final int UST_NI = 4238500; // ยฃ42,385 Upper Secondary Threshold (under 21) private static final int UEL_NI = 4238500; // ยฃ42,385 Upper Earnings Limit private static final double LOWER_RATE_NI = 0.02; // 2.00% private static final double MIDDLE_RATE_NI = 0.0585; // 5.85% private static final double UPPER_RATE_NI = 0.106; // 10.60% private static final double TOP_RATE_NI = 0.12; // 12.00% int grossAnnualIncome = 0; int totalDeductions = 0; int netAnnualIncome = 0; // Tax int personalAllowance = MAX_PERSONAL_ALLOWANCE; int basicRateDeduction = 0; int higherRateDeduction = 0; int additionalRateDeduction = 0; int totalTaxDeductions = 0; // National Insurance int contributionBetweenLelAndPt = 0; int contributionBetweenPtAndUap = 0; int contributionBetweenUapAndUel = 0; int contributionAboveUel = 0; int nationalInsuranceContributions = 0; public TaxCalculator() { } public void setGrossAnnualIncome(int newGrossAnnualIncome) { grossAnnualIncome = newGrossAnnualIncome; // All calculations should be done each time the salary is set calculateNetAnnualIncome(); } public int getGrossAnnualIncome() { return grossAnnualIncome; } public int calculatePersonalAllowance() { if (grossAnnualIncome > PERSONAL_ALLOWANCE_THRESHOLD) { int difference = grossAnnualIncome - PERSONAL_ALLOWANCE_THRESHOLD; // ยฃ1 is removed for each ยฃ2 earned above the personal allowance // Remove the odd pound so that the difference can be divided by 2 if (difference % 200 > 0) { difference = difference - 100; } personalAllowance = MAX_PERSONAL_ALLOWANCE - (difference / 2); // If the calculation results in a negative number, set personal allowance to 0 if (personalAllowance < 0) { personalAllowance = 0; } } else { // Personal allowance set to the maximum if salary is below the threshold personalAllowance = MAX_PERSONAL_ALLOWANCE; } return personalAllowance; } public int calculateTotalDeductions() { totalDeductions = calculateTotalTaxDeductions() + calculateNationalInsuranceContributions(); return totalDeductions; } public int calculateTotalTaxDeductions() { // Important to reset these to 0 in case getter methods are added later for these basicRateDeduction = 0; higherRateDeduction = 0; additionalRateDeduction = 0; personalAllowance = calculatePersonalAllowance(); if (grossAnnualIncome <= personalAllowance) { return totalTaxDeductions = 0; } // Calculation basic rate tax deduction int assessedBasicRateThreshold = TAX_BASIC_RATE_THRESHOLD + personalAllowance; if (grossAnnualIncome <= assessedBasicRateThreshold) { basicRateDeduction = (int)(TAX_BASIC_RATE * (grossAnnualIncome - personalAllowance)); return totalTaxDeductions = basicRateDeduction; } else { basicRateDeduction = (int)(TAX_BASIC_RATE * (assessedBasicRateThreshold - personalAllowance)); } // Calculate higher rate tax deduction if (grossAnnualIncome <= TAX_HIGHER_RATE_THRESHOLD) { higherRateDeduction = (int)(TAX_HIGHER_RATE * (grossAnnualIncome - assessedBasicRateThreshold)); return totalTaxDeductions = basicRateDeduction + higherRateDeduction; } else { higherRateDeduction = (int)(TAX_HIGHER_RATE * (TAX_HIGHER_RATE_THRESHOLD - assessedBasicRateThreshold)); } // Calculate additional rate tax deduction additionalRateDeduction = (int)(TAX_ADDITIONAL_RATE * (grossAnnualIncome - TAX_HIGHER_RATE_THRESHOLD)); return totalTaxDeductions = basicRateDeduction + higherRateDeduction + additionalRateDeduction; } public int calculateNationalInsuranceContributions() { // Important to reset these to 0 here for future getter methods contributionBetweenLelAndPt = 0; contributionBetweenPtAndUap = 0; contributionBetweenUapAndUel = 0; contributionAboveUel = 0; if (grossAnnualIncome <= LEL_NI) { return nationalInsuranceContributions = 0; } // Calculate earnings between LEL_NI and PT_NI and multiply by 0% if (grossAnnualIncome <= PT_NI) { contributionBetweenLelAndPt = (grossAnnualIncome - LEL_NI) * 0; return nationalInsuranceContributions = contributionBetweenLelAndPt; } else { contributionBetweenLelAndPt = (PT_NI - LEL_NI)*0; } // Calculate earnings between PT_NI and UAP_NI and multiply by TOP_RATE_NI % if (grossAnnualIncome <= UAP_NI) { contributionBetweenPtAndUap = (int)((grossAnnualIncome - PT_NI) * TOP_RATE_NI); return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap; } else { contributionBetweenPtAndUap = (int)((UAP_NI - PT_NI) * TOP_RATE_NI); } // Calculate earnings between UAP and UEL and multiply by TOP_RATE_NI % if (grossAnnualIncome <= UEL_NI) { contributionBetweenUapAndUel = (int)((grossAnnualIncome - UAP_NI) * TOP_RATE_NI); return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap + contributionBetweenUapAndUel; } else { contributionBetweenUapAndUel = (int)((UEL_NI - UAP_NI) * TOP_RATE_NI); } // Calculate earnings above UEL and multiply by LOWER_RATE_NI % contributionAboveUel = (int)((grossAnnualIncome - UEL_NI) * LOWER_RATE_NI); // Add all the values together and return return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap + contributionBetweenUapAndUel + contributionAboveUel; } public int getTotalTaxDeductions() { return totalTaxDeductions; } public int getPersonalAllowance() { return personalAllowance; } public int getTotalDeductions() { return totalDeductions; } public int getNationalInsuranceContributions() { return nationalInsuranceContributions; } public void calculateNetAnnualIncome() { totalDeductions = calculateTotalDeductions(); netAnnualIncome = grossAnnualIncome - totalDeductions; } public int getNetAnnualIncome() { return netAnnualIncome; } }
app/src/main/java/com/blocksolid/income/TaxCalculator.java
package com.blocksolid.income; public class TaxCalculator { // 2015-16 Tax constants private static final int MAX_PERSONAL_ALLOWANCE = 1060000; // ยฃ10,600 private static final int PERSONAL_ALLOWANCE_THRESHOLD = 10000000; // ยฃ100,000 private static final int TAX_BASIC_RATE_THRESHOLD = 3178500; // ยฃ31,785 private static final int TAX_HIGHER_RATE_THRESHOLD = 15000000; // ยฃ150,000 private static final double TAX_BASIC_RATE = 0.2; // 20% private static final double TAX_HIGHER_RATE = 0.4; // 40% private static final double TAX_ADDITIONAL_RATE = 0.45; // 45% // 2015-16 National Insurance constants // All values and calculations assume National Insurance Category A private static final int LEL_NI = 582400; // ยฃ5,824 Lower Earnings Limit private static final int PT_NI = 806000; // ยฃ8,060 Primary Threshold private static final int ST_NI = 811200; // ยฃ8,112 Secondary Threshold private static final int UAP_NI = 4004000; // ยฃ40,040 Upper Accrual Point private static final int UST_NI = 4238500; // ยฃ42,385 Upper Secondary Threshold (under 21) private static final int UEL_NI = 4238500; // ยฃ42,385 Upper Earnings Limit private static final double LOWER_RATE_NI = 0.02; // 2.00% private static final double MIDDLE_RATE_NI = 0.0585; // 5.85% private static final double UPPER_RATE_NI = 0.106; // 10.60% private static final double TOP_RATE_NI = 0.12; // 12.00% int grossAnnualIncome = 0; int personalAllowance = MAX_PERSONAL_ALLOWANCE; int basicRateDeduction = 0; int higherRateDeduction = 0; int additionalRateDeduction = 0; int totalTaxDeductions = 0; int nationalInsuranceContributions = 0; int totalDeductions = 0; int netAnnualIncome = 0; public TaxCalculator() { } public void setGrossAnnualIncome(int newGrossAnnualIncome) { grossAnnualIncome = newGrossAnnualIncome; // All calculations should be done each time the salary is set calculateNetAnnualIncome(); } public int getGrossAnnualIncome() { return grossAnnualIncome; } public int calculatePersonalAllowance() { /** * The standard Personal Allowance is ยฃ10,600, which is the amount of income that tax will * not be paid on. * * A persons Personal Allowance may be bigger if they were born before 6 April 1938 or if * they get Blind Personโ€™s Allowance. * * The Personal Allowance goes down by ยฃ1 for every ยฃ2 that the adjusted net income is * above ยฃ100,000. This means the allowance is zero if a persons income is ยฃ121,200 or over. */ if (grossAnnualIncome > PERSONAL_ALLOWANCE_THRESHOLD) { int difference = grossAnnualIncome - PERSONAL_ALLOWANCE_THRESHOLD; // ยฃ1 is removed for each ยฃ2 earned above the personal allowance // Remove the odd pound so that the difference can be divided by 2 if (difference % 200 > 0) { difference = difference - 100; } personalAllowance = MAX_PERSONAL_ALLOWANCE - (difference / 2); // If the calculation results in a negative number, set personal allowance to 0 if (personalAllowance < 0) { personalAllowance = 0; } } else { // Personal allowance set to the maximum if salary is below the threshold personalAllowance = MAX_PERSONAL_ALLOWANCE; } return personalAllowance; } public int calculateTotalDeductions() { totalDeductions = calculateTotalTaxDeductions() + calculateNationalInsuranceContributions(); return totalDeductions; } public int calculateTotalTaxDeductions() { /** * If I have a salary of 180,000 * I need to calculate the 45% tax I pay on the amount over ยฃ150,000 -> (30000 * 0.45 = 13500) * I need to calculate the 40% tax I pay on the amount between ยฃ31,785 and ยฃ150,000 -> (118215 * 0.40 = 47286) * I need to calculate the 20% tax I pay on the amount between ยฃ0 and ยฃ31,785 -> (31785 * 0.20 = 6357) * I need to add these together to get the total amount deducted (13500 + 47286 + 6357 = 67143) * I need to subtract this from my starting salary to get my net income (180000 - 67143 = 112857) */ /** * If I have a salary of 100,000 * I need to calculate the 45% tax I pay on the amount over ยฃ150,000 -> (0 * 0.45 = 0) * I need to calculate the 40% tax I pay on the amount between ยฃ42,385 and ยฃ150,000 -> (57615 * 0.40 = 23046) * I need to calculate the 20% tax I pay on the amount between ยฃ10,600 and ยฃ42,385 -> (31785 * 0.20 = 6357) * I need to add these together to get the total amount deducted (0 + 23046 + 6357 = 29403) * I need to subtract this from my starting salary to get my net income (100000 - 29403 = 70597) */ // Calculate additional rate tax deduction if (grossAnnualIncome > TAX_HIGHER_RATE_THRESHOLD) { additionalRateDeduction = (int)(TAX_ADDITIONAL_RATE * (grossAnnualIncome - TAX_HIGHER_RATE_THRESHOLD)); } else { additionalRateDeduction = 0; } // Calculate higher rate tax deduction personalAllowance = calculatePersonalAllowance(); int assessedBasicRateThreshold = TAX_BASIC_RATE_THRESHOLD + personalAllowance; int newHigherRateThreshold; if (grossAnnualIncome > assessedBasicRateThreshold) { if (grossAnnualIncome > TAX_HIGHER_RATE_THRESHOLD) { // Possibly set a boolean here to avoid doing this same calculation twice newHigherRateThreshold = TAX_HIGHER_RATE_THRESHOLD; } else { newHigherRateThreshold = grossAnnualIncome; } higherRateDeduction = (int)(TAX_HIGHER_RATE * (newHigherRateThreshold - assessedBasicRateThreshold)); } else { higherRateDeduction = 0; } // Calculation basic rate tax deduction if (grossAnnualIncome > personalAllowance) { // If the amount of income breaches the basic rate threshold, then the amount over the // threshold needs to be excluded from the basic rate calculation if (grossAnnualIncome > assessedBasicRateThreshold) { int amountAboveBasicRate = grossAnnualIncome - assessedBasicRateThreshold; int amountEligibleForBasicRateTax = grossAnnualIncome - amountAboveBasicRate - personalAllowance; basicRateDeduction = (int)(TAX_BASIC_RATE * amountEligibleForBasicRateTax); } else { int amountEligibleForBasicRateTax = (grossAnnualIncome - personalAllowance); basicRateDeduction = (int)(TAX_BASIC_RATE * amountEligibleForBasicRateTax); } } else { basicRateDeduction = 0; } totalTaxDeductions = basicRateDeduction + higherRateDeduction + additionalRateDeduction; return totalTaxDeductions; } public int calculateNationalInsuranceContributions() { int contributionBetweenLelAndPt; int contributionBetweenPtAndUap; int contributionBetweenUapAndUel; int contributionAboveUel; nationalInsuranceContributions = 0; if (grossAnnualIncome < LEL_NI) { return nationalInsuranceContributions; } // Calculate earnings between LEL_NI and PT_NI and multiply by 0% if (grossAnnualIncome < PT_NI) { contributionBetweenLelAndPt = (grossAnnualIncome - LEL_NI) * 0; return nationalInsuranceContributions = contributionBetweenLelAndPt; } else { contributionBetweenLelAndPt = (PT_NI - LEL_NI)*0; } // Calculate earnings between PT_NI and UAP_NI and multiply by TOP_RATE_NI % if (grossAnnualIncome < UAP_NI) { contributionBetweenPtAndUap = (int) ((grossAnnualIncome - PT_NI) * TOP_RATE_NI); return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap; } else { contributionBetweenPtAndUap = (int) ((UAP_NI - PT_NI) * TOP_RATE_NI); } // Calculate earnings between UAP and UEL and multiply by TOP_RATE_NI % if (grossAnnualIncome <= UEL_NI) { contributionBetweenUapAndUel = (int) ((grossAnnualIncome - UAP_NI) * TOP_RATE_NI); return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap + contributionBetweenUapAndUel; } else { contributionBetweenUapAndUel = (int) ((UEL_NI - UAP_NI) * TOP_RATE_NI); } // Calculate earning above UEL and multiply by LOWER_RATE_NI % contributionAboveUel = (int)((grossAnnualIncome - UEL_NI) * LOWER_RATE_NI); // Add all the values together and return return nationalInsuranceContributions = contributionBetweenLelAndPt + contributionBetweenPtAndUap + contributionBetweenUapAndUel + contributionAboveUel; } public int getTotalTaxDeductions() { return totalTaxDeductions; } public int getPersonalAllowance() { return personalAllowance; } public int getTotalDeductions() { return totalDeductions; } public int getNationalInsuranceContributions() { return nationalInsuranceContributions; } public void calculateNetAnnualIncome() { totalDeductions = calculateTotalDeductions(); netAnnualIncome = grossAnnualIncome - totalDeductions; } public int getNetAnnualIncome() { return netAnnualIncome; } }
Refactor calculateTotalTaxDeductions method
app/src/main/java/com/blocksolid/income/TaxCalculator.java
Refactor calculateTotalTaxDeductions method
Java
agpl-3.0
90474fe50dfefe48b92a960e0a938dd979c274b1
0
quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,bhutchinson/kfs,kkronenb/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/kfs,smith750/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,quikkian-ua-devops/will-financials,smith750/kfs,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,UniversityOfHawaii/kfs,kuali/kfs,kuali/kfs,bhutchinson/kfs,bhutchinson/kfs,UniversityOfHawaii/kfs,kuali/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,quikkian-ua-devops/will-financials,kuali/kfs,quikkian-ua-devops/will-financials,smith750/kfs,kkronenb/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,smith750/kfs,quikkian-ua-devops/kfs,ua-eas/kfs-devops-automation-fork,ua-eas/kfs,kkronenb/kfs,kkronenb/kfs,bhutchinson/kfs
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community 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://www.opensource.org/licenses/ecl1.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 org.kuali.kfs.module.ar.web.struts; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.ar.ArKeyConstants; import org.kuali.kfs.module.ar.businessobject.ContractsGrantsSuspendedInvoiceSummaryReport; import org.kuali.kfs.module.ar.report.ContractsGrantsReportDataHolder; import org.kuali.kfs.module.ar.report.ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder; import org.kuali.kfs.module.ar.report.service.ContractsGrantsSuspendedInvoiceSummaryReportService; import org.kuali.kfs.sys.KFSConstants; import org.kuali.kfs.sys.KFSConstants.ReportGeneration; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.kns.lookup.Lookupable; import org.kuali.rice.kns.util.WebUtils; import org.kuali.rice.kns.web.ui.ResultRow; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.ObjectUtils; /** * Action class for for the Contracts and Grants Suspended Invoice Summary Report Lookup. */ public class ContractsGrantsSuspendedInvoiceSummaryReportLookupAction extends ContractsGrantsReportLookupAction { /** * This method implements the print functionality for the Contracts and Grants Suspended Invoice Summary Report Lookup. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward print(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContractsGrantsSuspendedInvoiceSummaryReportLookupForm cgSuspendedInvoiceSummaryReportLookupForm = (ContractsGrantsSuspendedInvoiceSummaryReportLookupForm) form; String methodToCall = findMethodToCall(form, request); if (methodToCall.equalsIgnoreCase("search")) { GlobalVariables.getUserSession().removeObjectsByPrefix(KRADConstants.SEARCH_METHOD); } Lookupable kualiLookupable = cgSuspendedInvoiceSummaryReportLookupForm.getLookupable(); if (kualiLookupable == null) { throw new RuntimeException("Lookupable is null."); } List<ContractsGrantsSuspendedInvoiceSummaryReport> displayList = new ArrayList<ContractsGrantsSuspendedInvoiceSummaryReport>(); List<ResultRow> resultTable = new ArrayList<ResultRow>(); // validate search parameters kualiLookupable.validateSearchParameters(cgSuspendedInvoiceSummaryReportLookupForm.getFields()); // this is for 200 limit. turn it off for report. boolean bounded = false; displayList = (List<ContractsGrantsSuspendedInvoiceSummaryReport>) kualiLookupable.performLookup(cgSuspendedInvoiceSummaryReportLookupForm, resultTable, bounded); Object sortIndexObject = GlobalVariables.getUserSession().retrieveObject(SORT_INDEX_SESSION_KEY); // set default sort index as 0 if (ObjectUtils.isNull(sortIndexObject)) { sortIndexObject = "0"; } // get sort property String sortPropertyName = getFieldNameForSorting(Integer.parseInt(sortIndexObject.toString()), "ContractsGrantsSuspendedInvoiceSummaryReport"); // sort list sortReport(displayList, sortPropertyName); // check field is valid for subtotal // this report doesn't have subtotal boolean isFieldSubtotalRequired = false; Map<String, KualiDecimal> subTotalMap = new HashMap<String, KualiDecimal>(); // build report ContractsGrantsReportDataHolder cgSuspendedInvoiceSummaryReportDataHolder = new ContractsGrantsReportDataHolder(); List<ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder> details = cgSuspendedInvoiceSummaryReportDataHolder.getDetails(); for (ContractsGrantsSuspendedInvoiceSummaryReport cgSuspendedInvoiceSummaryReportEntry : displayList) { ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder reportDetail = new ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder(); // set report data setReportDate(cgSuspendedInvoiceSummaryReportEntry, reportDetail); reportDetail.setDisplaySubtotalInd(false); details.add(reportDetail); } cgSuspendedInvoiceSummaryReportDataHolder.setDetails(details); // Avoid generating pdf if there were no search results were returned if (CollectionUtils.isEmpty(cgSuspendedInvoiceSummaryReportDataHolder.getDetails())){ GlobalVariables.getMessageMap().putInfo(KFSConstants.DOCUMENT_ERRORS, ArKeyConstants.NO_VALUES_RETURNED); return mapping.findForward(KFSConstants.MAPPING_BASIC); } // build search criteria for report buildReportForSearchCriteia(cgSuspendedInvoiceSummaryReportDataHolder.getSearchCriteria(), cgSuspendedInvoiceSummaryReportLookupForm.getFieldsForLookup(), ContractsGrantsSuspendedInvoiceSummaryReport.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String reportFileName = SpringContext.getBean(ContractsGrantsSuspendedInvoiceSummaryReportService.class).generateReport(cgSuspendedInvoiceSummaryReportDataHolder, baos); WebUtils.saveMimeOutputStreamAsFile(response, ReportGeneration.PDF_MIME_TYPE, baos, reportFileName + ReportGeneration.PDF_FILE_EXTENSION); return null; } /** * @param cgSuspendedInvoiceSummaryReportEntry * @param reportDetail */ private void setReportDate(ContractsGrantsSuspendedInvoiceSummaryReport cgSuspendedInvoiceSummaryReportEntry, ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder reportDetail) { reportDetail.setSuspenseCategory(cgSuspendedInvoiceSummaryReportEntry.getSuspensionCategoryCode()); reportDetail.setCategoryDescription(cgSuspendedInvoiceSummaryReportEntry.getCategoryDescription()); reportDetail.setTotalInvoicesSuspended(cgSuspendedInvoiceSummaryReportEntry.getTotalInvoicesSuspended()); } }
work/src/org/kuali/kfs/module/ar/web/struts/ContractsGrantsSuspendedInvoiceSummaryReportLookupAction.java
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community 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://www.opensource.org/licenses/ecl1.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 org.kuali.kfs.module.ar.web.struts; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.ar.businessobject.ContractsGrantsSuspendedInvoiceSummaryReport; import org.kuali.kfs.module.ar.report.ContractsGrantsReportDataHolder; import org.kuali.kfs.module.ar.report.ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder; import org.kuali.kfs.module.ar.report.service.ContractsGrantsSuspendedInvoiceSummaryReportService; import org.kuali.kfs.sys.KFSConstants.ReportGeneration; import org.kuali.kfs.sys.context.SpringContext; import org.kuali.rice.core.api.util.type.KualiDecimal; import org.kuali.rice.kns.lookup.Lookupable; import org.kuali.rice.kns.util.WebUtils; import org.kuali.rice.kns.web.ui.ResultRow; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.KRADConstants; import org.kuali.rice.krad.util.ObjectUtils; /** * Action class for for the Contracts and Grants Suspended Invoice Summary Report Lookup. */ public class ContractsGrantsSuspendedInvoiceSummaryReportLookupAction extends ContractsGrantsReportLookupAction { /** * This method implements the print functionality for the Contracts and Grants Suspended Invoice Summary Report Lookup. * * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward print(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ContractsGrantsSuspendedInvoiceSummaryReportLookupForm cgSuspendedInvoiceSummaryReportLookupForm = (ContractsGrantsSuspendedInvoiceSummaryReportLookupForm) form; String methodToCall = findMethodToCall(form, request); if (methodToCall.equalsIgnoreCase("search")) { GlobalVariables.getUserSession().removeObjectsByPrefix(KRADConstants.SEARCH_METHOD); } Lookupable kualiLookupable = cgSuspendedInvoiceSummaryReportLookupForm.getLookupable(); if (kualiLookupable == null) { throw new RuntimeException("Lookupable is null."); } List<ContractsGrantsSuspendedInvoiceSummaryReport> displayList = new ArrayList<ContractsGrantsSuspendedInvoiceSummaryReport>(); List<ResultRow> resultTable = new ArrayList<ResultRow>(); // validate search parameters kualiLookupable.validateSearchParameters(cgSuspendedInvoiceSummaryReportLookupForm.getFields()); // this is for 200 limit. turn it off for report. boolean bounded = false; displayList = (List<ContractsGrantsSuspendedInvoiceSummaryReport>) kualiLookupable.performLookup(cgSuspendedInvoiceSummaryReportLookupForm, resultTable, bounded); Object sortIndexObject = GlobalVariables.getUserSession().retrieveObject(SORT_INDEX_SESSION_KEY); // set default sort index as 0 if (ObjectUtils.isNull(sortIndexObject)) { sortIndexObject = "0"; } // get sort property String sortPropertyName = getFieldNameForSorting(Integer.parseInt(sortIndexObject.toString()), "ContractsGrantsSuspendedInvoiceSummaryReport"); // sort list sortReport(displayList, sortPropertyName); // check field is valid for subtotal // this report doesn't have subtotal boolean isFieldSubtotalRequired = false; Map<String, KualiDecimal> subTotalMap = new HashMap<String, KualiDecimal>(); // build report ContractsGrantsReportDataHolder cgSuspendedInvoiceSummaryReportDataHolder = new ContractsGrantsReportDataHolder(); List<ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder> details = cgSuspendedInvoiceSummaryReportDataHolder.getDetails(); for (ContractsGrantsSuspendedInvoiceSummaryReport cgSuspendedInvoiceSummaryReportEntry : displayList) { ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder reportDetail = new ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder(); // set report data setReportDate(cgSuspendedInvoiceSummaryReportEntry, reportDetail); reportDetail.setDisplaySubtotalInd(false); details.add(reportDetail); } cgSuspendedInvoiceSummaryReportDataHolder.setDetails(details); // build search criteria for report buildReportForSearchCriteia(cgSuspendedInvoiceSummaryReportDataHolder.getSearchCriteria(), cgSuspendedInvoiceSummaryReportLookupForm.getFieldsForLookup(), ContractsGrantsSuspendedInvoiceSummaryReport.class); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String reportFileName = SpringContext.getBean(ContractsGrantsSuspendedInvoiceSummaryReportService.class).generateReport(cgSuspendedInvoiceSummaryReportDataHolder, baos); WebUtils.saveMimeOutputStreamAsFile(response, ReportGeneration.PDF_MIME_TYPE, baos, reportFileName + ReportGeneration.PDF_FILE_EXTENSION); return null; } /** * @param cgSuspendedInvoiceSummaryReportEntry * @param reportDetail */ private void setReportDate(ContractsGrantsSuspendedInvoiceSummaryReport cgSuspendedInvoiceSummaryReportEntry, ContractsGrantsSuspendedInvoiceSummaryReportDetailDataHolder reportDetail) { reportDetail.setSuspenseCategory(cgSuspendedInvoiceSummaryReportEntry.getSuspensionCategoryCode()); reportDetail.setCategoryDescription(cgSuspendedInvoiceSummaryReportEntry.getCategoryDescription()); reportDetail.setTotalInvoicesSuspended(cgSuspendedInvoiceSummaryReportEntry.getTotalInvoicesSuspended()); } }
KFSTP-1141 suspended invoice summary report - don't generate pdf if no results were returned from search
work/src/org/kuali/kfs/module/ar/web/struts/ContractsGrantsSuspendedInvoiceSummaryReportLookupAction.java
KFSTP-1141 suspended invoice summary report - don't generate pdf if no results were returned from search
Java
agpl-3.0
45a7ba75a76c1a86f3a871ede89f146fd9685f4c
0
rafaelsisweb/restheart,rafaelsisweb/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart
/* * RESTHeart - the data REST API server * Copyright (C) 2014 - 2015 SoftInstigate Srl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.restheart.handlers; import org.restheart.utils.HttpStatus; import io.undertow.server.HttpServerExchange; import io.undertow.util.HttpString; /** * * @author Andrea Di Cesare <[email protected]> */ public class OptionsHandler extends PipedHttpHandler { /** * Creates a new instance of OptionsHandler * * OPTIONS is used in CORS preflight phase and needs to be outside the * security zone (i.e. not Authorization header required) It is important * that OPTIONS responds to any resource URL, regardless its existance: This * is because OPTIONS http://restheart.org/employees/tofire/andrea shall not * give any information * * The Access-Control-Allow-Methods header indicates, as part of the * response to a preflight request, which methods can be used during the * actual request. * * @param next */ public OptionsHandler(PipedHttpHandler next) { super(next); } /** * * @param exchange * @param context * @throws Exception */ @Override public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception { if (!(context.getMethod() == RequestContext.METHOD.OPTIONS)) { getNext().handleRequest(exchange, context); return; } if (null != context.getType()) switch (context.getType()) { case ROOT: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case DB: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case COLLECTION: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, POST, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case FILES_BUCKET: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, POST, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case DOCUMENT: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, If-None-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case FILE: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, If-None-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case INDEX: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "PUT") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; case COLLECTION_INDEXES: exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); break; default: break; } exchange.setResponseCode(HttpStatus.SC_OK); exchange.endExchange(); } }
src/main/java/org/restheart/handlers/OptionsHandler.java
/* * RESTHeart - the data REST API server * Copyright (C) 2014 - 2015 SoftInstigate Srl * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.restheart.handlers; import org.restheart.utils.HttpStatus; import io.undertow.server.HttpServerExchange; import io.undertow.util.HttpString; /** * * @author Andrea Di Cesare <[email protected]> */ public class OptionsHandler extends PipedHttpHandler { /** * Creates a new instance of OptionsHandler * * OPTIONS is used in CORS preflight phase and needs to be outside the * security zone (i.e. not Authorization header required) It is important * that OPTIONS responds to any resource URL, regardless its existance: This * is because OPTIONS http://restheart.org/employees/tofire/andrea shall not * give any information * * The Access-Control-Allow-Methods header indicates, as part of the * response to a preflight request, which methods can be used during the * actual request. * * @param next */ public OptionsHandler(PipedHttpHandler next) { super(next); } /** * * @param exchange * @param context * @throws Exception */ @Override public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception { if (!(context.getMethod() == RequestContext.METHOD.OPTIONS)) { getNext().handleRequest(exchange, context); return; } if (context.getType() == RequestContext.TYPE.ROOT) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.DB) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.COLLECTION) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, POST, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.FILES_BUCKET) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, POST, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.DOCUMENT) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, PATCH, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, If-None-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.FILE) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET, PUT, DELETE, OPTIONS") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, If-Match, If-None-Match, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.INDEX) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "PUT") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } else if (context.getType() == RequestContext.TYPE.COLLECTION_INDEXES) { exchange.getResponseHeaders() .put(HttpString.tryFromString("Access-Control-Allow-Methods"), "GET") .put(HttpString.tryFromString("Access-Control-Allow-Headers"), "Accept, Accept-Encoding, Authorization, Content-Length, Content-Type, Host, Origin, X-Requested-With, User-Agent, No-Auth-Challenge"); } exchange.setResponseCode(HttpStatus.SC_OK); exchange.endExchange(); } }
Convert chain of IFs to switch statement
src/main/java/org/restheart/handlers/OptionsHandler.java
Convert chain of IFs to switch statement
Java
agpl-3.0
54fb2e0238c38490985199b221a3c547727bdf55
0
deepstupid/sphinx5
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.frontend; /** * A Data object that holds data of primitive type double. */ public class DoubleData implements Data, Cloneable { private double[] values; private int sampleRate; private long firstSampleNumber; private long collectTime; /** * Constructs a Data object with the given values, collect time, * and first sample number. * * @param values the data values * @param sampleRate the sample rate of the data * @param collectTime the time at which this data is collected * @param firstSampleNumber the position of the first sample in the * original data */ public DoubleData(double[] values, int sampleRate, long collectTime, long firstSampleNumber) { this.values = values; this.sampleRate = sampleRate; this.collectTime = collectTime; this.firstSampleNumber = firstSampleNumber; } /** * Returns a string that describes this DoubleData. * * @return a string that describes this DoubleData */ public String toString() { return ("DoubleData: " + sampleRate + "Hz, first sample #: " + firstSampleNumber + ", collect time: " + collectTime); } /** * Returns the values of this DoubleData object. * * @return the values */ public double[] getValues() { return values; } /** * Returns the sample rate of the data. * * @return the sample rate of the data */ public int getSampleRate() { return sampleRate; } /** * Returns the position of the first sample in the original data. * The very first sample number is zero. * * @return the position of the first sample in the original data */ public long getFirstSampleNumber() { return firstSampleNumber; } /** * Returns the time in milliseconds at which the audio data is collected. * * @return the difference, in milliseconds, between the time the * audio data is collected and midnight, January 1, 1970 */ public long getCollectTime() { return collectTime; } /** * Returns a clone of this Data object. * * @return a clone of this data object */ public Object clone() { try { Data data = (Data) super.clone(); return data; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } }
edu/cmu/sphinx/frontend/DoubleData.java
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.frontend; /** * A Data object that holds data of primitive type double. */ public class DoubleData implements Data, Cloneable { private double[] values; private int sampleRate; private long firstSampleNumber; private long collectTime; /** * Constructs a Data object with the given values, collect time, * and first sample number. * * @param values the data values * @param sampleRate the sample rate of the data * @param collectTime the time at which this data is collected * @param firstSampleNumber the position of the first sample in the * original data */ public DoubleData(double[] values, int sampleRate, long collectTime, long firstSampleNumber) { this.values = values; this.sampleRate = sampleRate; this.collectTime = collectTime; this.firstSampleNumber = firstSampleNumber; } /** * Returns a string that describes this DoubleData. * * @returns a string that describes this DoubleData */ public String toString() { return ("DoubleData: " + sampleRate + "Hz, first sample #: " + firstSampleNumber + ", collect time: " + collectTime); } /** * Returns the values of this DoubleData object. * * @return the values */ public double[] getValues() { return values; } /** * Returns the sample rate of the data. * * @return the sample rate of the data */ public int getSampleRate() { return sampleRate; } /** * Returns the position of the first sample in the original data. * The very first sample number is zero. * * @return the position of the first sample in the original data */ public long getFirstSampleNumber() { return firstSampleNumber; } /** * Returns the time in milliseconds at which the audio data is collected. * * @return the difference, in milliseconds, between the time the * audio data is collected and midnight, January 1, 1970 */ public long getCollectTime() { return collectTime; } /** * Returns a clone of this Data object. * * @return a clone of this data object */ public Object clone() { try { Data data = (Data) super.clone(); return data; } catch (CloneNotSupportedException e) { throw new InternalError(e.toString()); } } }
Fixed javadoc warning. git-svn-id: a8b04003a33e1d3e001b9d20391fa392a9f62d91@2758 94700074-3cef-4d97-a70e-9c8c206c02f5
edu/cmu/sphinx/frontend/DoubleData.java
Fixed javadoc warning.
Java
lgpl-2.1
3b9ae086753b0e9ae563450ef45049f9778a289c
0
adamallo/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc
/* * TreeAnnotator.java * * Copyright (c) 2002-2015 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.tools; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.evolution.io.Importer; import dr.evolution.io.NewickImporter; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.tree.*; import dr.evolution.util.TaxonList; import dr.geo.contouring.ContourMaker; import dr.geo.contouring.ContourPath; import dr.geo.contouring.ContourWithSynder; import dr.inference.trace.TraceCorrelation; import dr.inference.trace.TraceType; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import jam.console.ConsoleApplication; import org.rosuda.JRI.REXP; import org.rosuda.JRI.RVector; import org.rosuda.JRI.Rengine; import javax.swing.*; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * @author Alexei Drummond * @author Andrew Rambaut */ public class TreeAnnotator { private final static Version version = new BeastVersion(); private final static boolean USE_R = false; private static boolean forceIntegerToDiscrete = false; private static boolean computeESS = false; private double maxState = 1; enum Target { MAX_CLADE_CREDIBILITY("Maximum clade credibility tree"), //MAX_SUM_CLADE_CREDIBILITY("Maximum sum of clade credibilities"), USER_TARGET_TREE("User target tree"); String desc; Target(String s) { desc = s; } public String toString() { return desc; } } enum HeightsSummary { MEDIAN_HEIGHTS("Median heights"), MEAN_HEIGHTS("Mean heights"), KEEP_HEIGHTS("Keep target heights"), CA_HEIGHTS("Common Ancestor heights"); String desc; HeightsSummary(String s) { desc = s; } public String toString() { return desc; } } // Messages to stderr, output to stdout private static PrintStream progressStream = System.err; private final String location1Attribute = "longLat1"; private final String location2Attribute = "longLat2"; private final String locationOutputAttribute = "location"; /** * Burnin can be specified as the number of trees or the number of states * (one or other should be zero). * @param burninTrees * @param burninStates * @param heightsOption * @param posteriorLimit * @param hpd2D * @param targetOption * @param targetTreeFileName * @param inputFileName * @param outputFileName * @throws IOException */ public TreeAnnotator(final int burninTrees, final long burninStates, HeightsSummary heightsOption, double posteriorLimit, double[] hpd2D, Target targetOption, String targetTreeFileName, String inputFileName, String outputFileName ) throws IOException { this.posteriorLimit = posteriorLimit; this.hpd2D = hpd2D; attributeNames.add("height"); attributeNames.add("length"); CladeSystem cladeSystem = new CladeSystem(); int burnin = -1; totalTrees = 10000; totalTreesUsed = 0; progressStream.println("Reading trees (bar assumes 10,000 trees)..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); long stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; if (targetOption != Target.USER_TARGET_TREE) { cladeSystem = new CladeSystem(); FileReader fileReader = new FileReader(inputFileName); TreeImporter importer = new NexusImporter(fileReader, true); try { totalTrees = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); long state = Long.MAX_VALUE; if (burninStates > 0) { // if burnin has been specified in states, try to parse it out... String name = tree.getId().trim(); if (name != null && name.length() > 0 && name.startsWith("STATE_")) { state = Long.parseLong(name.split("_")[1]); maxState = state; } } if (totalTrees >= burninTrees && state >= burninStates) { // if either of the two burnin thresholds have been reached... if (burnin < 0) { // if this is the first time this point has been reached, // record the number of trees this represents for future use... burnin = totalTrees; } cladeSystem.add(tree, false); totalTreesUsed += 1; } if (totalTrees > 0 && totalTrees % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } totalTrees++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } fileReader.close(); progressStream.println(); progressStream.println(); if (totalTrees < 1) { System.err.println("No trees"); return; } if (totalTreesUsed <= 1) { if (burnin > 0) { System.err.println("No trees to use: burnin too high"); return; } } cladeSystem.calculateCladeCredibilities(totalTreesUsed); progressStream.println("Total trees read: " + totalTrees); if (burninTrees > 0) { progressStream.println("Ignoring first " + burninTrees + " trees" + (burninStates > 0 ? " (" + burninStates + " states)." : "." )); } else if (burninStates > 0) { progressStream.println("Ignoring first " + burninStates + " states (" + burnin + " trees)."); } progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size()); progressStream.println(); } MutableTree targetTree = null; switch (targetOption) { case USER_TARGET_TREE: { if (targetTreeFileName != null) { progressStream.println("Reading user specified target tree, " + targetTreeFileName); NexusImporter importer = new NexusImporter(new FileReader(targetTreeFileName)); try { Tree tree = importer.importNextTree(); if (tree == null) { NewickImporter x = new NewickImporter(new FileReader(targetTreeFileName)); tree = x.importNextTree(); } if (tree == null) { System.err.println("No tree in target nexus or newick file " + targetTreeFileName); return; } targetTree = new FlexibleTree(tree); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } break; } case MAX_CLADE_CREDIBILITY: { progressStream.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName /*, false*/)); break; } // case MAX_SUM_CLADE_CREDIBILITY: { // progressStream.println("Finding maximum sum clade credibility tree..."); // targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); // break; // } default: throw new IllegalArgumentException("Unknown targetOption"); } progressStream.println("Collecting node information..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; FileReader fileReader = new FileReader(inputFileName); NexusImporter importer = new NexusImporter(fileReader); // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below cladeSystem = new CladeSystem(targetTree); totalTreesUsed = 0; try { boolean firstTree = true; int counter = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { if (firstTree) { setupAttributes(tree); firstTree = false; } cladeSystem.collectAttributes(tree); totalTreesUsed += 1; } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); //progressStream.println("totalTreesUsed=" + totalTreesUsed); cladeSystem.calculateCladeCredibilities(totalTreesUsed); } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } progressStream.println(); progressStream.println(); fileReader.close(); progressStream.println("Annotating target tree..."); try { cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); if( heightsOption == HeightsSummary.CA_HEIGHTS ) { setTreeHeightsByCA(targetTree, inputFileName, burnin); } } catch (Exception e) { System.err.println("Error annotating tree: " + e.getMessage() + "\nPlease check the tree log file format."); return; } progressStream.println("Writing annotated tree...."); try { final PrintStream stream = outputFileName != null ? new PrintStream(new FileOutputStream(outputFileName)) : System.out; new NexusExporter(stream).exportTree(targetTree); } catch (Exception e) { System.err.println("Error to write annotated tree file: " + e.getMessage()); return; } } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { while (iter.hasNext()) { String name = (String) iter.next(); attributeNames.add(name); } } } for (TreeAnnotationPlugin plugin : plugins) { Set<String> claimed = plugin.setAttributeNames(attributeNames); attributeNames.removeAll(claimed); } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName /*, boolean useSumCladeCredibility */) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; progressStream.println("Analyzing " + totalTreesUsed + " trees..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; int bestTreeNumber = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName), true); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem /*, useSumCladeCredibility*/); // progressStream.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; bestTreeNumber = counter + 1; } } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } progressStream.println(); progressStream.println(); progressStream.println("Best tree: " + bestTree.getId() + " (tree number " + bestTreeNumber + ")"); // if (useSumCladeCredibility) { // progressStream.println("Highest Sum Clade Credibility: " + bestScore); // } else { progressStream.println("Highest Log Clade Credibility: " + bestScore); // } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem /*, boolean useSumCladeCredibility*/) { // if (useSumCladeCredibility) { // return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); // } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); // } } private class CladeSystem { // // Public stuff // /** */ public CladeSystem() { } /** */ public CladeSystem(Tree targetTree) { this.targetTree = targetTree; add(targetTree, true); } /** * adds all the clades in the tree */ public void add(Tree tree, boolean includeTips) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), includeTips); } // // public Clade getClade(NodeRef node) { // return null; // } private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { addClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(addClades(tree, node1, includeTips)); } addClade(bits); } return bits; } private void addClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); } public void collectAttributes(Tree tree) { collectAttributes(tree, tree.getRoot()); } private BitSet collectAttributes(Tree tree, NodeRef node) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); if (index < 0) { throw new IllegalArgumentException("Taxon, " + tree.getNodeTaxon(node).getId() + ", not found in target tree"); } bits.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(collectAttributes(tree, node1)); } } collectAttributesForClade(bits, tree, node); return bits; } private void collectAttributesForClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = cladeMap.get(bits); if (clade != null) { if (clade.attributeValues == null) { clade.attributeValues = new ArrayList<Object[]>(); } int i = 0; Object[] values = new Object[attributeNames.size()]; for (String attributeName : attributeNames) { boolean processed = false; if (!processed) { Object value; if (attributeName.equals("height")) { value = tree.getNodeHeight(node); } else if (attributeName.equals("length")) { value = tree.getBranchLength(node); // AR - we deal with this once everything // } else if (attributeName.equals(location1Attribute)) { // // If this is one of the two specified bivariate location names then // // merge this and the other one into a single array. // Object value1 = tree.getNodeAttribute(node, attributeName); // Object value2 = tree.getNodeAttribute(node, location2Attribute); // // value = new Object[]{value1, value2}; // } else if (attributeName.equals(location2Attribute)) { // // do nothing - already dealt with this... // value = null; } else { value = tree.getNodeAttribute(node, attributeName); if (value instanceof String && ((String) value).startsWith("\"")) { value = ((String) value).replaceAll("\"", ""); } } //if (value == null) { // progressStream.println("attribute " + attributeNames[i] + " is null."); //} values[i] = value; } i++; } clade.attributeValues.add(values); //progressStream.println(clade + " " + clade.getValuesSize()); clade.setCount(clade.getCount() + 1); } } public Map getCladeMap() { return cladeMap; } public void calculateCladeCredibilities(int totalTreesUsed) { for (Clade clade : cladeMap.values()) { if (clade.getCount() > totalTreesUsed) { throw new AssertionError("clade.getCount=(" + clade.getCount() + ") should be <= totalTreesUsed = (" + totalTreesUsed + ")"); } clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed); } } // public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { // // double sum = 0.0; // // if (tree.isExternal(node)) { // // int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); // bits.set(index); // } else { // // BitSet bits2 = new BitSet(); // for (int i = 0; i < tree.getChildCount(node); i++) { // // NodeRef node1 = tree.getChild(node, i); // // sum += getSumCladeCredibility(tree, node1, bits2); // } // // sum += getCladeCredibility(bits2); // // if (bits != null) { // bits.or(bits2); // } // } // // return sum; // } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, HeightsSummary heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, HeightsSummary heightsOption) { Clade clade = cladeMap.get(bits); assert clade != null : "Clade missing?"; boolean filter = false; if (!isTip) { final double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } int i = 0; for (String attributeName : attributeNames) { if (clade.attributeValues != null && clade.attributeValues.size() > 0) { double[] values = new double[clade.attributeValues.size()]; HashMap<Object, Integer> hashMap = new HashMap<Object, Integer>(); Object[] v = clade.attributeValues.get(0); if (v[i] != null) { final boolean isHeight = attributeName.equals("height"); boolean isBoolean = v[i] instanceof Boolean; boolean isDiscrete = v[i] instanceof String; if (forceIntegerToDiscrete && v[i] instanceof Integer) isDiscrete = true; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; final boolean isArray = v[i] instanceof Object[]; boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double; // This is Java, friends - first value type does not imply all. if (isDoubleArray) { for (Object n : (Object[]) v[i]) { if (!(n instanceof Double)) { isDoubleArray = false; break; } } } // todo Handle other types of arrays double[][] valuesArray = null; double[] minValueArray = null; double[] maxValueArray = null; int lenArray = 0; if (isDoubleArray) { lenArray = ((Object[]) v[i]).length; valuesArray = new double[lenArray][clade.attributeValues.size()]; minValueArray = new double[lenArray]; maxValueArray = new double[lenArray]; for (int k = 0; k < lenArray; k++) { minValueArray[k] = Double.MAX_VALUE; maxValueArray[k] = -Double.MAX_VALUE; } } for (int j = 0; j < clade.attributeValues.size(); j++) { Object value = clade.attributeValues.get(j)[i]; if (isDiscrete) { final Object s = value; if (hashMap.containsKey(s)) { hashMap.put(s, hashMap.get(s) + 1); } else { hashMap.put(s, 1); } } else if (isBoolean) { values[j] = (((Boolean) value) ? 1.0 : 0.0); } else if (isDoubleArray) { // Forcing to Double[] causes a cast exception. MAS Object[] array = (Object[]) value; for (int k = 0; k < lenArray; k++) { valuesArray[k][j] = ((Double) array[k]); if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j]; if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j]; } } else { // Ignore other (unknown) types if (value instanceof Number) { values[j] = ((Number) value).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } } if (isHeight) { if (heightsOption == HeightsSummary.MEAN_HEIGHTS) { final double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) { final double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { boolean processed = false; for (TreeAnnotationPlugin plugin : plugins) { if (plugin.handleAttribute(tree, node, attributeName, values)) { processed = true; } } if (!processed) { if (!isDiscrete) { if (!isDoubleArray) annotateMeanAttribute(tree, node, attributeName, values); else { for (int k = 0; k < lenArray; k++) { annotateMeanAttribute(tree, node, attributeName + (k + 1), valuesArray[k]); } } } else { annotateModeAttribute(tree, node, attributeName, hashMap); annotateFrequencyAttribute(tree, node, attributeName, hashMap); } if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); if (computeESS == true) { annotateESSAttribute(tree, node, attributeName + "_ESS", values); } } if (isDoubleArray) { String name = attributeName; // todo // if (name.equals(location1Attribute)) { // name = locationOutputAttribute; // } boolean want2d = processBivariateAttributes && lenArray == 2; if (name.equals("dmv")) { // terrible hack want2d = false; } for (int k = 0; k < lenArray; k++) { if (minValueArray[k] < maxValueArray[k]) { annotateMedianAttribute(tree, node, name + (k + 1) + "_median", valuesArray[k]); annotateRangeAttribute(tree, node, name + (k + 1) + "_range", valuesArray[k]); if (!want2d) annotateHPDAttribute(tree, node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]); } } // 2D contours if (want2d) { boolean variationInFirst = (minValueArray[0] < maxValueArray[0]); boolean variationInSecond = (minValueArray[1] < maxValueArray[1]); if (variationInFirst && !variationInSecond) annotateHPDAttribute(tree, node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]); if (variationInSecond && !variationInFirst) annotateHPDAttribute(tree, node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]); if (variationInFirst && variationInSecond){ for (int l = 0; l < hpd2D.length; l++) { if (hpd2D[l] > 1) { System.err.println("no HPD for proportion > 1 (" + hpd2D[l] + ")"); } else if (hpd2D[l] < 0){ System.err.println("no HPD for proportion < 0 (" + hpd2D[l] + ")"); } else { annotate2DHPDAttribute(tree, node, name, "_" + (int) (100 * hpd2D[l]) + "%HPD", hpd2D[l], valuesArray); } } } } } } } } } i++; } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, mean); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, median); } private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { Object mode = null; int maxCount = 0; int totalCount = 0; int countInMode = 1; for (Object key : values.keySet()) { int thisCount = values.get(key); if (thisCount == maxCount) { // I hope this is the intention mode = mode.toString().concat("+" + key); countInMode++; } else if (thisCount > maxCount) { mode = key; maxCount = thisCount; countInMode = 1; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount * countInMode; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", freq); } private void annotateFrequencyAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { double totalCount = 0; Set keySet = values.keySet(); int length = keySet.size(); String[] name = new String[length]; Double[] freq = new Double[length]; int index = 0; for (Object key : values.keySet()) { name[index] = key.toString(); freq[index] = new Double(values.get(key)); totalCount += freq[index]; index++; } for (int i = 0; i < length; i++) freq[i] /= totalCount; tree.setNodeAttribute(node, label + ".set", name); tree.setNodeAttribute(node, label + ".set.prob", freq); } private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{min, max}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{lower, upper}); } private void annotateESSAttribute(MutableTree tree, NodeRef node, String label, double[] values) { // array --> list (to construct traceCorrelation obj) List<Double> values2 = new ArrayList<Double>(0); for (int i = 0; i < values.length; i++) { values2.add(values[i]); } TraceType traceType = TraceType.REAL; // maxState / totalTrees = stepSize for ESS int logStep = (int) (maxState / totalTrees); TraceCorrelation traceCorrelation = new TraceCorrelation(values2, traceType, logStep); double ESS = traceCorrelation.getESS(); tree.setNodeAttribute(node, label, ESS); } // todo Move rEngine to outer class; create once. Rengine rEngine = null; private final String[] rArgs = {"--no-save"}; // private int called = 0; private final String[] rBootCommands = { "library(MASS)", "makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" + "post1 = kde2d(var1, var2, n = n, h=h); " + // This had h=h in argument "dx = diff(post1$x[1:2]); " + "dy = diff(post1$y[1:2]); " + "sz = sort(post1$z); " + "c1 = cumsum(sz) * dx * dy; " + "levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " + "line = contourLines(post1$x, post1$y, post1$z, level = levels); " + "return(line) }" }; private String makeRString(double[] values) { StringBuffer sb = new StringBuffer("c("); sb.append(values[0]); for (int i = 1; i < values.length; i++) { sb.append(","); sb.append(values[i]); } sb.append(")"); return sb.toString(); } public static final String CORDINATE = "cordinates"; // private String formattedLocation(double loc1, double loc2) { // return formattedLocation(loc1) + "," + formattedLocation(loc2); // } private String formattedLocation(double x) { return String.format("%5.8f", x); } private void annotate2DHPDAttribute(MutableTree tree, NodeRef node, String preLabel, String postLabel, double hpd, double[][] values) { int N = 50; if (USE_R) { // Uses R-Java interface, and the HPD routines from 'emdbook' and 'coda' if (rEngine == null) { if (!Rengine.versionCheck()) { throw new RuntimeException("JRI library version mismatch"); } rEngine = new Rengine(rArgs, false, null); if (!rEngine.waitForR()) { throw new RuntimeException("Cannot load R"); } for (String command : rBootCommands) { rEngine.eval(command); } } // todo Need a good method to pick grid size REXP x = rEngine.eval("makeContour(" + makeRString(values[0]) + "," + makeRString(values[1]) + "," + hpd + "," + N + ")"); RVector contourList = x.asVector(); int numberContours = contourList.size(); if (numberContours > 1) { System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } tree.setNodeAttribute(node, preLabel + postLabel + "_modality", numberContours); StringBuffer output = new StringBuffer(); for (int i = 0; i < numberContours; i++) { output.append("\n<" + CORDINATE + ">\n"); RVector oneContour = contourList.at(i).asVector(); double[] xList = oneContour.at(1).asDoubleArray(); double[] yList = oneContour.at(2).asDoubleArray(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); } } else { // do not use R // KernelDensityEstimator2D kde = new KernelDensityEstimator2D(values[0], values[1], N); //ContourMaker kde = new ContourWithSynder(values[0], values[1], N); boolean bandwidthLimit = false; ContourMaker kde = new ContourWithSynder(values[0], values[1], bandwidthLimit); ContourPath[] paths = kde.getContourPaths(hpd); tree.setNodeAttribute(node, preLabel + postLabel + "_modality", paths.length); if (paths.length > 1) { System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } StringBuffer output = new StringBuffer(); int i = 0; for (ContourPath p : paths) { output.append("\n<" + CORDINATE + ">\n"); double[] xList = p.getAllX(); double[] yList = p.getAllY(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); i++; } } } public BitSet removeClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { removeClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(removeClades(tree, node1, includeTips)); } removeClade(bits); } return bits; } private void removeClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade != null) { clade.setCount(clade.getCount() - 1); } } // Get tree clades as bitSets on target taxa // codes is an array of existing BitSet objects, which are reused void getTreeCladeCodes(Tree tree, BitSet[] codes) { getTreeCladeCodes(tree, tree.getRoot(), codes); } int getTreeCladeCodes(Tree tree, NodeRef node, BitSet[] codes) { final int inode = node.getNumber(); codes[inode].clear(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); codes[inode].set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { final NodeRef child = tree.getChild(node, i); final int childIndex = getTreeCladeCodes(tree, child, codes); codes[inode].or(codes[childIndex]); } } return inode; } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } public String toString() { return "clade " + bits.toString(); } int count; double credibility; BitSet bits; List<Object[]> attributeValues = null; } // // Private stuff // TaxonList taxonList = null; Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); Tree targetTree; } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; //PL: double hpd2D = 0.80; double[] hpd2D = {0.80}; private final List<TreeAnnotationPlugin> plugins = new ArrayList<TreeAnnotationPlugin>(); Set<String> attributeNames = new HashSet<String>(); TaxonList taxa = null; static boolean processBivariateAttributes = false; static { try { System.loadLibrary("jri"); processBivariateAttributes = true; System.err.println("JRI loaded. Will process bivariate attributes"); } catch (UnsatisfiedLinkError e) { // System.err.print("JRI not available. "); if (!USE_R) { processBivariateAttributes = true; // System.err.println("Using Java bivariate attributes"); } else { // System.err.println("Will not process bivariate attributes"); } } } public static void printTitle() { progressStream.println(); centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output analysis", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); progressStream.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("[email protected]", 60); progressStream.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("[email protected]", 60); progressStream.println(); progressStream.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { progressStream.print(" "); } progressStream.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]"); progressStream.println(); progressStream.println(" Example: treeannotator test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -heights mean test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -target map.tree test.trees out.txt"); progressStream.println(); } public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException { List<Double> returnList = new ArrayList<Double>(); StringTokenizer st = new StringTokenizer(inString,","); while(st.hasMoreTokens()) { try { returnList.add(Double.parseDouble(st.nextToken())); } catch (NumberFormatException e) { throw new Arguments.ArgumentException(); } } if (returnList.size()>0) { double[] doubleArray = new double[returnList.size()]; for(int i=0; i<doubleArray.length; i++) doubleArray[i] = returnList.get(i); return doubleArray; } return null; } //Main method public static void main(String[] args) throws IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "TreeAnnotator " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:[email protected]\">[email protected]</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:[email protected]\">[email protected]</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http://beast.community\">http://beast.community</a></p>" + "</center></html>"; new ConsoleApplication(nameString, aboutString, icon, true); // The ConsoleApplication will have overridden System.out so set progressStream // to capture the output to the window: progressStream = System.out; printTitle(); TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); if (!dialog.showDialog("TreeAnnotator " + versionString)) { return; } long burninStates = dialog.getBurninStates(); int burninTrees = dialog.getBurninTrees(); double posteriorLimit = dialog.getPosteriorLimit(); double[] hpd2D = {0.80}; Target targetOption = dialog.getTargetOption(); HeightsSummary heightsOption = dialog.getHeightsOption(); targetTreeFileName = dialog.getTargetFileName(); if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) { System.err.println("No target file specified"); return; } inputFileName = dialog.getInputFileName(); if (inputFileName == null) { System.err.println("No input file specified"); return; } outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { System.err.println("No output file specified"); return; } try { new TreeAnnotator( burninTrees, burninStates, heightsOption, posteriorLimit, hpd2D, targetOption, targetTreeFileName, inputFileName, outputFileName); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } progressStream.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean", "ca"}, false, "an option of 'keep' (default), 'median', 'mean' or 'ca'"), new Arguments.LongOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.IntegerOption("burninTrees", "the number of trees to be considered as 'burn-in'"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message"), new Arguments.Option("forceDiscrete", "forces integer traits to be treated as discrete traits."), new Arguments.StringOption("hpd2D", "the HPD interval to be used for the bivariate traits", "specifies a (vector of comma separated) HPD proportion(s)"), new Arguments.Option("ess", "compute ess for branch parameters") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("forceDiscrete")) { System.out.println(" Forcing integer traits to be treated as discrete traits."); forceIntegerToDiscrete = true; } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } HeightsSummary heights = HeightsSummary.KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = HeightsSummary.MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = HeightsSummary.MEDIAN_HEIGHTS; } else if (value.equalsIgnoreCase("ca")) { heights = HeightsSummary.CA_HEIGHTS; System.out.println("Please cite: Heled and Bouckaert: Looking for trees in the forest:\n" + "summary tree from posterior samples. BMC Evolutionary Biology 2013 13:221."); } } long burninStates = -1; int burninTrees = -1; if (arguments.hasOption("burnin")) { burninStates = arguments.getLongOption("burnin"); } if (arguments.hasOption("burninTrees")) { burninTrees = arguments.getIntegerOption("burninTrees"); } if (arguments.hasOption("ess")) { if(burninStates != -1) { System.out.println(" Calculating ESS for branch parameters."); computeESS = true; } else { throw new RuntimeException("Specify burnin as states to use 'ess' option."); } } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } double[] hpd2D = {80}; if (arguments.hasOption("hpd2D")) { try { hpd2D = parseVariableLengthDoubleArray(arguments.getStringOption("hpd2D")); } catch (Arguments.ArgumentException e) { System.err.println("Error reading " + arguments.getStringOption("hpd2D")); } } Target target = Target.MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = Target.USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 2: outputFileName = args2[1]; // fall to case 1: inputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } } new TreeAnnotator(burninTrees, burninStates, heights, posteriorLimit, hpd2D, target, targetTreeFileName, inputFileName, outputFileName); System.exit(0); } /** * @author Andrew Rambaut * @version $Id$ */ public static interface TreeAnnotationPlugin { Set<String> setAttributeNames(Set<String> attributeNames); boolean handleAttribute(Tree tree, NodeRef node, String attributeName, double[] values); } // very inefficient, but Java wonderful bitset has no subset op // perhaps using bit iterator would be faster, I can't br bothered. static boolean isSubSet(BitSet x, BitSet y) { y = (BitSet) y.clone(); y.and(x); return y.equals(x); } boolean setTreeHeightsByCA(MutableTree targetTree, final String inputFileName, final int burnin) throws IOException, Importer.ImportException { progressStream.println("Setting node heights..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); int reportStepSize = totalTrees / 60; if (reportStepSize < 1) reportStepSize = 1; final FileReader fileReader = new FileReader(inputFileName); final NexusImporter importer = new NexusImporter(fileReader, true); // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below CladeSystem cladeSystem = new CladeSystem(targetTree); final int nClades = cladeSystem.getCladeMap().size(); // allocate posterior tree nodes order once int[] postOrderList = new int[nClades]; BitSet[] ctarget = new BitSet[nClades]; BitSet[] ctree = new BitSet[nClades]; for (int k = 0; k < nClades; ++k) { ctarget[k] = new BitSet(); ctree[k] = new BitSet(); } cladeSystem.getTreeCladeCodes(targetTree, ctarget); // temp collecting heights inside loop allocated once double[] hs = new double[nClades]; // heights total sum from posterior trees double[] ths = new double[nClades]; totalTreesUsed = 0; int counter = 0; while (importer.hasTree()) { final Tree tree = importer.importNextTree(); if (counter >= burnin) { TreeUtils.preOrderTraversalList(tree, postOrderList); cladeSystem.getTreeCladeCodes(tree, ctree); for (int k = 0; k < nClades; ++k) { int j = postOrderList[k]; for (int i = 0; i < nClades; ++i) { if( isSubSet(ctarget[i], ctree[j]) ) { hs[i] = tree.getNodeHeight(tree.getNode(j)); } } } for (int k = 0; k < nClades; ++k) { ths[k] += hs[k]; } totalTreesUsed += 1; } if (counter > 0 && counter % reportStepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); for (int k = 0; k < nClades; ++k) { ths[k] /= totalTreesUsed; final NodeRef node = targetTree.getNode(k); targetTree.setNodeHeight(node, ths[k]); } fileReader.close(); progressStream.println(); progressStream.println(); return true; } }
src/dr/app/tools/TreeAnnotator.java
/* * TreeAnnotator.java * * Copyright (c) 2002-2015 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.tools; import dr.app.beast.BeastVersion; import dr.app.util.Arguments; import dr.evolution.io.Importer; import dr.evolution.io.NewickImporter; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.tree.*; import dr.evolution.util.TaxonList; import dr.geo.contouring.ContourMaker; import dr.geo.contouring.ContourPath; import dr.geo.contouring.ContourWithSynder; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.Version; import jam.console.ConsoleApplication; import org.rosuda.JRI.REXP; import org.rosuda.JRI.RVector; import org.rosuda.JRI.Rengine; import javax.swing.*; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * @author Alexei Drummond * @author Andrew Rambaut */ public class TreeAnnotator { private final static Version version = new BeastVersion(); private final static boolean USE_R = false; private static boolean forceIntegerToDiscrete = false; enum Target { MAX_CLADE_CREDIBILITY("Maximum clade credibility tree"), //MAX_SUM_CLADE_CREDIBILITY("Maximum sum of clade credibilities"), USER_TARGET_TREE("User target tree"); String desc; Target(String s) { desc = s; } public String toString() { return desc; } } enum HeightsSummary { MEDIAN_HEIGHTS("Median heights"), MEAN_HEIGHTS("Mean heights"), KEEP_HEIGHTS("Keep target heights"), CA_HEIGHTS("Common Ancestor heights"); String desc; HeightsSummary(String s) { desc = s; } public String toString() { return desc; } } // Messages to stderr, output to stdout private static PrintStream progressStream = System.err; private final String location1Attribute = "longLat1"; private final String location2Attribute = "longLat2"; private final String locationOutputAttribute = "location"; /** * Burnin can be specified as the number of trees or the number of states * (one or other should be zero). * @param burninTrees * @param burninStates * @param heightsOption * @param posteriorLimit * @param hpd2D * @param targetOption * @param targetTreeFileName * @param inputFileName * @param outputFileName * @throws IOException */ public TreeAnnotator(final int burninTrees, final long burninStates, HeightsSummary heightsOption, double posteriorLimit, double[] hpd2D, Target targetOption, String targetTreeFileName, String inputFileName, String outputFileName ) throws IOException { this.posteriorLimit = posteriorLimit; this.hpd2D = hpd2D; attributeNames.add("height"); attributeNames.add("length"); CladeSystem cladeSystem = new CladeSystem(); int burnin = -1; totalTrees = 10000; totalTreesUsed = 0; progressStream.println("Reading trees (bar assumes 10,000 trees)..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); long stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; if (targetOption != Target.USER_TARGET_TREE) { cladeSystem = new CladeSystem(); FileReader fileReader = new FileReader(inputFileName); TreeImporter importer = new NexusImporter(fileReader, true); try { totalTrees = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); long state = Long.MAX_VALUE; if (burninStates > 0) { // if burnin has been specified in states, try to parse it out... String name = tree.getId().trim(); if (name != null && name.length() > 0 && name.startsWith("STATE_")) { state = Long.parseLong(name.split("_")[1]); } } if (totalTrees >= burninTrees && state >= burninStates) { // if either of the two burnin thresholds have been reached... if (burnin < 0) { // if this is the first time this point has been reached, // record the number of trees this represents for future use... burnin = totalTrees; } cladeSystem.add(tree, false); totalTreesUsed += 1; } if (totalTrees > 0 && totalTrees % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } totalTrees++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } fileReader.close(); progressStream.println(); progressStream.println(); if (totalTrees < 1) { System.err.println("No trees"); return; } if (totalTreesUsed <= 1) { if (burnin > 0) { System.err.println("No trees to use: burnin too high"); return; } } cladeSystem.calculateCladeCredibilities(totalTreesUsed); progressStream.println("Total trees read: " + totalTrees); if (burninTrees > 0) { progressStream.println("Ignoring first " + burninTrees + " trees" + (burninStates > 0 ? " (" + burninStates + " states)." : "." )); } else if (burninStates > 0) { progressStream.println("Ignoring first " + burninStates + " states (" + burnin + " trees)."); } progressStream.println("Total unique clades: " + cladeSystem.getCladeMap().keySet().size()); progressStream.println(); } MutableTree targetTree = null; switch (targetOption) { case USER_TARGET_TREE: { if (targetTreeFileName != null) { progressStream.println("Reading user specified target tree, " + targetTreeFileName); NexusImporter importer = new NexusImporter(new FileReader(targetTreeFileName)); try { Tree tree = importer.importNextTree(); if (tree == null) { NewickImporter x = new NewickImporter(new FileReader(targetTreeFileName)); tree = x.importNextTree(); } if (tree == null) { System.err.println("No tree in target nexus or newick file " + targetTreeFileName); return; } targetTree = new FlexibleTree(tree); } catch (Importer.ImportException e) { System.err.println("Error Parsing Target Tree: " + e.getMessage()); return; } } else { System.err.println("No user target tree specified."); return; } break; } case MAX_CLADE_CREDIBILITY: { progressStream.println("Finding maximum credibility tree..."); targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName /*, false*/)); break; } // case MAX_SUM_CLADE_CREDIBILITY: { // progressStream.println("Finding maximum sum clade credibility tree..."); // targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true)); // break; // } default: throw new IllegalArgumentException("Unknown targetOption"); } progressStream.println("Collecting node information..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; FileReader fileReader = new FileReader(inputFileName); NexusImporter importer = new NexusImporter(fileReader); // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below cladeSystem = new CladeSystem(targetTree); totalTreesUsed = 0; try { boolean firstTree = true; int counter = 0; while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { if (firstTree) { setupAttributes(tree); firstTree = false; } cladeSystem.collectAttributes(tree); totalTreesUsed += 1; } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); //progressStream.println("totalTreesUsed=" + totalTreesUsed); cladeSystem.calculateCladeCredibilities(totalTreesUsed); } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return; } progressStream.println(); progressStream.println(); fileReader.close(); progressStream.println("Annotating target tree..."); try { cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption); if( heightsOption == HeightsSummary.CA_HEIGHTS ) { setTreeHeightsByCA(targetTree, inputFileName, burnin); } } catch (Exception e) { System.err.println("Error annotating tree: " + e.getMessage() + "\nPlease check the tree log file format."); return; } progressStream.println("Writing annotated tree...."); try { final PrintStream stream = outputFileName != null ? new PrintStream(new FileOutputStream(outputFileName)) : System.out; new NexusExporter(stream).exportTree(targetTree); } catch (Exception e) { System.err.println("Error to write annotated tree file: " + e.getMessage()); return; } } private void setupAttributes(Tree tree) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); Iterator iter = tree.getNodeAttributeNames(node); if (iter != null) { while (iter.hasNext()) { String name = (String) iter.next(); attributeNames.add(name); } } } for (TreeAnnotationPlugin plugin : plugins) { Set<String> claimed = plugin.setAttributeNames(attributeNames); attributeNames.removeAll(claimed); } } private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName /*, boolean useSumCladeCredibility */) throws IOException { Tree bestTree = null; double bestScore = Double.NEGATIVE_INFINITY; progressStream.println("Analyzing " + totalTreesUsed + " trees..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); int stepSize = totalTrees / 60; if (stepSize < 1) stepSize = 1; int counter = 0; int bestTreeNumber = 0; TreeImporter importer = new NexusImporter(new FileReader(inputFileName), true); try { while (importer.hasTree()) { Tree tree = importer.importNextTree(); if (counter >= burnin) { double score = scoreTree(tree, cladeSystem /*, useSumCladeCredibility*/); // progressStream.println(score); if (score > bestScore) { bestTree = tree; bestScore = score; bestTreeNumber = counter + 1; } } if (counter > 0 && counter % stepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } } catch (Importer.ImportException e) { System.err.println("Error Parsing Input Tree: " + e.getMessage()); return null; } progressStream.println(); progressStream.println(); progressStream.println("Best tree: " + bestTree.getId() + " (tree number " + bestTreeNumber + ")"); // if (useSumCladeCredibility) { // progressStream.println("Highest Sum Clade Credibility: " + bestScore); // } else { progressStream.println("Highest Log Clade Credibility: " + bestScore); // } return bestTree; } private double scoreTree(Tree tree, CladeSystem cladeSystem /*, boolean useSumCladeCredibility*/) { // if (useSumCladeCredibility) { // return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null); // } else { return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null); // } } private class CladeSystem { // // Public stuff // /** */ public CladeSystem() { } /** */ public CladeSystem(Tree targetTree) { this.targetTree = targetTree; add(targetTree, true); } /** * adds all the clades in the tree */ public void add(Tree tree, boolean includeTips) { if (taxonList == null) { taxonList = tree; } // Recurse over the tree and add all the clades (or increment their // frequency if already present). The root clade is added too (for // annotation purposes). addClades(tree, tree.getRoot(), includeTips); } // // public Clade getClade(NodeRef node) { // return null; // } private BitSet addClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { addClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(addClades(tree, node1, includeTips)); } addClade(bits); } return bits; } private void addClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { clade = new Clade(bits); cladeMap.put(bits, clade); } clade.setCount(clade.getCount() + 1); } public void collectAttributes(Tree tree) { collectAttributes(tree, tree.getRoot()); } private BitSet collectAttributes(Tree tree, NodeRef node) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); if (index < 0) { throw new IllegalArgumentException("Taxon, " + tree.getNodeTaxon(node).getId() + ", not found in target tree"); } bits.set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(collectAttributes(tree, node1)); } } collectAttributesForClade(bits, tree, node); return bits; } private void collectAttributesForClade(BitSet bits, Tree tree, NodeRef node) { Clade clade = cladeMap.get(bits); if (clade != null) { if (clade.attributeValues == null) { clade.attributeValues = new ArrayList<Object[]>(); } int i = 0; Object[] values = new Object[attributeNames.size()]; for (String attributeName : attributeNames) { boolean processed = false; if (!processed) { Object value; if (attributeName.equals("height")) { value = tree.getNodeHeight(node); } else if (attributeName.equals("length")) { value = tree.getBranchLength(node); // AR - we deal with this once everything // } else if (attributeName.equals(location1Attribute)) { // // If this is one of the two specified bivariate location names then // // merge this and the other one into a single array. // Object value1 = tree.getNodeAttribute(node, attributeName); // Object value2 = tree.getNodeAttribute(node, location2Attribute); // // value = new Object[]{value1, value2}; // } else if (attributeName.equals(location2Attribute)) { // // do nothing - already dealt with this... // value = null; } else { value = tree.getNodeAttribute(node, attributeName); if (value instanceof String && ((String) value).startsWith("\"")) { value = ((String) value).replaceAll("\"", ""); } } //if (value == null) { // progressStream.println("attribute " + attributeNames[i] + " is null."); //} values[i] = value; } i++; } clade.attributeValues.add(values); //progressStream.println(clade + " " + clade.getValuesSize()); clade.setCount(clade.getCount() + 1); } } public Map getCladeMap() { return cladeMap; } public void calculateCladeCredibilities(int totalTreesUsed) { for (Clade clade : cladeMap.values()) { if (clade.getCount() > totalTreesUsed) { throw new AssertionError("clade.getCount=(" + clade.getCount() + ") should be <= totalTreesUsed = (" + totalTreesUsed + ")"); } clade.setCredibility(((double) clade.getCount()) / (double) totalTreesUsed); } } // public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) { // // double sum = 0.0; // // if (tree.isExternal(node)) { // // int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); // bits.set(index); // } else { // // BitSet bits2 = new BitSet(); // for (int i = 0; i < tree.getChildCount(node); i++) { // // NodeRef node1 = tree.getChild(node, i); // // sum += getSumCladeCredibility(tree, node1, bits2); // } // // sum += getCladeCredibility(bits2); // // if (bits != null) { // bits.or(bits2); // } // } // // return sum; // } public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) { double logCladeCredibility = 0.0; if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); } else { BitSet bits2 = new BitSet(); for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); logCladeCredibility += getLogCladeCredibility(tree, node1, bits2); } logCladeCredibility += Math.log(getCladeCredibility(bits2)); if (bits != null) { bits.or(bits2); } } return logCladeCredibility; } private double getCladeCredibility(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade == null) { return 0.0; } return clade.getCredibility(); } public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, HeightsSummary heightsOption) { BitSet bits2 = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits2.set(index); annotateNode(tree, node, bits2, true, heightsOption); } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); annotateTree(tree, node1, bits2, heightsOption); } annotateNode(tree, node, bits2, false, heightsOption); } if (bits != null) { bits.or(bits2); } } private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, HeightsSummary heightsOption) { Clade clade = cladeMap.get(bits); assert clade != null : "Clade missing?"; boolean filter = false; if (!isTip) { final double posterior = clade.getCredibility(); tree.setNodeAttribute(node, "posterior", posterior); if (posterior < posteriorLimit) { filter = true; } } int i = 0; for (String attributeName : attributeNames) { if (clade.attributeValues != null && clade.attributeValues.size() > 0) { double[] values = new double[clade.attributeValues.size()]; HashMap<Object, Integer> hashMap = new HashMap<Object, Integer>(); Object[] v = clade.attributeValues.get(0); if (v[i] != null) { final boolean isHeight = attributeName.equals("height"); boolean isBoolean = v[i] instanceof Boolean; boolean isDiscrete = v[i] instanceof String; if (forceIntegerToDiscrete && v[i] instanceof Integer) isDiscrete = true; double minValue = Double.MAX_VALUE; double maxValue = -Double.MAX_VALUE; final boolean isArray = v[i] instanceof Object[]; boolean isDoubleArray = isArray && ((Object[]) v[i])[0] instanceof Double; // This is Java, friends - first value type does not imply all. if (isDoubleArray) { for (Object n : (Object[]) v[i]) { if (!(n instanceof Double)) { isDoubleArray = false; break; } } } // todo Handle other types of arrays double[][] valuesArray = null; double[] minValueArray = null; double[] maxValueArray = null; int lenArray = 0; if (isDoubleArray) { lenArray = ((Object[]) v[i]).length; valuesArray = new double[lenArray][clade.attributeValues.size()]; minValueArray = new double[lenArray]; maxValueArray = new double[lenArray]; for (int k = 0; k < lenArray; k++) { minValueArray[k] = Double.MAX_VALUE; maxValueArray[k] = -Double.MAX_VALUE; } } for (int j = 0; j < clade.attributeValues.size(); j++) { Object value = clade.attributeValues.get(j)[i]; if (isDiscrete) { final Object s = value; if (hashMap.containsKey(s)) { hashMap.put(s, hashMap.get(s) + 1); } else { hashMap.put(s, 1); } } else if (isBoolean) { values[j] = (((Boolean) value) ? 1.0 : 0.0); } else if (isDoubleArray) { // Forcing to Double[] causes a cast exception. MAS Object[] array = (Object[]) value; for (int k = 0; k < lenArray; k++) { valuesArray[k][j] = ((Double) array[k]); if (valuesArray[k][j] < minValueArray[k]) minValueArray[k] = valuesArray[k][j]; if (valuesArray[k][j] > maxValueArray[k]) maxValueArray[k] = valuesArray[k][j]; } } else { // Ignore other (unknown) types if (value instanceof Number) { values[j] = ((Number) value).doubleValue(); if (values[j] < minValue) minValue = values[j]; if (values[j] > maxValue) maxValue = values[j]; } } } if (isHeight) { if (heightsOption == HeightsSummary.MEAN_HEIGHTS) { final double mean = DiscreteStatistics.mean(values); tree.setNodeHeight(node, mean); } else if (heightsOption == HeightsSummary.MEDIAN_HEIGHTS) { final double median = DiscreteStatistics.median(values); tree.setNodeHeight(node, median); } else { // keep the existing height } } if (!filter) { boolean processed = false; for (TreeAnnotationPlugin plugin : plugins) { if (plugin.handleAttribute(tree, node, attributeName, values)) { processed = true; } } if (!processed) { if (!isDiscrete) { if (!isDoubleArray) annotateMeanAttribute(tree, node, attributeName, values); else { for (int k = 0; k < lenArray; k++) { annotateMeanAttribute(tree, node, attributeName + (k + 1), valuesArray[k]); } } } else { annotateModeAttribute(tree, node, attributeName, hashMap); annotateFrequencyAttribute(tree, node, attributeName, hashMap); } if (!isBoolean && minValue < maxValue && !isDiscrete && !isDoubleArray) { // Basically, if it is a boolean (0, 1) then we don't need the distribution information // Likewise if it doesn't vary. annotateMedianAttribute(tree, node, attributeName + "_median", values); annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values); annotateRangeAttribute(tree, node, attributeName + "_range", values); } if (isDoubleArray) { String name = attributeName; // todo // if (name.equals(location1Attribute)) { // name = locationOutputAttribute; // } boolean want2d = processBivariateAttributes && lenArray == 2; if (name.equals("dmv")) { // terrible hack want2d = false; } for (int k = 0; k < lenArray; k++) { if (minValueArray[k] < maxValueArray[k]) { annotateMedianAttribute(tree, node, name + (k + 1) + "_median", valuesArray[k]); annotateRangeAttribute(tree, node, name + (k + 1) + "_range", valuesArray[k]); if (!want2d) annotateHPDAttribute(tree, node, name + (k + 1) + "_95%_HPD", 0.95, valuesArray[k]); } } // 2D contours if (want2d) { boolean variationInFirst = (minValueArray[0] < maxValueArray[0]); boolean variationInSecond = (minValueArray[1] < maxValueArray[1]); if (variationInFirst && !variationInSecond) annotateHPDAttribute(tree, node, name + "1" + "_95%_HPD", 0.95, valuesArray[0]); if (variationInSecond && !variationInFirst) annotateHPDAttribute(tree, node, name + "2" + "_95%_HPD", 0.95, valuesArray[1]); if (variationInFirst && variationInSecond){ for (int l = 0; l < hpd2D.length; l++) { if (hpd2D[l] > 1) { System.err.println("no HPD for proportion > 1 (" + hpd2D[l] + ")"); } else if (hpd2D[l] < 0){ System.err.println("no HPD for proportion < 0 (" + hpd2D[l] + ")"); } else { annotate2DHPDAttribute(tree, node, name, "_" + (int) (100 * hpd2D[l]) + "%HPD", hpd2D[l], valuesArray); } } } } } } } } } i++; } } private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double mean = DiscreteStatistics.mean(values); tree.setNodeAttribute(node, label, mean); } private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double median = DiscreteStatistics.median(values); tree.setNodeAttribute(node, label, median); } private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { Object mode = null; int maxCount = 0; int totalCount = 0; int countInMode = 1; for (Object key : values.keySet()) { int thisCount = values.get(key); if (thisCount == maxCount) { // I hope this is the intention mode = mode.toString().concat("+" + key); countInMode++; } else if (thisCount > maxCount) { mode = key; maxCount = thisCount; countInMode = 1; } totalCount += thisCount; } double freq = (double) maxCount / (double) totalCount * countInMode; tree.setNodeAttribute(node, label, mode); tree.setNodeAttribute(node, label + ".prob", freq); } private void annotateFrequencyAttribute(MutableTree tree, NodeRef node, String label, HashMap<Object, Integer> values) { double totalCount = 0; Set keySet = values.keySet(); int length = keySet.size(); String[] name = new String[length]; Double[] freq = new Double[length]; int index = 0; for (Object key : values.keySet()) { name[index] = key.toString(); freq[index] = new Double(values.get(key)); totalCount += freq[index]; index++; } for (int i = 0; i < length; i++) freq[i] /= totalCount; tree.setNodeAttribute(node, label + ".set", name); tree.setNodeAttribute(node, label + ".set.prob", freq); } private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) { double min = DiscreteStatistics.min(values); double max = DiscreteStatistics.max(values); tree.setNodeAttribute(node, label, new Object[]{min, max}); } private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) { int[] indices = new int[values.length]; HeapSort.sort(values, indices); double minRange = Double.MAX_VALUE; int hpdIndex = 0; int diff = (int) Math.round(hpd * (double) values.length); for (int i = 0; i <= (values.length - diff); i++) { double minValue = values[indices[i]]; double maxValue = values[indices[i + diff - 1]]; double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } double lower = values[indices[hpdIndex]]; double upper = values[indices[hpdIndex + diff - 1]]; tree.setNodeAttribute(node, label, new Object[]{lower, upper}); } // todo Move rEngine to outer class; create once. Rengine rEngine = null; private final String[] rArgs = {"--no-save"}; // private int called = 0; private final String[] rBootCommands = { "library(MASS)", "makeContour = function(var1, var2, prob=0.95, n=50, h=c(1,1)) {" + "post1 = kde2d(var1, var2, n = n, h=h); " + // This had h=h in argument "dx = diff(post1$x[1:2]); " + "dy = diff(post1$y[1:2]); " + "sz = sort(post1$z); " + "c1 = cumsum(sz) * dx * dy; " + "levels = sapply(prob, function(x) { approx(c1, sz, xout = 1 - x)$y }); " + "line = contourLines(post1$x, post1$y, post1$z, level = levels); " + "return(line) }" }; private String makeRString(double[] values) { StringBuffer sb = new StringBuffer("c("); sb.append(values[0]); for (int i = 1; i < values.length; i++) { sb.append(","); sb.append(values[i]); } sb.append(")"); return sb.toString(); } public static final String CORDINATE = "cordinates"; // private String formattedLocation(double loc1, double loc2) { // return formattedLocation(loc1) + "," + formattedLocation(loc2); // } private String formattedLocation(double x) { return String.format("%5.8f", x); } private void annotate2DHPDAttribute(MutableTree tree, NodeRef node, String preLabel, String postLabel, double hpd, double[][] values) { int N = 50; if (USE_R) { // Uses R-Java interface, and the HPD routines from 'emdbook' and 'coda' if (rEngine == null) { if (!Rengine.versionCheck()) { throw new RuntimeException("JRI library version mismatch"); } rEngine = new Rengine(rArgs, false, null); if (!rEngine.waitForR()) { throw new RuntimeException("Cannot load R"); } for (String command : rBootCommands) { rEngine.eval(command); } } // todo Need a good method to pick grid size REXP x = rEngine.eval("makeContour(" + makeRString(values[0]) + "," + makeRString(values[1]) + "," + hpd + "," + N + ")"); RVector contourList = x.asVector(); int numberContours = contourList.size(); if (numberContours > 1) { System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } tree.setNodeAttribute(node, preLabel + postLabel + "_modality", numberContours); StringBuffer output = new StringBuffer(); for (int i = 0; i < numberContours; i++) { output.append("\n<" + CORDINATE + ">\n"); RVector oneContour = contourList.at(i).asVector(); double[] xList = oneContour.at(1).asDoubleArray(); double[] yList = oneContour.at(2).asDoubleArray(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); } } else { // do not use R // KernelDensityEstimator2D kde = new KernelDensityEstimator2D(values[0], values[1], N); //ContourMaker kde = new ContourWithSynder(values[0], values[1], N); boolean bandwidthLimit = false; ContourMaker kde = new ContourWithSynder(values[0], values[1], bandwidthLimit); ContourPath[] paths = kde.getContourPaths(hpd); tree.setNodeAttribute(node, preLabel + postLabel + "_modality", paths.length); if (paths.length > 1) { System.err.println("Warning: a node has a disjoint " + 100 * hpd + "% HPD region. This may be an artifact!"); System.err.println("Try decreasing the enclosed mass or increasing the number of samples."); } StringBuffer output = new StringBuffer(); int i = 0; for (ContourPath p : paths) { output.append("\n<" + CORDINATE + ">\n"); double[] xList = p.getAllX(); double[] yList = p.getAllY(); StringBuffer xString = new StringBuffer("{"); StringBuffer yString = new StringBuffer("{"); for (int k = 0; k < xList.length; k++) { xString.append(formattedLocation(xList[k])).append(","); yString.append(formattedLocation(yList[k])).append(","); } xString.append(formattedLocation(xList[0])).append("}"); yString.append(formattedLocation(yList[0])).append("}"); tree.setNodeAttribute(node, preLabel + "1" + postLabel + "_" + (i + 1), xString); tree.setNodeAttribute(node, preLabel + "2" + postLabel + "_" + (i + 1), yString); i++; } } } public BitSet removeClades(Tree tree, NodeRef node, boolean includeTips) { BitSet bits = new BitSet(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); bits.set(index); if (includeTips) { removeClade(bits); } } else { for (int i = 0; i < tree.getChildCount(node); i++) { NodeRef node1 = tree.getChild(node, i); bits.or(removeClades(tree, node1, includeTips)); } removeClade(bits); } return bits; } private void removeClade(BitSet bits) { Clade clade = cladeMap.get(bits); if (clade != null) { clade.setCount(clade.getCount() - 1); } } // Get tree clades as bitSets on target taxa // codes is an array of existing BitSet objects, which are reused void getTreeCladeCodes(Tree tree, BitSet[] codes) { getTreeCladeCodes(tree, tree.getRoot(), codes); } int getTreeCladeCodes(Tree tree, NodeRef node, BitSet[] codes) { final int inode = node.getNumber(); codes[inode].clear(); if (tree.isExternal(node)) { int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId()); codes[inode].set(index); } else { for (int i = 0; i < tree.getChildCount(node); i++) { final NodeRef child = tree.getChild(node, i); final int childIndex = getTreeCladeCodes(tree, child, codes); codes[inode].or(codes[childIndex]); } } return inode; } class Clade { public Clade(BitSet bits) { this.bits = bits; count = 0; credibility = 0.0; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getCredibility() { return credibility; } public void setCredibility(double credibility) { this.credibility = credibility; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Clade clade = (Clade) o; return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null); } public int hashCode() { return (bits != null ? bits.hashCode() : 0); } public String toString() { return "clade " + bits.toString(); } int count; double credibility; BitSet bits; List<Object[]> attributeValues = null; } // // Private stuff // TaxonList taxonList = null; Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>(); Tree targetTree; } int totalTrees = 0; int totalTreesUsed = 0; double posteriorLimit = 0.0; //PL: double hpd2D = 0.80; double[] hpd2D = {0.80}; private final List<TreeAnnotationPlugin> plugins = new ArrayList<TreeAnnotationPlugin>(); Set<String> attributeNames = new HashSet<String>(); TaxonList taxa = null; static boolean processBivariateAttributes = false; static { try { System.loadLibrary("jri"); processBivariateAttributes = true; System.err.println("JRI loaded. Will process bivariate attributes"); } catch (UnsatisfiedLinkError e) { // System.err.print("JRI not available. "); if (!USE_R) { processBivariateAttributes = true; // System.err.println("Using Java bivariate attributes"); } else { // System.err.println("Will not process bivariate attributes"); } } } public static void printTitle() { progressStream.println(); centreLine("TreeAnnotator " + version.getVersionString() + ", " + version.getDateString(), 60); centreLine("MCMC Output analysis", 60); centreLine("by", 60); centreLine("Andrew Rambaut and Alexei J. Drummond", 60); progressStream.println(); centreLine("Institute of Evolutionary Biology", 60); centreLine("University of Edinburgh", 60); centreLine("[email protected]", 60); progressStream.println(); centreLine("Department of Computer Science", 60); centreLine("University of Auckland", 60); centreLine("[email protected]", 60); progressStream.println(); progressStream.println(); } public static void centreLine(String line, int pageWidth) { int n = pageWidth - line.length(); int n1 = n / 2; for (int i = 0; i < n1; i++) { progressStream.print(" "); } progressStream.println(line); } public static void printUsage(Arguments arguments) { arguments.printUsage("treeannotator", "<input-file-name> [<output-file-name>]"); progressStream.println(); progressStream.println(" Example: treeannotator test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -heights mean test.trees out.txt"); progressStream.println(" Example: treeannotator -burnin 100 -target map.tree test.trees out.txt"); progressStream.println(); } public static double[] parseVariableLengthDoubleArray(String inString) throws Arguments.ArgumentException { List<Double> returnList = new ArrayList<Double>(); StringTokenizer st = new StringTokenizer(inString,","); while(st.hasMoreTokens()) { try { returnList.add(Double.parseDouble(st.nextToken())); } catch (NumberFormatException e) { throw new Arguments.ArgumentException(); } } if (returnList.size()>0) { double[] doubleArray = new double[returnList.size()]; for(int i=0; i<doubleArray.length; i++) doubleArray[i] = returnList.get(i); return doubleArray; } return null; } //Main method public static void main(String[] args) throws IOException { // There is a major issue with languages that use the comma as a decimal separator. // To ensure compatibility between programs in the package, enforce the US locale. Locale.setDefault(Locale.US); String targetTreeFileName = null; String inputFileName = null; String outputFileName = null; if (args.length == 0) { System.setProperty("com.apple.macos.useScreenMenuBar", "true"); System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("apple.awt.showGrowBox", "true"); java.net.URL url = LogCombiner.class.getResource("/images/utility.png"); javax.swing.Icon icon = null; if (url != null) { icon = new javax.swing.ImageIcon(url); } final String versionString = version.getVersionString(); String nameString = "TreeAnnotator " + versionString; String aboutString = "<html><center><p>" + versionString + ", " + version.getDateString() + "</p>" + "<p>by<br>" + "Andrew Rambaut and Alexei J. Drummond</p>" + "<p>Institute of Evolutionary Biology, University of Edinburgh<br>" + "<a href=\"mailto:[email protected]\">[email protected]</a></p>" + "<p>Department of Computer Science, University of Auckland<br>" + "<a href=\"mailto:[email protected]\">[email protected]</a></p>" + "<p>Part of the BEAST package:<br>" + "<a href=\"http://beast.community\">http://beast.community</a></p>" + "</center></html>"; new ConsoleApplication(nameString, aboutString, icon, true); // The ConsoleApplication will have overridden System.out so set progressStream // to capture the output to the window: progressStream = System.out; printTitle(); TreeAnnotatorDialog dialog = new TreeAnnotatorDialog(new JFrame()); if (!dialog.showDialog("TreeAnnotator " + versionString)) { return; } long burninStates = dialog.getBurninStates(); int burninTrees = dialog.getBurninTrees(); double posteriorLimit = dialog.getPosteriorLimit(); double[] hpd2D = {0.80}; Target targetOption = dialog.getTargetOption(); HeightsSummary heightsOption = dialog.getHeightsOption(); targetTreeFileName = dialog.getTargetFileName(); if (targetOption == Target.USER_TARGET_TREE && targetTreeFileName == null) { System.err.println("No target file specified"); return; } inputFileName = dialog.getInputFileName(); if (inputFileName == null) { System.err.println("No input file specified"); return; } outputFileName = dialog.getOutputFileName(); if (outputFileName == null) { System.err.println("No output file specified"); return; } try { new TreeAnnotator( burninTrees, burninStates, heightsOption, posteriorLimit, hpd2D, targetOption, targetTreeFileName, inputFileName, outputFileName); } catch (Exception ex) { System.err.println("Exception: " + ex.getMessage()); } progressStream.println("Finished - Quit program to exit."); while (true) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } printTitle(); Arguments arguments = new Arguments( new Arguments.Option[]{ //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"), new Arguments.StringOption("heights", new String[]{"keep", "median", "mean", "ca"}, false, "an option of 'keep' (default), 'median', 'mean' or 'ca'"), new Arguments.LongOption("burnin", "the number of states to be considered as 'burn-in'"), new Arguments.IntegerOption("burninTrees", "the number of trees to be considered as 'burn-in'"), new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"), new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"), new Arguments.Option("help", "option to print this message"), new Arguments.Option("forceDiscrete", "forces integer traits to be treated as discrete traits."), new Arguments.StringOption("hpd2D", "the HPD interval to be used for the bivariate traits", "specifies a (vector of comma seperated) HPD proportion(s)") }); try { arguments.parseArguments(args); } catch (Arguments.ArgumentException ae) { progressStream.println(ae); printUsage(arguments); System.exit(1); } if (arguments.hasOption("forceDiscrete")) { System.out.println(" Forcing integer traits to be treated as discrete traits."); forceIntegerToDiscrete = true; } if (arguments.hasOption("help")) { printUsage(arguments); System.exit(0); } HeightsSummary heights = HeightsSummary.KEEP_HEIGHTS; if (arguments.hasOption("heights")) { String value = arguments.getStringOption("heights"); if (value.equalsIgnoreCase("mean")) { heights = HeightsSummary.MEAN_HEIGHTS; } else if (value.equalsIgnoreCase("median")) { heights = HeightsSummary.MEDIAN_HEIGHTS; } else if (value.equalsIgnoreCase("ca")) { heights = HeightsSummary.CA_HEIGHTS; System.out.println("Please cite: Heled and Bouckaert: Looking for trees in the forest:\n" + "summary tree from posterior samples. BMC Evolutionary Biology 2013 13:221."); } } long burninStates = -1; int burninTrees = -1; if (arguments.hasOption("burnin")) { burninStates = arguments.getLongOption("burnin"); } if (arguments.hasOption("burninTrees")) { burninTrees = arguments.getIntegerOption("burninTrees"); } double posteriorLimit = 0.0; if (arguments.hasOption("limit")) { posteriorLimit = arguments.getRealOption("limit"); } double[] hpd2D = {80}; if (arguments.hasOption("hpd2D")) { try { hpd2D = parseVariableLengthDoubleArray(arguments.getStringOption("hpd2D")); } catch (Arguments.ArgumentException e) { System.err.println("Error reading " + arguments.getStringOption("hpd2D")); } } Target target = Target.MAX_CLADE_CREDIBILITY; if (arguments.hasOption("target")) { target = Target.USER_TARGET_TREE; targetTreeFileName = arguments.getStringOption("target"); } final String[] args2 = arguments.getLeftoverArguments(); switch (args2.length) { case 2: outputFileName = args2[1]; // fall to case 1: inputFileName = args2[0]; break; default: { System.err.println("Unknown option: " + args2[2]); System.err.println(); printUsage(arguments); System.exit(1); } } new TreeAnnotator(burninTrees, burninStates, heights, posteriorLimit, hpd2D, target, targetTreeFileName, inputFileName, outputFileName); System.exit(0); } /** * @author Andrew Rambaut * @version $Id$ */ public static interface TreeAnnotationPlugin { Set<String> setAttributeNames(Set<String> attributeNames); boolean handleAttribute(Tree tree, NodeRef node, String attributeName, double[] values); } // very inefficient, but Java wonderful bitset has no subset op // perhaps using bit iterator would be faster, I can't br bothered. static boolean isSubSet(BitSet x, BitSet y) { y = (BitSet) y.clone(); y.and(x); return y.equals(x); } boolean setTreeHeightsByCA(MutableTree targetTree, final String inputFileName, final int burnin) throws IOException, Importer.ImportException { progressStream.println("Setting node heights..."); progressStream.println("0 25 50 75 100"); progressStream.println("|--------------|--------------|--------------|--------------|"); int reportStepSize = totalTrees / 60; if (reportStepSize < 1) reportStepSize = 1; final FileReader fileReader = new FileReader(inputFileName); final NexusImporter importer = new NexusImporter(fileReader, true); // this call increments the clade counts and it shouldn't // this is remedied with removeClades call after while loop below CladeSystem cladeSystem = new CladeSystem(targetTree); final int nClades = cladeSystem.getCladeMap().size(); // allocate posterior tree nodes order once int[] postOrderList = new int[nClades]; BitSet[] ctarget = new BitSet[nClades]; BitSet[] ctree = new BitSet[nClades]; for (int k = 0; k < nClades; ++k) { ctarget[k] = new BitSet(); ctree[k] = new BitSet(); } cladeSystem.getTreeCladeCodes(targetTree, ctarget); // temp collecting heights inside loop allocated once double[] hs = new double[nClades]; // heights total sum from posterior trees double[] ths = new double[nClades]; totalTreesUsed = 0; int counter = 0; while (importer.hasTree()) { final Tree tree = importer.importNextTree(); if (counter >= burnin) { TreeUtils.preOrderTraversalList(tree, postOrderList); cladeSystem.getTreeCladeCodes(tree, ctree); for (int k = 0; k < nClades; ++k) { int j = postOrderList[k]; for (int i = 0; i < nClades; ++i) { if( isSubSet(ctarget[i], ctree[j]) ) { hs[i] = tree.getNodeHeight(tree.getNode(j)); } } } for (int k = 0; k < nClades; ++k) { ths[k] += hs[k]; } totalTreesUsed += 1; } if (counter > 0 && counter % reportStepSize == 0) { progressStream.print("*"); progressStream.flush(); } counter++; } cladeSystem.removeClades(targetTree, targetTree.getRoot(), true); for (int k = 0; k < nClades; ++k) { ths[k] /= totalTreesUsed; final NodeRef node = targetTree.getNode(k); targetTree.setNodeHeight(node, ths[k]); } fileReader.close(); progressStream.println(); progressStream.println(); return true; } }
add -ess option to treeAnnotator
src/dr/app/tools/TreeAnnotator.java
add -ess option to treeAnnotator
Java
lgpl-2.1
f2d6beef495a19883317ef0ac445ad4c109639ba
0
eXist-db/exist,zwobit/exist,ljo/exist,dizzzz/exist,ambs/exist,dizzzz/exist,lcahlander/exist,kohsah/exist,olvidalo/exist,dizzzz/exist,opax/exist,jensopetersen/exist,jessealama/exist,olvidalo/exist,MjAbuz/exist,zwobit/exist,jensopetersen/exist,eXist-db/exist,joewiz/exist,jensopetersen/exist,wolfgangmm/exist,patczar/exist,wshager/exist,jessealama/exist,olvidalo/exist,joewiz/exist,eXist-db/exist,joewiz/exist,ambs/exist,hungerburg/exist,wshager/exist,wolfgangmm/exist,wshager/exist,dizzzz/exist,jensopetersen/exist,dizzzz/exist,RemiKoutcherawy/exist,adamretter/exist,wshager/exist,patczar/exist,RemiKoutcherawy/exist,jessealama/exist,eXist-db/exist,kohsah/exist,ljo/exist,hungerburg/exist,patczar/exist,MjAbuz/exist,zwobit/exist,joewiz/exist,olvidalo/exist,ambs/exist,ljo/exist,patczar/exist,shabanovd/exist,wshager/exist,patczar/exist,jessealama/exist,shabanovd/exist,dizzzz/exist,olvidalo/exist,kohsah/exist,shabanovd/exist,adamretter/exist,shabanovd/exist,windauer/exist,RemiKoutcherawy/exist,lcahlander/exist,wshager/exist,windauer/exist,shabanovd/exist,wolfgangmm/exist,jessealama/exist,wolfgangmm/exist,opax/exist,lcahlander/exist,joewiz/exist,joewiz/exist,kohsah/exist,opax/exist,RemiKoutcherawy/exist,wolfgangmm/exist,hungerburg/exist,ambs/exist,hungerburg/exist,lcahlander/exist,RemiKoutcherawy/exist,MjAbuz/exist,opax/exist,adamretter/exist,zwobit/exist,ambs/exist,windauer/exist,kohsah/exist,jensopetersen/exist,jessealama/exist,adamretter/exist,windauer/exist,MjAbuz/exist,hungerburg/exist,adamretter/exist,ljo/exist,shabanovd/exist,ljo/exist,wolfgangmm/exist,eXist-db/exist,opax/exist,jensopetersen/exist,windauer/exist,lcahlander/exist,RemiKoutcherawy/exist,MjAbuz/exist,adamretter/exist,patczar/exist,MjAbuz/exist,eXist-db/exist,zwobit/exist,kohsah/exist,ambs/exist,windauer/exist,lcahlander/exist,ljo/exist,zwobit/exist
/* * eXist Open Source Native XML Database * Copyright (C) 2001-09 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.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 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 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery.functions.request; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.log4j.Logger; import org.exist.dom.QName; import org.exist.external.org.apache.commons.io.output.ByteArrayOutputStream; import org.exist.http.servlets.RequestWrapper; import org.exist.memtree.DocumentBuilderReceiver; import org.exist.memtree.MemTreeBuilder; import org.exist.util.MimeTable; import org.exist.util.MimeType; import org.exist.util.io.CachingFilterInputStream; import org.exist.util.io.FilterInputStreamCache; import org.exist.util.io.MemoryMappedFileFilterInputStreamCache; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Variable; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Base64BinaryValueType; import org.exist.xquery.value.BinaryValueFromInputStream; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.JavaObjectValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * @author Wolfgang Meier <[email protected]> */ public class GetData extends BasicFunction { protected static final Logger logger = Logger.getLogger(GetData.class); public final static FunctionSignature signature = new FunctionSignature( new QName("get-data", RequestModule.NAMESPACE_URI, RequestModule.PREFIX), "Returns the content of a POST request.If its a binary document xs:base64Binary is returned or if its an XML document a node() is returned. All other data is returned as an xs:string representaion. Returns an empty sequence if there is no data.", null, new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_ONE, "the content of a POST request") ); public GetData(XQueryContext context) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ @Override public Sequence eval(Sequence[] args, Sequence contextSequence)throws XPathException { RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI); // request object is read from global variable $request Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR); if(var == null || var.getValue() == null) { throw new XPathException(this, "No request object found in the current XQuery context."); } if(var.getValue().getItemType() != Type.JAVA_OBJECT) { throw new XPathException(this, "Variable $request is not bound to an Java object."); } JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0); if(value.getObject() instanceof RequestWrapper) { RequestWrapper request = (RequestWrapper)value.getObject(); //if the content length is unknown or 0, return if (request.getContentLength() == -1 || request.getContentLength() == 0) { return Sequence.EMPTY_SEQUENCE; } //first, get the content of the request InputStream is = null; try { is = request.getInputStream(); } catch(IOException ioe) { throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe); } //was there any POST content FilterInputStreamCache cache = null; try { if(is != null && is.available()>0) { //determine if exists mime database considers this binary data String contentType = request.getContentType(); if(contentType != null) { //strip off any charset encoding info if(contentType.indexOf(";") > -1) { contentType = contentType.substring(0, contentType.indexOf(";")); } MimeType mimeType = MimeTable.getInstance().getContentType(contentType); if(mimeType != null) { if(!mimeType.isXMLType()) { //binary data return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), is); } } } //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt) cache = new MemoryMappedFileFilterInputStreamCache(); is = new CachingFilterInputStream(cache, is); is.mark(Integer.MAX_VALUE); //try and parse as an XML documemnt, otherwise fallback to returning the data as a string context.pushDocumentContext(); try { //try and construct xml document from input stream, we use eXist's in-memory DOM implementation SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //TODO : we should be able to cope with context.getBaseURI() //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread InputSource src = new InputSource(new CloseShieldInputStream(is)); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true); reader.setContentHandler(receiver); reader.parse(src); Document doc = receiver.getDocument(); return (NodeValue)doc.getDocumentElement(); } catch(ParserConfigurationException e) { //do nothing, we will default to trying to return a string below } catch(SAXException e) { //do nothing, we will default to trying to return a string below } catch(IOException e) { //do nothing, we will default to trying to return a string below } finally { context.popDocumentContext(); is.reset(); //reset as we may need to reuse for string parsing } //not a valid XML document, return a string representation of the document String encoding = request.getCharacterEncoding(); if(encoding == null) { encoding = "UTF-8"; } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int l = -1; while ((l = is.read(buf)) > -1) { bos.write(buf, 0, l); } String s = new String(bos.toByteArray(), encoding); return new StringValue(s); } catch (IOException e) { throw new XPathException(this, "An IO exception occurred: " + e.getMessage(), e); } } else { //no post data return Sequence.EMPTY_SEQUENCE; } } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } finally { if(cache != null) { try { cache.invalidate(); } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } if(is != null) { try { is.close(); } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } } } else { throw new XPathException(this, "Variable $request is not bound to a Request object."); } return Sequence.EMPTY_SEQUENCE; } }
src/org/exist/xquery/functions/request/GetData.java
/* * eXist Open Source Native XML Database * Copyright (C) 2001-09 Wolfgang M. Meier * [email protected] * http://exist.sourceforge.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 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 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id$ */ package org.exist.xquery.functions.request; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.commons.io.input.CloseShieldInputStream; import org.apache.log4j.Logger; import org.exist.dom.QName; import org.exist.external.org.apache.commons.io.output.ByteArrayOutputStream; import org.exist.http.servlets.RequestWrapper; import org.exist.memtree.DocumentBuilderReceiver; import org.exist.memtree.MemTreeBuilder; import org.exist.util.MimeTable; import org.exist.util.MimeType; import org.exist.util.io.CachingFilterInputStream; import org.exist.util.io.FilterInputStreamCache; import org.exist.util.io.MemoryMappedFileFilterInputStreamCache; import org.exist.xquery.BasicFunction; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.Variable; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Base64BinaryValueType; import org.exist.xquery.value.BinaryValueFromInputStream; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.JavaObjectValue; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.Type; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; /** * @author Wolfgang Meier ([email protected]) */ public class GetData extends BasicFunction { protected static final Logger logger = Logger.getLogger(GetData.class); public final static FunctionSignature signature = new FunctionSignature( new QName( "get-data", RequestModule.NAMESPACE_URI, RequestModule.PREFIX), "Returns the content of a POST request.If its a binary document xs:base64Binary is returned or if its an XML document a node() is returned. All other data is returned as an xs:string representaion. Returns an empty sequence if there is no data.", null, new FunctionReturnSequenceType(Type.ITEM, Cardinality.ZERO_OR_ONE, "the content of a POST request")); public GetData(XQueryContext context) { super(context, signature); } /* (non-Javadoc) * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence) */ public Sequence eval(Sequence[] args, Sequence contextSequence)throws XPathException { RequestModule myModule = (RequestModule) context.getModule(RequestModule.NAMESPACE_URI); // request object is read from global variable $request Variable var = myModule.resolveVariable(RequestModule.REQUEST_VAR); if(var == null || var.getValue() == null) throw new XPathException(this, "No request object found in the current XQuery context."); if(var.getValue().getItemType() != Type.JAVA_OBJECT) throw new XPathException(this, "Variable $request is not bound to an Java object."); JavaObjectValue value = (JavaObjectValue) var.getValue().itemAt(0); if(value.getObject() instanceof RequestWrapper) { RequestWrapper request = (RequestWrapper)value.getObject(); //if the content length is unknown or 0, return if (request.getContentLength() == -1 || request.getContentLength() == 0) { return Sequence.EMPTY_SEQUENCE; } //first, get the content of the request InputStream is = null; try { is = request.getInputStream(); } catch(IOException ioe) { throw new XPathException(this, "An IO exception occurred: " + ioe.getMessage(), ioe); } //was there any POST content FilterInputStreamCache cache = null; try { if(is != null && is.available()>0) { //determine if exists mime database considers this binary data String contentType = request.getContentType(); if(contentType != null) { //strip off any charset encoding info if(contentType.indexOf(";") > -1) { contentType = contentType.substring(0, contentType.indexOf(";")); } MimeType mimeType = MimeTable.getInstance().getContentType(contentType); if(mimeType != null) { if(!mimeType.isXMLType()) { //binary data return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), is); } } } //we have to cache the input stream, so we can reread it, as we may use it twice (once for xml attempt and once for string attempt) cache = new MemoryMappedFileFilterInputStreamCache(); is = new CachingFilterInputStream(cache, is); is.mark(Integer.MAX_VALUE); //try and parse as an XML documemnt, otherwise fallback to returning the data as a string context.pushDocumentContext(); try { //try and construct xml document from input stream, we use eXist's in-memory DOM implementation SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); //TODO : we should be able to cope with context.getBaseURI() //we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread InputSource src = new InputSource(new CloseShieldInputStream(is)); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); MemTreeBuilder builder = context.getDocumentBuilder(); DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true); reader.setContentHandler(receiver); reader.parse(src); Document doc = receiver.getDocument(); return (NodeValue)doc.getDocumentElement(); } catch(ParserConfigurationException e) { //do nothing, we will default to trying to return a string below } catch(SAXException e) { //do nothing, we will default to trying to return a string below } catch(IOException e) { //do nothing, we will default to trying to return a string below } finally { context.popDocumentContext(); is.reset(); //reset as we may need to reuse for string parsing } //not a valid XML document, return a string representation of the document String encoding = request.getCharacterEncoding(); if(encoding == null) { encoding = "UTF-8"; } try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int l = -1; while ((l = is.read(buf)) > -1) { bos.write(buf, 0, l); } String s = new String(bos.toByteArray(), encoding); return new StringValue(s); } catch (IOException e) { throw new XPathException(this, "An IO exception occurred: " + e.getMessage(), e); } } else { //no post data return Sequence.EMPTY_SEQUENCE; } } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } finally { if(cache != null) { try { cache.invalidate(); } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } if(is != null) { try { is.close(); } catch(IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } } } else { throw new XPathException(this, "Variable $request is not bound to a Request object."); } return Sequence.EMPTY_SEQUENCE; } }
[ignore] reformatted code svn path=/trunk/eXist/; revision=13484
src/org/exist/xquery/functions/request/GetData.java
[ignore] reformatted code
Java
apache-2.0
2e8f60faed0aba831d7eeaeefc7ed90085cd81d7
0
skycat36/pevgeny
package ru.job4j.array; /** * @author Evgeny Popov * @since 1.0 */ public class MergeArray { /** * Merge two array in one. * @param oneArr - first array * @param twoArr - second array. * @return Merged array. */ public int[] merge(int[] oneArr, int[] twoArr) { int lenOneArr = oneArr.length , lenTwoArr = twoArr.length ; // ะ”ะปะธะฝะฝะฐ 1-ะณะพ ะธ 2-ะณะพ ะผะฐััะธะฒะฐ int[] threeArr = new int[lenOneArr + lenTwoArr]; int i = 0, j = 0; while (i < lenOneArr && j < lenTwoArr) { if (oneArr[i] < twoArr[j]) { threeArr[i + j] = oneArr[i]; i++; } else { threeArr[i + j] = twoArr[j]; j++; } } while (i < lenOneArr) { // ะ•ัะปะธ ะดะพัั‚ะธะณะฝัƒั‚ ะบะพะฝะตั† ะพะดะฝะพะณะพ ะธะท ะผะฐััะธะฒะฐ ั†ะธะบะป ะดะพะฟะธัั‹ะฒะฐะตั‚ ะพัั‚ะฐะฒัˆัƒัŽัั ั‡ะฐัั‚ัŒ ะดะพะบะพะฝั†ะฐ. threeArr[i + j] = oneArr[i]; i++; } while (j < lenTwoArr) { threeArr[i + j] = twoArr[j]; j++; } return threeArr; } }
chapter_001/src/main/java/ru/job4j/array/MergeArray.java
package ru.job4j.array; public class MergeArray { public int[] merge(int[] oneArr, int[] twoArr) { int lenOneArr = oneArr.length , lenTwoArr = twoArr.length ; // ะ”ะปะธะฝะฝะฐ 1-ะณะพ ะธ 2-ะณะพ ะผะฐััะธะฒะฐ int[] threeArr = new int[lenOneArr + lenTwoArr]; int i = 0, j = 0; while (i < lenOneArr && j < lenTwoArr) { if (oneArr[i] < twoArr[j]) { threeArr[i + j] = oneArr[i]; i++; } else { threeArr[i + j] = twoArr[j]; j++; } } while (i < lenOneArr) { // ะ•ัะปะธ ะดะพัั‚ะธะณะฝัƒั‚ ะบะพะฝะตั† ะพะดะฝะพะณะพ ะธะท ะผะฐััะธะฒะฐ ั†ะธะบะป ะดะพะฟะธัั‹ะฒะฐะตั‚ ะพัั‚ะฐะฒัˆัƒัŽัั ั‡ะฐัั‚ัŒ ะดะพะบะพะฝั†ะฐ. threeArr[i + j] = oneArr[i]; i++; } while (j < lenTwoArr) { threeArr[i + j] = twoArr[j]; j++; } return threeArr; } }
Complite control work [184]
chapter_001/src/main/java/ru/job4j/array/MergeArray.java
Complite control work [184]
Java
apache-2.0
47542bf24c9c0678406c9dc133b2e59beb6a25cb
0
ajordens/igor,spinnaker/igor,spinnaker/igor,spinnaker/igor,ajordens/igor,ajordens/igor,ajordens/igor
/* * Copyright 2020 Netflix, 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.netflix.spinnaker.igor.plugins; import com.netflix.discovery.DiscoveryClient; import com.netflix.spectator.api.Registry; import com.netflix.spinnaker.igor.IgorConfigurationProperties; import com.netflix.spinnaker.igor.history.EchoService; import com.netflix.spinnaker.igor.plugins.front50.PluginReleaseService; import com.netflix.spinnaker.igor.plugins.model.PluginEvent; import com.netflix.spinnaker.igor.plugins.model.PluginRelease; import com.netflix.spinnaker.igor.polling.*; import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService; import com.netflix.spinnaker.security.AuthenticatedRequest; import java.time.Instant; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import lombok.Data; public class PluginsBuildMonitor extends CommonPollingMonitor< PluginsBuildMonitor.PluginDelta, PluginsBuildMonitor.PluginPollingDelta> { private final PluginReleaseService pluginInfoService; private final PluginCache cache; private final Optional<EchoService> echoService; public PluginsBuildMonitor( IgorConfigurationProperties igorProperties, Registry registry, DynamicConfigService dynamicConfigService, Optional<DiscoveryClient> discoveryClient, Optional<LockService> lockService, PluginReleaseService pluginInfoService, PluginCache cache, Optional<EchoService> echoService) { super(igorProperties, registry, dynamicConfigService, discoveryClient, lockService); this.pluginInfoService = pluginInfoService; this.cache = cache; this.echoService = echoService; } @Override protected PluginPollingDelta generateDelta(PollContext ctx) { return new PluginPollingDelta( pluginInfoService.getPluginReleasesSince(cache.getLastPollCycleTimestamp()).stream() .map(PluginDelta::new) .collect(Collectors.toList())); } @Override protected void commitDelta(PluginPollingDelta delta, boolean sendEvents) { log.info("Found {} new plugin releases", delta.items.size()); delta.items.forEach( item -> { if (sendEvents) { postEvent(item.pluginRelease); } else { log.debug("{} processed, but not sending event", item.pluginRelease); } }); delta.items.stream() .map(it -> Instant.parse(it.pluginRelease.getTimestamp())) .max(Comparator.naturalOrder()) .ifPresent(cache::setLastPollCycleTimestamp); } private void postEvent(PluginRelease release) { if (!echoService.isPresent()) { log.warn("Cannot send new plugin notification: Echo is not configured"); registry .counter( missedNotificationId.withTag("monitor", PluginsBuildMonitor.class.getSimpleName())) .increment(); } else if (release != null) { AuthenticatedRequest.allowAnonymous( () -> echoService.get().postEvent(new PluginEvent(release))); log.debug("{} event posted", release); } } @Override public void poll(boolean sendEvents) { pollSingle(new PollContext("front50")); } @Override public String getName() { return "pluginsMonitor"; } @Data static class PluginDelta implements DeltaItem { private final PluginRelease pluginRelease; } @Data static class PluginPollingDelta implements PollingDelta<PluginDelta> { private final List<PluginDelta> items; } }
igor-monitor-plugins/src/main/java/com/netflix/spinnaker/igor/plugins/PluginsBuildMonitor.java
/* * Copyright 2020 Netflix, 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.netflix.spinnaker.igor.plugins; import com.netflix.discovery.DiscoveryClient; import com.netflix.spectator.api.Registry; import com.netflix.spinnaker.igor.IgorConfigurationProperties; import com.netflix.spinnaker.igor.history.EchoService; import com.netflix.spinnaker.igor.plugins.front50.PluginReleaseService; import com.netflix.spinnaker.igor.plugins.model.PluginEvent; import com.netflix.spinnaker.igor.plugins.model.PluginRelease; import com.netflix.spinnaker.igor.polling.*; import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService; import com.netflix.spinnaker.security.AuthenticatedRequest; import java.time.Instant; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import lombok.Data; public class PluginsBuildMonitor extends CommonPollingMonitor< PluginsBuildMonitor.PluginDelta, PluginsBuildMonitor.PluginPollingDelta> { private final PluginReleaseService pluginInfoService; private final PluginCache cache; private final Optional<EchoService> echoService; public PluginsBuildMonitor( IgorConfigurationProperties igorProperties, Registry registry, DynamicConfigService dynamicConfigService, Optional<DiscoveryClient> discoveryClient, Optional<LockService> lockService, PluginReleaseService pluginInfoService, PluginCache cache, Optional<EchoService> echoService) { super(igorProperties, registry, dynamicConfigService, discoveryClient, lockService); this.pluginInfoService = pluginInfoService; this.cache = cache; this.echoService = echoService; } @Override protected PluginPollingDelta generateDelta(PollContext ctx) { return new PluginPollingDelta( pluginInfoService.getPluginReleasesSince(cache.getLastPollCycleTimestamp()).stream() .map(PluginDelta::new) .collect(Collectors.toList())); } @Override protected void commitDelta(PluginPollingDelta delta, boolean sendEvents) { delta.items.forEach( item -> { if (sendEvents) { postEvent(item.pluginRelease); } else { log.debug("{} processed, but not sending event", item.pluginRelease); } }); delta.items.stream() .map(it -> Instant.parse(it.pluginRelease.getTimestamp())) .max(Comparator.naturalOrder()) .ifPresent(cache::setLastPollCycleTimestamp); } private void postEvent(PluginRelease release) { if (!echoService.isPresent()) { log.warn("Cannot send new plugin notification: Echo is not configured"); registry .counter( missedNotificationId.withTag("monitor", PluginsBuildMonitor.class.getSimpleName())) .increment(); } else if (release != null) { AuthenticatedRequest.allowAnonymous( () -> echoService.get().postEvent(new PluginEvent(release))); log.debug("{} event posted", release); } } @Override public void poll(boolean sendEvents) { pollSingle(new PollContext("front50")); } @Override public String getName() { return "pluginsMonitor"; } @Data static class PluginDelta implements DeltaItem { private final PluginRelease pluginRelease; } @Data static class PluginPollingDelta implements PollingDelta<PluginDelta> { private final List<PluginDelta> items; } }
chore(plugins): Add some additional logging (#737)
igor-monitor-plugins/src/main/java/com/netflix/spinnaker/igor/plugins/PluginsBuildMonitor.java
chore(plugins): Add some additional logging (#737)
Java
apache-2.0
ef621f6a9493d41ce4cfe73bc6154aecb8d54c7c
0
prestodb/tempto,prestodb/tempto
/* * 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.teradata.tempto.fulfillment.table.hive.tpcds; import com.google.common.base.Charsets; import com.teradata.tempto.fulfillment.table.hive.HiveDataSource; import com.teradata.tempto.hadoop.hdfs.HdfsClient.RepeatableContentProducer; import com.teradata.tpcds.Results; import com.teradata.tpcds.Session; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import static com.teradata.tpcds.Results.constructResults; import static java.lang.String.format; import static java.util.Collections.singleton; import static java.util.Objects.requireNonNull; public class TpcdsDataSource implements HiveDataSource { private static final String DATA_REVISION = "v.1.0"; private final TpcdsTable table; private final int scaleFactor; public TpcdsDataSource(TpcdsTable table, int scaleFactor) { checkArgument(scaleFactor > 0, "Scale factor should be greater than 0: %s", scaleFactor); this.table = table; this.scaleFactor = scaleFactor; } @Override public String getPathSuffix() { return format("tpcds/sf-%d/%s", scaleFactor, table.name()).replaceAll("\\.", "_"); } @Override public Collection<RepeatableContentProducer> data() { return singleton(() -> new StringIteratorInputStream(generate())); } private Iterator<String> generate() { Session session = Session.getDefaultSession() .withScale(scaleFactor) .withParallelism(1) .withTable(table.getTable()) .withNoSexism(false); Results results = constructResults(table.getTable(), session); return StreamSupport.stream(results.spliterator(), false) .flatMap(rowBatch -> rowBatch.stream()) .map(this::formatRow) .flatMap(row -> Stream.of(row, "\n")) .iterator(); } private String formatRow(List<String> row) { return row.stream() .map(column -> column == null ? "\\N" : column) .collect(Collectors.joining("|")) + "|"; } @Override public String revisionMarker() { return DATA_REVISION; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TpcdsDataSource that = (TpcdsDataSource) o; return scaleFactor == that.scaleFactor && table == that.table; } @Override public int hashCode() { return Objects.hash(table, scaleFactor); } private static class StringIteratorInputStream extends InputStream { private final Iterator<String> data; public int position; public byte[] value; public StringIteratorInputStream(Iterator<String> data) { this.data = requireNonNull(data, "data is null"); } @Override public int read() throws IOException { if (value == null) { if (data.hasNext()) { position = 0; value = data.next().getBytes(Charsets.UTF_8); } else { return -1; } } if (position < value.length) { return value[position++]; } else { value = null; return read(); } } } }
tempto-core/src/main/java/com/teradata/tempto/fulfillment/table/hive/tpcds/TpcdsDataSource.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 com.teradata.tempto.fulfillment.table.hive.tpcds; import com.teradata.tempto.fulfillment.table.hive.HiveDataSource; import com.teradata.tempto.hadoop.hdfs.HdfsClient.RepeatableContentProducer; import com.teradata.tpcds.Results; import com.teradata.tpcds.Session; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkArgument; import static com.teradata.tpcds.Results.constructResults; import static java.lang.String.format; import static java.util.Collections.singleton; import static java.util.Objects.requireNonNull; public class TpcdsDataSource implements HiveDataSource { private static final String DATA_REVISION = "v.1.0"; private final TpcdsTable table; private final int scaleFactor; public TpcdsDataSource(TpcdsTable table, int scaleFactor) { checkArgument(scaleFactor > 0, "Scale factor should be greater than 0: %s", scaleFactor); this.table = table; this.scaleFactor = scaleFactor; } @Override public String getPathSuffix() { return format("tpcds/sf-%d/%s", scaleFactor, table.name()).replaceAll("\\.", "_"); } @Override public Collection<RepeatableContentProducer> data() { return singleton(() -> new StringIteratorInputStream(generate())); } private Iterator<String> generate() { Session session = Session.getDefaultSession() .withScale(scaleFactor) .withParallelism(1) .withTable(table.getTable()) .withNoSexism(false); Results results = constructResults(table.getTable(), session); return StreamSupport.stream(results.spliterator(), false) .flatMap(rowBatch -> rowBatch.stream()) .map(this::formatRow) .flatMap(row -> Stream.of(row, "\n")) .iterator(); } private String formatRow(List<String> row) { return row.stream() .map(column -> column == null ? "\\N" : column) .collect(Collectors.joining("|")) + "|"; } @Override public String revisionMarker() { return DATA_REVISION; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TpcdsDataSource that = (TpcdsDataSource) o; return scaleFactor == that.scaleFactor && table == that.table; } @Override public int hashCode() { return Objects.hash(table, scaleFactor); } private static class StringIteratorInputStream extends InputStream { private final Iterator<String> data; public int position; public String value; public StringIteratorInputStream(Iterator<String> data) { this.data = requireNonNull(data, "data is null"); } @Override public int read() throws IOException { if (value == null) { if (data.hasNext()) { position = 0; value = data.next(); } else { return -1; } } if (position < value.length()) { return value.charAt(position++); } else { value = null; return read(); } } } }
Handle UTF data for TPC-H tables
tempto-core/src/main/java/com/teradata/tempto/fulfillment/table/hive/tpcds/TpcdsDataSource.java
Handle UTF data for TPC-H tables
Java
apache-2.0
fa8c8c23b177cc9514e038c1c95877be81dabf88
0
chunlinyao/fop,chunlinyao/fop,apache/fop,chunlinyao/fop,apache/fop,apache/fop,chunlinyao/fop,chunlinyao/fop,apache/fop,apache/fop
/* * Copyright 1999-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. */ /* $Id$ */ package org.apache.fop.fo.properties; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.Constants; import org.apache.fop.fo.PropertyList; /** * This subclass of LengthProperty.Maker handles the special treatment of * border width described in 7.7.20. */ public class BorderWidthPropertyMaker extends LengthProperty.Maker { int borderStyleId = 0; /** * Create a length property which check the value of the border-*-style * property and return a length of 0 when the style is "none". * @param propId the border-*-width of the property. */ public BorderWidthPropertyMaker(int propId) { super(propId); } /** * Set the propId of the style property for the same side. * @param borderStyleId */ public void setBorderStyleId(int borderStyleId) { this.borderStyleId = borderStyleId; } /** * Check the value of the style property and return a length of 0 when * the style is NONE. * @see org.apache.fop.fo.properties.PropertyMaker#get(int, PropertyList, boolean, boolean) */ public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws FOPException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); // Calculate the values as described in 7.7.20. Property style = propertyList.get(borderStyleId); if (style.getEnum() == Constants.NONE) { return new FixedLength(0); } return p; } }
src/java/org/apache/fop/fo/properties/BorderWidthPropertyMaker.java
/* * Copyright 1999-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. */ /* $Id$ */ package org.apache.fop.fo.properties; import org.apache.fop.apps.FOPException; import org.apache.fop.fo.Constants; import org.apache.fop.fo.PropertyList; /** * This subclass of LengthProperty.Maker handles the special treatment of * border width described in 7.7.20. */ public class BorderWidthPropertyMaker extends LengthProperty.Maker { int borderStyleId = 0; /** * Create a length property which check the value of the border-*-style * property and return a length of 0 when the style is "none". * @param propId the border-*-width of the property. */ public BorderWidthPropertyMaker(int propId) { super(propId); } /** * Set the propId of the style property for the same side. * @param borderStyleId */ public void setBorderStyleId(int borderStyleId) { this.borderStyleId = borderStyleId; } /** * Check the value of the style property and return a length of 0 when * the style is NONE. * @see org.apache.fop.fo.properties.PropertyMaker#get(int, PropertyList, boolean, boolean) */ public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws FOPException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); // Calculate the values as described in 7.7.20. Property style = propertyList.get(borderStyleId); if (style.getEnum() == Constants.NONE) { // TODO: bckfnn reenable return p; // new LengthProperty(new FixedLength(0)); } return p; } }
Force a 0mpt border-width when the border-style is 'none'. git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@197963 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/fop/fo/properties/BorderWidthPropertyMaker.java
Force a 0mpt border-width when the border-style is 'none'.
Java
apache-2.0
99dc0a6624b07756cfefbdbc2a5b8434a7782219
0
akhilesh0707/sync-android,nuan-nuan/sync-android,akhilesh0707/sync-android,cloudant/sync-android,nuan-nuan/sync-android,nuan-nuan/sync-android,cloudant/sync-android,akhilesh0707/sync-android
/** * Copyright (c) 2013 Cloudant, Inc. 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.cloudant.sync.indexing; import com.cloudant.sync.datastore.ConflictException; import com.cloudant.sync.datastore.DatastoreExtended; import com.cloudant.sync.datastore.DatastoreManager; import com.cloudant.sync.datastore.DocumentBody; import com.cloudant.sync.datastore.DocumentBodyFactory; import com.cloudant.sync.datastore.DocumentRevision; import com.cloudant.sync.sqlite.Cursor; import com.cloudant.sync.sqlite.SQLDatabase; import com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper; import com.cloudant.sync.util.SQLDatabaseTestUtils; import com.cloudant.sync.util.TestUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static org.hamcrest.Matchers.containsInAnyOrder; public class IndexManagerIndexTest { SQLiteWrapper database = null; DatastoreExtended datastore = null; IndexManager indexManager = null; List<DocumentBody> dbBodies = null; private String datastoreManagerPath; @Before public void setUp() throws IOException, SQLException { datastoreManagerPath = TestUtils.createTempTestingDir(this.getClass().getName()); DatastoreManager datastoreManager = new DatastoreManager(this.datastoreManagerPath); datastore = (DatastoreExtended) datastoreManager.openDatastore(getClass().getSimpleName()); indexManager = new IndexManager(datastore); database = (SQLiteWrapper) indexManager.getDatabase(); createTestBDBodies(); } @After public void tearDown() throws Exception { TestUtils.deleteDatabaseQuietly(database); TestUtils.deleteTempTestingDir(datastoreManagerPath); } private void createTestBDBodies() throws IOException { dbBodies = new ArrayList<DocumentBody>(); for (int i = 0; i < 7; i++) { dbBodies.add(TestUtils.createBDBody("fixture/index" + "_" + i + ".json")); } } @Test public void close_sqlDatabaseShouldBeClosed() { Assert.assertTrue(indexManager.getDatabase().isOpen()); indexManager.onDatastoreClosed(null); Assert.assertFalse(indexManager.getDatabase().isOpen()); } @Test public void getIndex_newIndex_allDataShouldBePersistent() throws IndexExistsException { indexManager.ensureIndexed("A", "a"); Index index = indexManager.getIndex("A"); Assert.assertEquals("A", index.getName()); Assert.assertTrue(index.getLastSequence().equals(-1l)); } @Test public void getIndex_indexNotExist_returnNull() { Index index = indexManager.getIndex("Z"); Assert.assertNull(index); } @Test public void ensuredIndexed_newIndex_indexShouldBeCreatedAndPersistent() throws IndexExistsException, SQLException { { // String index indexManager.ensureIndexed("Album", "album"); Index album = indexManager.getIndex("Album"); assertIndexDataFields("Album", "album", IndexType.STRING, -1L, album); String tableName = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "Album"); assertTableCreated(tableName); } { // Integer index indexManager.ensureIndexed("a_123", "abc_123", IndexType.INTEGER); Index artist = indexManager.getIndex("a_123"); assertIndexDataFields("a_123", "abc_123", IndexType.INTEGER, -1L, artist); String tableName = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "a_123"); assertTableCreated(tableName); } } private void assertIndexDataFields(String expectedIndexName, String expectedFieldName, IndexType expectedIndexType, Long expectLastSequence, Index actual) throws SQLException { Assert.assertEquals(expectedIndexName, actual.getName()); Assert.assertEquals(expectedIndexType, actual.getIndexType()); Assert.assertTrue(actual.getLastSequence().equals(expectLastSequence)); } private void assertTableCreated(String name) throws SQLException { Set<String> tables = SQLDatabaseTestUtils.getAllTableNames(database); Assert.assertTrue(tables.contains(name)); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexNamesButDifferentField() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album2"); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexNamesButDifferentType() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album", IndexType.INTEGER); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexes() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album"); } @Test public void getAllIndexes_allIndexesShouldBeReturned() throws IndexExistsException { Assert.assertEquals(0, indexManager.getAllIndexes().size()); Index albumIndex = createAndGetIndex("album", "album", IndexType.STRING); Assert.assertEquals(1, indexManager.getAllIndexes().size()); indexManager.ensureIndexed("artist", "artist", IndexType.INTEGER); Index artistIndex = indexManager.getIndex("artist"); Set<Index> indexes = indexManager.getAllIndexes(); Assert.assertEquals(2, indexes.size()); Assert.assertTrue(indexes.contains(albumIndex)); Assert.assertTrue(indexes.contains(artistIndex)); for(Index index : indexes) { if(index.getName().equals("album")) { assertSameIndex(index, albumIndex); } else if (index.getName().equals("artist")) { assertSameIndex(index, artistIndex); } } } private void assertSameIndex(Index l, Index r) { Assert.assertEquals(l.getName(), r.getName()); Assert.assertEquals(l.getIndexType(), r.getIndexType()); Assert.assertEquals(l.getLastSequence(), r.getLastSequence()); } @Test public void deleteIndex_delete_indexShouldBeDeleted() throws IndexExistsException, SQLException { Index index = createAndGetIndex("album", "album", IndexType.STRING); Assert.assertNotNull(index); indexManager.deleteIndex(index.getName()); Assert.assertEquals(0, indexManager.getAllIndexes().size()); String indexTable = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "album"); assertTableDeleted(indexTable); } private void assertTableDeleted(String table) throws SQLException { Set<String> tables = SQLDatabaseTestUtils.getAllTableNames(database); Assert.assertFalse(tables.contains(table)); } @Test(expected = IllegalArgumentException.class) public void deleteIndex_indexNotExist_exception() { Assert.assertNull(indexManager.getIndex("Z")); indexManager.deleteIndex("Z"); } @Test public void ensuredIndexed_documentExistBeforeIndexCreated_existingDocShouldBeIndexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); Index index = createAndGetIndex("album", "album", IndexType.STRING); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj1); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj2); } @Test public void ensure_custom_indexing_function_used_non_null_indexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); final class TestIF implements IndexFunction<String> { public List<String> indexedValues(String indexName, Map map) { return Arrays.asList("fred"); } } this.indexManager.ensureIndexed("album", IndexType.STRING, new TestIF()); Index index = indexManager.getIndex("album"); for (DocumentRevision obj : new DocumentRevision[]{obj0,obj1,obj2}) { IndexTestUtils.assertDBObjectInIndexWithValue( database, index, obj, "fred" ); } } @Test public void ensure_custom_indexing_function_used_null_not_indexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); final class TestIF implements IndexFunction<String> { public List<String> indexedValues(String indexName, Map map) { return null; } } this.indexManager.ensureIndexed("album", IndexType.STRING, new TestIF()); Index index = indexManager.getIndex("album"); for (DocumentRevision obj : new DocumentRevision[]{obj0,obj1,obj2}) { IndexTestUtils.assertDBObjectNotInIndex( database, index, obj ); } } @Test public void createStringIndex_documentInsertedAfterIndexCreated_documentShouldBeIndexed() throws IndexExistsException, SQLException { Index index = createAndGetIndex("album", "album", IndexType.STRING); DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj1); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj2); } @Test public void createLongIndex_documentInsertedAfterIndexCreated_documentShouldBeIndexed() throws IndexExistsException, SQLException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); } { DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } } @Test public void createLongIndex_indexValueIsBigLong_documentShouldBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_really_big_long.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } @Test public void createLongIndex_indexValueIsFloat_documentShouldBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_float.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } @Test public void createLongIndex_indexValueConversionNotSupported_documentShouldNotBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_string.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj1); } @Test public void indexString_documentWithValidField_indexRowShouldBeAdded() throws IndexExistsException, SQLException, IOException { Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); } @Test public void indexString_documentWithInvalidField_indexRowShouldNotBeAdded() throws IndexExistsException, IOException, SQLException { Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexString_documentUpdated_indexRowShouldBeUpdated() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); DocumentRevision obj = datastore.createDocument(TestUtils.createBDBody("fixture/string_index_valid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), TestUtils.createBDBody("fixture/string_index_valid_field_updated.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj2); } @Test public void indexString_documentUpdatedFromInvalidToValidValue_indexRowShouldBeUpdated() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); DocumentRevision obj = datastore.createDocument(TestUtils.createBDBody("fixture/string_index_invalid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), TestUtils.createBDBody("fixture/string_index_valid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj2); } private Index createAndGetIndex(String indexName, String filedName, IndexType type) throws IndexExistsException { indexManager.ensureIndexed(indexName, filedName, type); return indexManager.getIndex(indexName); } @Test public void indexString_documentUpdatedWithInvalidValue_indexValueShouldBeRemoved() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/string_index_invalid_field.json")); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj2); } @Test public void indexString_documentDeleted_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); datastore.deleteDocument(obj.getId(), obj.getRevision()); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexInteger_documentCreated_indexRowShouldBeAdded() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); } @Test public void indexInteger_documentCreatedWithInvalidIndexValue_indexRowShouldNotBeAdded() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexInteger_documentUpdated_indexValueShouldBeUpdate() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field_updated.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj2); } @Test public void indexInteger_documentUpdatedFromInvalidToValidValue_indexValueShouldBeUpdate() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj2); } @Test public void indexInteger_documentUpdatedWithInvalidIndexValue_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj2); } @Test public void indexInteger_documentDeleted_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); datastore.deleteDocument(obj.getId(), obj.getRevision()); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void multiIndex_documentWithoutTheField_notIndexed() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(0)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId()); } @Test public void multiIndex_documentFieldWithListOfTwo_twoIndexValueAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(1)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop", "Rock"); } @Test public void multiIndex_documentFieldWithListOfOne_oneIndexValueAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(3)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop"); } @Test public void multiIndex_documentFieldWithDuplicatedValues_noDuplicatedValuesAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(4)); // this Document has field: genre: [ "Pop", "Pop" ], and assert // only one entry added for "Pop" indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop"); } @Test public void index_fieldWithUnsupportedValue_unsupportedValueShouldBeIgnored() throws IndexExistsException, SQLException, IOException { DocumentBody body = TestUtils.createBDBody("fixture/index_with_unsupported_value.json"); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop", "Rock"); } @Test public void index_valueWithLeadingTailingSpaces_spacesRemoved() throws IndexExistsException, SQLException, IOException { DocumentBody body = TestUtils.createBDBody("fixture/index_with_spaces.json"); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), " Pop", "Rock ", " R & B "); } @Test public void index_fieldWith10KValues_allValuesShouldBeAdded() throws IndexExistsException, SQLException, IOException { Map m = new HashMap<String, String>(); List<String> tags = new ArrayList<String>(100000); for(int i = 0 ; i < 100000 ; i ++) { tags.add("tag" + i); } m.put("Tag", tags); DocumentBody body = DocumentBodyFactory.create(m); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Tag", "Tag", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), tags.toArray(new String[]{})); } // test that index updates itself on create/update/delete @Test public void index_UpdateCrud() throws IndexExistsException, SQLException, ConflictException { Index index = createAndGetIndex("title", "title", IndexType.STRING); // create DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); this.assertIndexed(database, index, obj1.getId(), "Politik"); // update Map<String,Object> map = obj1.getBody().asMap(); map.put("title", "Another Green Day"); DocumentBody body = DocumentBodyFactory.create(map); DocumentRevision obj2 = datastore.updateDocument(obj1.getId(), obj1.getRevision(), body); Assert.assertEquals(obj1.getId(), obj2.getId()); this.assertIndexed(database, index, obj2.getId(), "Another Green Day"); // delete datastore.deleteDocument(obj2.getId(), obj2.getRevision()); this.assertNotIndexed(database, index, obj2.getId()); } /** * A sanity-check that updating the datastore from many threads * doesn't cause the index manager to balk. */ @Test public void index_UpdateCrudMultiThreaded() throws IndexExistsException, SQLException, ConflictException, InterruptedException { int n_threads = 3; final int n_docs = 100; // We'll later search for search == success final Map<String,String> matching = ImmutableMap.of("search", "success"); final Map<String,String> nonmatching = ImmutableMap.of("search", "failure"); indexManager.ensureIndexed("search", "search", IndexType.STRING); final List<String> matching_ids = Collections.synchronizedList(new ArrayList<String>()); // When run, this thread creates n_docs documents with unique // names in the datastore. A subset of these // will be matched by our query to the datastore later, which // we record in the matching_ids list. class PopulateThread extends Thread { @Override public void run() { String docId; final String thread_id; DocumentBody body; thread_id = Thread.currentThread().getName(); for (int i = 0; i < n_docs; i++) { docId = String.format("%s-%s", thread_id, i); if ((i % 2) == 0) { // even numbers create matching docs body = DocumentBodyFactory.create(matching); matching_ids.add(docId); } else { body = DocumentBodyFactory.create(nonmatching); } datastore.createDocument(docId, body); } // we're not on the main thread, so we must close our own connection datastore.getSQLDatabase().close(); } } List<Thread> threads = new ArrayList<Thread>(); // Create, start and wait for the threads to complete for (int i = 0; i < n_threads; i++) { threads.add(new PopulateThread()); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // Check appropriate entries in index QueryBuilder q = new QueryBuilder(); q.index("search").equalTo("success"); QueryResult result = indexManager.query(q.build()); List<DocumentRevision> docRevisions = Lists.newArrayList(result); List<String> docIds = new ArrayList<String>(); for (DocumentRevision r : docRevisions) { docIds.add(r.getId()); } Assert.assertEquals(matching_ids.size(), docIds.size()); for (String id : matching_ids) { Assert.assertTrue(docIds.contains(id)); } } private void assertNotIndexed(SQLDatabase database, Index index, String docId) throws SQLException { String table = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, index.getName()); Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? ", new String[]{String.valueOf(docId)} ); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(cursor.getInt(0))); } private void assertIndexed(SQLDatabase database, Index index, String docId, String ... expectedValues) throws SQLException { String table = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, index.getName()); assertIndexedValueCount(database, docId, table, expectedValues); for(String value : expectedValues) { assertIndexedValue(database, docId, table, value); } } private void assertIndexedValue(SQLDatabase database, String docId, String table, String value) throws SQLException { Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? and value = ? ", new String[]{String.valueOf(docId), value}); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(1), Integer.valueOf(cursor.getInt(0))); } private void assertIndexedValueCount(SQLDatabase database, String docId, String table, String[] expectedValues) throws SQLException { Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? ", new String[]{String.valueOf(docId)}); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(expectedValues.length), Integer.valueOf(cursor.getInt(0))); } }
src/test/java/com/cloudant/sync/indexing/IndexManagerIndexTest.java
/** * Copyright (c) 2013 Cloudant, Inc. 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.cloudant.sync.indexing; import com.cloudant.sync.datastore.ConflictException; import com.cloudant.sync.datastore.DatastoreExtended; import com.cloudant.sync.datastore.DatastoreManager; import com.cloudant.sync.datastore.DocumentBody; import com.cloudant.sync.datastore.DocumentBodyFactory; import com.cloudant.sync.datastore.DocumentRevision; import com.cloudant.sync.sqlite.Cursor; import com.cloudant.sync.sqlite.SQLDatabase; import com.cloudant.sync.sqlite.sqlite4java.SQLiteWrapper; import com.cloudant.sync.util.SQLDatabaseTestUtils; import com.cloudant.sync.util.TestUtils; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import static org.hamcrest.Matchers.containsInAnyOrder; public class IndexManagerIndexTest { SQLiteWrapper database = null; DatastoreExtended datastore = null; IndexManager indexManager = null; List<DocumentBody> dbBodies = null; private String datastoreManagerPath; @Before public void setUp() throws IOException, SQLException { datastoreManagerPath = TestUtils.createTempTestingDir(this.getClass().getName()); DatastoreManager datastoreManager = new DatastoreManager(this.datastoreManagerPath); datastore = (DatastoreExtended) datastoreManager.openDatastore(getClass().getSimpleName()); indexManager = new IndexManager(datastore); database = (SQLiteWrapper) indexManager.getDatabase(); createTestBDBodies(); } @After public void tearDown() throws Exception { TestUtils.deleteDatabaseQuietly(database); TestUtils.deleteTempTestingDir(datastoreManagerPath); } private void createTestBDBodies() throws IOException { dbBodies = new ArrayList<DocumentBody>(); for (int i = 0; i < 7; i++) { dbBodies.add(TestUtils.createBDBody("fixture/index" + "_" + i + ".json")); } } @Test public void close_sqlDatabaseShouldBeClosed() { Assert.assertTrue(indexManager.getDatabase().isOpen()); indexManager.onDatastoreClosed(null); Assert.assertFalse(indexManager.getDatabase().isOpen()); } @Test public void getIndex_newIndex_allDataShouldBePersistent() throws IndexExistsException { indexManager.ensureIndexed("A", "a"); Index index = indexManager.getIndex("A"); Assert.assertEquals("A", index.getName()); Assert.assertTrue(index.getLastSequence().equals(-1l)); } @Test public void getIndex_indexNotExist_returnNull() { Index index = indexManager.getIndex("Z"); Assert.assertNull(index); } @Test public void ensuredIndexed_newIndex_indexShouldBeCreatedAndPersistent() throws IndexExistsException, SQLException { { // String index indexManager.ensureIndexed("Album", "album"); Index album = indexManager.getIndex("Album"); assertIndexDataFields("Album", "album", IndexType.STRING, -1L, album); String tableName = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "Album"); assertTableCreated(tableName); } { // Integer index indexManager.ensureIndexed("a_123", "abc_123", IndexType.INTEGER); Index artist = indexManager.getIndex("a_123"); assertIndexDataFields("a_123", "abc_123", IndexType.INTEGER, -1L, artist); String tableName = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "a_123"); assertTableCreated(tableName); } } private void assertIndexDataFields(String expectedIndexName, String expectedFieldName, IndexType expectedIndexType, Long expectLastSequence, Index actual) throws SQLException { Assert.assertEquals(expectedIndexName, actual.getName()); Assert.assertEquals(expectedIndexType, actual.getIndexType()); Assert.assertTrue(actual.getLastSequence().equals(expectLastSequence)); } private void assertTableCreated(String name) throws SQLException { Set<String> tables = SQLDatabaseTestUtils.getAllTableNames(database); Assert.assertTrue(tables.contains(name)); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexNamesButDifferentField() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album2"); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexNamesButDifferentType() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album", IndexType.INTEGER); } @Test(expected = IndexExistsException.class) public void ensuredIndexed_duplicatedIndexes() throws IndexExistsException { indexManager.ensureIndexed("Album", "album"); indexManager.ensureIndexed("Album", "album"); } @Test public void getAllIndexes_allIndexesShouldBeReturned() throws IndexExistsException { Assert.assertEquals(0, indexManager.getAllIndexes().size()); Index albumIndex = createAndGetIndex("album", "album", IndexType.STRING); Assert.assertEquals(1, indexManager.getAllIndexes().size()); indexManager.ensureIndexed("artist", "artist", IndexType.INTEGER); Index artistIndex = indexManager.getIndex("artist"); Set<Index> indexes = indexManager.getAllIndexes(); Assert.assertEquals(2, indexes.size()); Assert.assertTrue(indexes.contains(albumIndex)); Assert.assertTrue(indexes.contains(artistIndex)); for(Index index : indexes) { if(index.getName().equals("album")) { assertSameIndex(index, albumIndex); } else if (index.getName().equals("artist")) { assertSameIndex(index, artistIndex); } } } private void assertSameIndex(Index l, Index r) { Assert.assertEquals(l.getName(), r.getName()); Assert.assertEquals(l.getIndexType(), r.getIndexType()); Assert.assertEquals(l.getLastSequence(), r.getLastSequence()); } @Test public void deleteIndex_delete_indexShouldBeDeleted() throws IndexExistsException, SQLException { Index index = createAndGetIndex("album", "album", IndexType.STRING); Assert.assertNotNull(index); indexManager.deleteIndex(index.getName()); Assert.assertEquals(0, indexManager.getAllIndexes().size()); String indexTable = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, "album"); assertTableDeleted(indexTable); } private void assertTableDeleted(String table) throws SQLException { Set<String> tables = SQLDatabaseTestUtils.getAllTableNames(database); Assert.assertFalse(tables.contains(table)); } @Test(expected = IllegalArgumentException.class) public void deleteIndex_indexNotExist_exception() { Assert.assertNull(indexManager.getIndex("Z")); indexManager.deleteIndex("Z"); } @Test public void ensuredIndexed_documentExistBeforeIndexCreated_existingDocShouldBeIndexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); Index index = createAndGetIndex("album", "album", IndexType.STRING); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj1); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj2); } @Test public void ensure_custom_indexing_function_used_non_null_indexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); final class TestIF implements IndexFunction<String> { public List<String> indexedValues(String indexName, Map map) { return Arrays.asList("fred"); } } this.indexManager.ensureIndexed("album", IndexType.STRING, new TestIF()); Index index = indexManager.getIndex("album"); for (DocumentRevision obj : new DocumentRevision[]{obj0,obj1,obj2}) { IndexTestUtils.assertDBObjectInIndexWithValue( database, index, obj, "fred" ); } } @Test public void ensure_custom_indexing_function_used_null_not_indexed() throws IndexExistsException, SQLException { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); final class TestIF implements IndexFunction<String> { public List<String> indexedValues(String indexName, Map map) { return null; } } this.indexManager.ensureIndexed("album", IndexType.STRING, new TestIF()); Index index = indexManager.getIndex("album"); for (DocumentRevision obj : new DocumentRevision[]{obj0,obj1,obj2}) { IndexTestUtils.assertDBObjectNotInIndex( database, index, obj ); } } @Test public void createStringIndex_documentInsertedAfterIndexCreated_documentShouldBeIndexed() throws IndexExistsException, SQLException { Index index = createAndGetIndex("album", "album", IndexType.STRING); DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); DocumentRevision obj2 = datastore.createDocument(dbBodies.get(2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj1); IndexTestUtils.assertDBObjectInIndex(database, index, "album", obj2); } @Test public void createLongIndex_documentInsertedAfterIndexCreated_documentShouldBeIndexed() throws IndexExistsException, SQLException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); { DocumentRevision obj0 = datastore.createDocument(dbBodies.get(0)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj0); } { DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } } @Test public void createLongIndex_indexValueIsBigLong_documentShouldBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_really_big_long.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } @Test public void createLongIndex_indexValueIsFloat_documentShouldBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_float.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "class", obj1); } @Test public void createLongIndex_indexValueConversionNotSupported_documentShouldNotBeIndexed() throws IndexExistsException, SQLException, IOException { indexManager.ensureIndexed("class", "class", IndexType.INTEGER); Index index = indexManager.getIndex("class"); byte[] data = FileUtils.readFileToByteArray(new File("fixture/index_string.json")); DocumentRevision obj1 = datastore.createDocument(DocumentBodyFactory.create(data)); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj1); } @Test public void indexString_documentWithValidField_indexRowShouldBeAdded() throws IndexExistsException, SQLException, IOException { Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); } @Test public void indexString_documentWithInvalidField_indexRowShouldNotBeAdded() throws IndexExistsException, IOException, SQLException { Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexString_documentUpdated_indexRowShouldBeUpdated() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); DocumentRevision obj = datastore.createDocument(TestUtils.createBDBody("fixture/string_index_valid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), TestUtils.createBDBody("fixture/string_index_valid_field_updated.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj2); } @Test public void indexString_documentUpdatedFromInvalidToValidValue_indexRowShouldBeUpdated() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); DocumentRevision obj = datastore.createDocument(TestUtils.createBDBody("fixture/string_index_invalid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), TestUtils.createBDBody("fixture/string_index_valid_field.json")); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj2); } private Index createAndGetIndex(String indexName, String filedName, IndexType type) throws IndexExistsException { indexManager.ensureIndexed(indexName, filedName, type); return indexManager.getIndex(indexName); } @Test public void indexString_documentUpdatedWithInvalidValue_indexValueShouldBeRemoved() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/string_index_invalid_field.json")); DocumentRevision obj2 = datastore.updateDocument(obj.getId(), obj.getRevision(), DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj2); } @Test public void indexString_documentDeleted_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("stringIndex", "stringIndex", IndexType.STRING); byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "stringIndex", obj); datastore.deleteDocument(obj.getId(), obj.getRevision()); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexInteger_documentCreated_indexRowShouldBeAdded() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); } @Test public void indexInteger_documentCreatedWithInvalidIndexValue_indexRowShouldNotBeAdded() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void indexInteger_documentUpdated_indexValueShouldBeUpdate() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field_updated.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj2); } @Test public void indexInteger_documentUpdatedFromInvalidToValidValue_indexValueShouldBeUpdate() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj2); } @Test public void indexInteger_documentUpdatedWithInvalidIndexValue_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); byte[] data2 = FileUtils.readFileToByteArray(new File("fixture/integer_index_invalid_field.json")); DocumentRevision obj2 = datastore.createDocument(DocumentBodyFactory.create(data2)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj2); } @Test public void indexInteger_documentDeleted_indexRowShouldBeRemoved() throws Exception { Index index = createAndGetIndex("integerIndex", "integerIndex", IndexType.INTEGER); byte[] data = FileUtils.readFileToByteArray(new File("fixture/integer_index_valid_field.json")); DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data)); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectInIndex(database, index, "integerIndex", obj); datastore.deleteDocument(obj.getId(), obj.getRevision()); indexManager.updateAllIndexes(); IndexTestUtils.assertDBObjectNotInIndex(database, index, obj); } @Test public void multiIndex_documentWithoutTheField_notIndexed() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(0)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId()); } @Test public void multiIndex_documentFieldWithListOfTwo_twoIndexValueAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(1)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop", "Rock"); } @Test public void multiIndex_documentFieldWithListOfOne_oneIndexValueAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(3)); indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop"); } @Test public void multiIndex_documentFieldWithDuplicatedValues_noDuplicatedValuesAdded() throws IndexExistsException, SQLException { Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); DocumentRevision rev = datastore.createDocument(dbBodies.get(4)); // this Document has field: genre: [ "Pop", "Pop" ], and assert // only one entry added for "Pop" indexManager.updateAllIndexes(); Index index2 = indexManager.getIndex("Genre"); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index2.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop"); } @Test public void index_fieldWithUnsupportedValue_unsupportedValueShouldBeIgnored() throws IndexExistsException, SQLException, IOException { DocumentBody body = TestUtils.createBDBody("fixture/index_with_unsupported_value.json"); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), "Pop", "Rock"); } @Test public void index_valueWithLeadingTailingSpaces_spacesRemoved() throws IndexExistsException, SQLException, IOException { DocumentBody body = TestUtils.createBDBody("fixture/index_with_spaces.json"); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Genre", "Genre", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), " Pop", "Rock ", " R & B "); } @Test public void index_fieldWith10KValues_allValuesShouldBeAdded() throws IndexExistsException, SQLException, IOException { Map m = new HashMap<String, String>(); List<String> tags = new ArrayList<String>(100000); for(int i = 0 ; i < 100000 ; i ++) { tags.add("tag" + i); } m.put("Tag", tags); DocumentBody body = DocumentBodyFactory.create(m); DocumentRevision rev = datastore.createDocument(body); Index index = createAndGetIndex("Tag", "Tag", IndexType.STRING); Assert.assertEquals(Long.valueOf(datastore.getLastSequence()), Long.valueOf(index.getLastSequence())); this.assertIndexed(database, index, rev.getId(), tags.toArray(new String[]{})); } // test that index updates itself on create/update/delete @Test public void index_UpdateCrud() throws IndexExistsException, SQLException, ConflictException { Index index = createAndGetIndex("title", "title", IndexType.STRING); // create DocumentRevision obj1 = datastore.createDocument(dbBodies.get(1)); this.assertIndexed(database, index, obj1.getId(), "Politik"); // update Map<String,Object> map = obj1.getBody().asMap(); map.put("title", "Another Green Day"); DocumentBody body = DocumentBodyFactory.create(map); DocumentRevision obj2 = datastore.updateDocument(obj1.getId(), obj1.getRevision(), body); Assert.assertEquals(obj1.getId(), obj2.getId()); this.assertIndexed(database, index, obj2.getId(), "Another Green Day"); // delete datastore.deleteDocument(obj2.getId(), obj2.getRevision()); this.assertNotIndexed(database, index, obj2.getId()); } /** * A sanity-check that updating the datastore from many threads * doesn't cause the index manager to balk. */ @Test public void index_UpdateCrudMultiThreaded() throws IndexExistsException, SQLException, ConflictException, InterruptedException { int n_threads = 5; final int n_docs = 100; // We'll later search for search == success final Map<String,String> matching = ImmutableMap.of("search", "success"); final Map<String,String> nonmatching = ImmutableMap.of("search", "failure"); indexManager.ensureIndexed("search", "search", IndexType.STRING); final List<String> matching_ids = Collections.synchronizedList(new ArrayList<String>()); // When run, this thread creates n_docs documents with unique // names in the datastore. A subset of these // will be matched by our query to the datastore later, which // we record in the matching_ids list. class PopulateThread extends Thread { @Override public void run() { String docId; final String thread_id; DocumentBody body; thread_id = Thread.currentThread().getName(); for (int i = 0; i < n_docs; i++) { docId = String.format("%s-%s", thread_id, i); if ((i % 2) == 0) { // even numbers create matching docs body = DocumentBodyFactory.create(matching); matching_ids.add(docId); } else { body = DocumentBodyFactory.create(nonmatching); } datastore.createDocument(docId, body); } // we're not on the main thread, so we must close our own connection datastore.getSQLDatabase().close(); } } List<Thread> threads = new ArrayList<Thread>(); // Create, start and wait for the threads to complete for (int i = 0; i < n_threads; i++) { threads.add(new PopulateThread()); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } // Check appropriate entries in index QueryBuilder q = new QueryBuilder(); q.index("search").equalTo("success"); QueryResult result = indexManager.query(q.build()); List<DocumentRevision> docRevisions = Lists.newArrayList(result); List<String> docIds = new ArrayList<String>(); for (DocumentRevision r : docRevisions) { docIds.add(r.getId()); } Assert.assertEquals(matching_ids.size(), docIds.size()); for (String id : matching_ids) { Assert.assertTrue(docIds.contains(id)); } } private void assertNotIndexed(SQLDatabase database, Index index, String docId) throws SQLException { String table = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, index.getName()); Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? ", new String[]{String.valueOf(docId)} ); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(0), Integer.valueOf(cursor.getInt(0))); } private void assertIndexed(SQLDatabase database, Index index, String docId, String ... expectedValues) throws SQLException { String table = String.format(IndexManager.TABLE_INDEX_NAME_FORMAT, index.getName()); assertIndexedValueCount(database, docId, table, expectedValues); for(String value : expectedValues) { assertIndexedValue(database, docId, table, value); } } private void assertIndexedValue(SQLDatabase database, String docId, String table, String value) throws SQLException { Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? and value = ? ", new String[]{String.valueOf(docId), value}); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(1), Integer.valueOf(cursor.getInt(0))); } private void assertIndexedValueCount(SQLDatabase database, String docId, String table, String[] expectedValues) throws SQLException { Cursor cursor = database.rawQuery("SELECT count(*) FROM " + table + " where docid = ? ", new String[]{String.valueOf(docId)}); Assert.assertTrue(cursor.moveToFirst()); Assert.assertEquals(Integer.valueOf(expectedValues.length), Integer.valueOf(cursor.getInt(0))); } }
Bring thread count down to 3, to speed up travis builds
src/test/java/com/cloudant/sync/indexing/IndexManagerIndexTest.java
Bring thread count down to 3, to speed up travis builds
Java
apache-2.0
d1a1d96e57eaf1151c0ab74a2ac04ecd54ad83d1
0
ricepanda/rice-git3,kuali/rice-playground,ricepanda/rice-git2,ricepanda/rice-git3,kuali/rice-playground,ricepanda/rice-git2,ricepanda/rice-git2,kuali/rice-playground,ricepanda/rice-git3,ricepanda/rice-git2,kuali/rice-playground,ricepanda/rice-git3
package org.kuali.rice.kew.docsearch; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceRemoteServiceConnectionException; import org.kuali.rice.core.api.uif.RemotableAttributeError; import org.kuali.rice.core.api.uif.RemotableAttributeField; import org.kuali.rice.kew.framework.document.lookup.AttributeFields; import org.kuali.rice.kew.framework.document.attribute.SearchableAttribute; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupResultSetConfiguration; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCriteriaConfiguration; import org.kuali.rice.kew.api.document.lookup.DocumentLookupCriteria; import org.kuali.rice.kew.api.document.lookup.DocumentLookupResult; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupResultValues; import org.kuali.rice.kew.api.extension.ExtensionDefinition; import org.kuali.rice.kew.api.extension.ExtensionRepositoryService; import org.kuali.rice.kew.api.extension.ExtensionUtils; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomization; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomizationHandlerService; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomizer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * TODO... * * @author Kuali Rice Team ([email protected]) */ public class DocumentLookupCustomizationHandlerServiceImpl implements DocumentLookupCustomizationHandlerService { private static final Logger LOG = Logger.getLogger(DocumentLookupCustomizationHandlerServiceImpl.class); private ExtensionRepositoryService extensionRepositoryService; @Override public DocumentLookupCriteriaConfiguration getDocumentLookupConfiguration(String documentTypeName, List<String> searchableAttributeNames) { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } DocumentLookupCriteriaConfiguration.Builder configBuilder = DocumentLookupCriteriaConfiguration.Builder.create(); if (CollectionUtils.isNotEmpty(searchableAttributeNames)) { try { List<AttributeFields> searchAttributeFields = new ArrayList<AttributeFields>(); for (String searchableAttributeName : searchableAttributeNames) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(searchableAttributeName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a SearchableAttribute with the given name: " + searchableAttributeName); } SearchableAttribute searchableAttribute = loadSearchableAttribute(extensionDefinition); List<RemotableAttributeField> attributeSearchFields = searchableAttribute.getSearchFields(extensionDefinition, documentTypeName); if (CollectionUtils.isNotEmpty(attributeSearchFields)) { searchAttributeFields.add(AttributeFields.create(searchableAttributeName, attributeSearchFields)); } } configBuilder.setSearchAttributeFields(searchAttributeFields); } catch (RiceRemoteServiceConnectionException e) { LOG.warn("Unable to connect to load searchable attributes for document type: " + documentTypeName, e); } } // TODO - Rice 2.0 - add in the "resultSetFields"... return configBuilder.build(); } @Override public List<RemotableAttributeError> validateSearchFieldParameters(String documentTypeName, List<String> searchableAttributeNames, Map<String, List<String>> parameters) { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } if (CollectionUtils.isEmpty(searchableAttributeNames)) { return Collections.emptyList(); } try { List<RemotableAttributeError> searchFieldErrors = new ArrayList<RemotableAttributeError>(); for (String searchableAttributeName : searchableAttributeNames) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(searchableAttributeName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a SearchableAttribute with the given name: " + searchableAttributeName); } SearchableAttribute searchableAttribute = loadSearchableAttribute(extensionDefinition); List<RemotableAttributeError> errors = searchableAttribute.validateSearchFieldParameters(extensionDefinition, parameters, documentTypeName); if (!CollectionUtils.isEmpty(errors)) { searchFieldErrors.addAll(errors); } } return Collections.unmodifiableList(searchFieldErrors); } catch (RiceRemoteServiceConnectionException e) { LOG.warn("Unable to connect to load searchable attributes for document type: " + documentTypeName, e); return Collections.emptyList(); } } @Override public DocumentLookupCriteria customizeCriteria(DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeCriteria(documentLookupCriteria); } @Override public DocumentLookupCriteria customizeClearCriteria(DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeClearCriteria(documentLookupCriteria); } @Override public DocumentLookupResultValues customizeResults(DocumentLookupCriteria documentLookupCriteria, List<DocumentLookupResult> defaultResults, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (defaultResults == null) { throw new RiceIllegalArgumentException("defaultResults was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeResults(documentLookupCriteria, defaultResults); } @Override public DocumentLookupResultSetConfiguration customizeResultSetConfiguration( DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeResultSetConfiguration(documentLookupCriteria); } @Override public Set<DocumentLookupCustomization> getEnabledCustomizations(String documentTypeName, String customizerName) throws RiceIllegalArgumentException { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(documentTypeName); Set<DocumentLookupCustomization> customizations = new HashSet<DocumentLookupCustomization>(); if (customizer.isCustomizeCriteriaEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.CRITERIA); } if (customizer.isCustomizeClearCriteriaEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.CLEAR_CRITERIA); } if (customizer.isCustomizeResultsEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.RESULTS); } if (customizer.isCustomizeResultSetFieldsEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.RESULT_SET_FIELDS); } return Collections.unmodifiableSet(customizations); } private SearchableAttribute loadSearchableAttribute(ExtensionDefinition extensionDefinition) { Object searchableAttribute = ExtensionUtils.loadExtension(extensionDefinition); if (searchableAttribute == null) { throw new RiceIllegalArgumentException("Failed to load SearchableAttribute for: " + extensionDefinition); } return (SearchableAttribute)searchableAttribute; } private DocumentLookupCustomizer loadCustomizer(String customizerName) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(customizerName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a DocumentLookupCustomizer with the given name: " + customizerName); } DocumentLookupCustomizer customizer = ExtensionUtils.loadExtension(extensionDefinition); if (customizer == null) { throw new RiceIllegalArgumentException("Failed to load DocumentLookupCustomizer for: " + extensionDefinition); } return customizer; } protected ExtensionRepositoryService getExtensionRepositoryService() { return extensionRepositoryService; } public void setExtensionRepositoryService(ExtensionRepositoryService extensionRepositoryService) { this.extensionRepositoryService = extensionRepositoryService; } }
impl/src/main/java/org/kuali/rice/kew/docsearch/DocumentLookupCustomizationHandlerServiceImpl.java
package org.kuali.rice.kew.docsearch; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.kuali.rice.core.api.exception.RiceIllegalArgumentException; import org.kuali.rice.core.api.exception.RiceRemoteServiceConnectionException; import org.kuali.rice.core.api.uif.RemotableAttributeError; import org.kuali.rice.core.api.uif.RemotableAttributeField; import org.kuali.rice.kew.framework.document.lookup.AttributeFields; import org.kuali.rice.kew.framework.document.attribute.SearchableAttribute; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupResultSetConfiguration; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCriteriaConfiguration; import org.kuali.rice.kew.api.document.lookup.DocumentLookupCriteria; import org.kuali.rice.kew.api.document.lookup.DocumentLookupResult; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupResultValues; import org.kuali.rice.kew.api.extension.ExtensionDefinition; import org.kuali.rice.kew.api.extension.ExtensionRepositoryService; import org.kuali.rice.kew.api.extension.ExtensionUtils; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomization; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomizationHandlerService; import org.kuali.rice.kew.framework.document.lookup.DocumentLookupCustomizer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * TODO... * * @author Kuali Rice Team ([email protected]) */ public class DocumentLookupCustomizationHandlerServiceImpl implements DocumentLookupCustomizationHandlerService { private static final Logger LOG = Logger.getLogger(DocumentLookupCustomizationHandlerServiceImpl.class); private ExtensionRepositoryService extensionRepositoryService; @Override public DocumentLookupCriteriaConfiguration getDocumentLookupConfiguration(String documentTypeName, List<String> searchableAttributeNames) { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } DocumentLookupCriteriaConfiguration.Builder configBuilder = DocumentLookupCriteriaConfiguration.Builder.create(); if (CollectionUtils.isNotEmpty(searchableAttributeNames)) { try { List<AttributeFields> searchAttributeFields = new ArrayList<AttributeFields>(); for (String searchableAttributeName : searchableAttributeNames) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(searchableAttributeName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a SearchableAttribute with the given name: " + searchableAttributeName); } SearchableAttribute searchableAttribute = loadSearchableAttribute(extensionDefinition); List<RemotableAttributeField> attributeSearchFields = searchableAttribute.getSearchFields(extensionDefinition, documentTypeName); searchAttributeFields.add(AttributeFields.create(searchableAttributeName, attributeSearchFields)); } configBuilder.setSearchAttributeFields(searchAttributeFields); } catch (RiceRemoteServiceConnectionException e) { LOG.warn("Unable to connect to load searchable attributes for document type: " + documentTypeName, e); } } // TODO - Rice 2.0 - add in the "resultSetFields"... return configBuilder.build(); } @Override public List<RemotableAttributeError> validateSearchFieldParameters(String documentTypeName, List<String> searchableAttributeNames, Map<String, List<String>> parameters) { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } if (CollectionUtils.isEmpty(searchableAttributeNames)) { return Collections.emptyList(); } try { List<RemotableAttributeError> searchFieldErrors = new ArrayList<RemotableAttributeError>(); for (String searchableAttributeName : searchableAttributeNames) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(searchableAttributeName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a SearchableAttribute with the given name: " + searchableAttributeName); } SearchableAttribute searchableAttribute = loadSearchableAttribute(extensionDefinition); List<RemotableAttributeError> errors = searchableAttribute.validateSearchFieldParameters(extensionDefinition, parameters, documentTypeName); if (!CollectionUtils.isEmpty(errors)) { searchFieldErrors.addAll(errors); } } return Collections.unmodifiableList(searchFieldErrors); } catch (RiceRemoteServiceConnectionException e) { LOG.warn("Unable to connect to load searchable attributes for document type: " + documentTypeName, e); return Collections.emptyList(); } } @Override public DocumentLookupCriteria customizeCriteria(DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeCriteria(documentLookupCriteria); } @Override public DocumentLookupCriteria customizeClearCriteria(DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeClearCriteria(documentLookupCriteria); } @Override public DocumentLookupResultValues customizeResults(DocumentLookupCriteria documentLookupCriteria, List<DocumentLookupResult> defaultResults, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (defaultResults == null) { throw new RiceIllegalArgumentException("defaultResults was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeResults(documentLookupCriteria, defaultResults); } @Override public DocumentLookupResultSetConfiguration customizeResultSetConfiguration( DocumentLookupCriteria documentLookupCriteria, String customizerName) throws RiceIllegalArgumentException { if (documentLookupCriteria == null) { throw new RiceIllegalArgumentException("documentLookupCriteria was null"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(customizerName); return customizer.customizeResultSetConfiguration(documentLookupCriteria); } @Override public Set<DocumentLookupCustomization> getEnabledCustomizations(String documentTypeName, String customizerName) throws RiceIllegalArgumentException { if (StringUtils.isBlank(documentTypeName)) { throw new RiceIllegalArgumentException("documentTypeName was null or blank"); } if (StringUtils.isBlank(customizerName)) { throw new RiceIllegalArgumentException("customizerName was null or blank"); } DocumentLookupCustomizer customizer = loadCustomizer(documentTypeName); Set<DocumentLookupCustomization> customizations = new HashSet<DocumentLookupCustomization>(); if (customizer.isCustomizeCriteriaEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.CRITERIA); } if (customizer.isCustomizeClearCriteriaEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.CLEAR_CRITERIA); } if (customizer.isCustomizeResultsEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.RESULTS); } if (customizer.isCustomizeResultSetFieldsEnabled(documentTypeName)) { customizations.add(DocumentLookupCustomization.RESULT_SET_FIELDS); } return Collections.unmodifiableSet(customizations); } private SearchableAttribute loadSearchableAttribute(ExtensionDefinition extensionDefinition) { Object searchableAttribute = ExtensionUtils.loadExtension(extensionDefinition); if (searchableAttribute == null) { throw new RiceIllegalArgumentException("Failed to load SearchableAttribute for: " + extensionDefinition); } return (SearchableAttribute)searchableAttribute; } private DocumentLookupCustomizer loadCustomizer(String customizerName) { ExtensionDefinition extensionDefinition = getExtensionRepositoryService().getExtensionByName(customizerName); if (extensionDefinition == null) { throw new RiceIllegalArgumentException("Failed to locate a DocumentLookupCustomizer with the given name: " + customizerName); } DocumentLookupCustomizer customizer = ExtensionUtils.loadExtension(extensionDefinition); if (customizer == null) { throw new RiceIllegalArgumentException("Failed to load DocumentLookupCustomizer for: " + extensionDefinition); } return customizer; } protected ExtensionRepositoryService getExtensionRepositoryService() { return extensionRepositoryService; } public void setExtensionRepositoryService(ExtensionRepositoryService extensionRepositoryService) { this.extensionRepositoryService = extensionRepositoryService; } }
KULRICE-5056 - modified DocumentLookupCustomizationHandlerServiceImpl so that it can handle a null or empty list return from SearchableAttribute.getSearchFields git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@22441 7a7aa7f6-c479-11dc-97e2-85a2497f191d
impl/src/main/java/org/kuali/rice/kew/docsearch/DocumentLookupCustomizationHandlerServiceImpl.java
KULRICE-5056 - modified DocumentLookupCustomizationHandlerServiceImpl so that it can handle a null or empty list return from SearchableAttribute.getSearchFields
Java
apache-2.0
aa400b16f22e1736d9ecd3378daa2d9fc0c03741
0
dstendardi/snowplow-java-tracker,snowplow/snowplow-java-tracker,dstendardi/snowplow-java-tracker
/* * Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.tracker.core.emitter; import com.snowplowanalytics.snowplow.tracker.core.Constants; import com.snowplowanalytics.snowplow.tracker.core.payload.Payload; import com.snowplowanalytics.snowplow.tracker.core.payload.SchemaPayload; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class Emitter { private URIBuilder uri; private BufferOption option = BufferOption.Default; private RequestMethod requestMethod = RequestMethod.Synchronous; private RequestCallback requestCallback; private CloseableHttpClient httpClient; private CloseableHttpAsyncClient httpAsyncClient; private final ArrayList<Payload> buffer = new ArrayList<Payload>(); private final Logger logger = LoggerFactory.getLogger(Emitter.class); protected HttpMethod httpMethod = HttpMethod.GET; /** * Default constructor does nothing. */ public Emitter() { } /** * Create an Emitter instance with a collector URL. * @param URI The collector URL. Don't include "http://" - this is done automatically. */ public Emitter(String URI) { this(URI, HttpMethod.GET, null); } /** * Create an Emitter instance with a collector URL, and callback function. * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param callback The callback function to handle success/failure cases when sending events. */ public Emitter(String URI, RequestCallback callback) { this(URI, HttpMethod.GET, callback); } /** * Create an Emitter instance with a collector URL, * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>. */ public Emitter(String URI, HttpMethod httpMethod) { this(URI, httpMethod, null); } /** * Create an Emitter instance with a collector URL and HttpMethod to send requests. * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>. * @param callback The callback function to handle success/failure cases when sending events. */ public Emitter(String URI, HttpMethod httpMethod, RequestCallback callback) { if (httpMethod == HttpMethod.GET) { uri = new URIBuilder() .setScheme("http") .setHost(URI) .setPath("/i"); } else { // POST uri = new URIBuilder() .setScheme("http") .setHost(URI) .setPath("/" + Constants.DEFAULT_VENDOR + "/tp2"); } this.requestCallback = callback; this.httpMethod = httpMethod; this.httpClient = HttpClients.createDefault(); if (httpMethod == HttpMethod.GET) { this.setBufferOption(BufferOption.Instant); } } /** * Sets whether the buffer should send events instantly or after the buffer has reached * it's limit. By default, this is set to BufferOption Default. * @param option Set the BufferOption enum to Instant send events upon creation. */ public void setBufferOption(BufferOption option) { this.option = option; } /** * Sets whether requests should be sent synchronously or asynchronously. * @param option The HTTP request method */ public void setRequestMethod(RequestMethod option) { this.requestMethod = option; this.httpAsyncClient = HttpAsyncClients.createDefault(); this.httpAsyncClient.start(); } /** * Add event payloads to the emitter's buffer * @param payload Payload to be added * @return Returns the boolean value if the event was successfully added to the buffer */ public boolean addToBuffer(Payload payload) { boolean ret = buffer.add(payload); if (buffer.size() == option.getCode()) flushBuffer(); return ret; } /** * Sends all events in the buffer to the collector. */ public void flushBuffer() { if (buffer.isEmpty()) { logger.debug("Buffer is empty, exiting flush operation.."); return; } if (httpMethod == HttpMethod.GET) { int success_count = 0; LinkedList<Payload> unsentPayloads = new LinkedList<Payload>(); for (Payload payload : buffer) { int status_code = sendGetData(payload).getStatusLine().getStatusCode(); if (status_code == 200) success_count++; else unsentPayloads.add(payload); } if (unsentPayloads.size() == 0) { if (requestCallback != null) requestCallback.onSuccess(success_count); } else if (requestCallback != null) requestCallback.onFailure(success_count, unsentPayloads); } else if (httpMethod == HttpMethod.POST) { LinkedList<Payload> unsentPayload = new LinkedList<Payload>(); SchemaPayload postPayload = new SchemaPayload(); postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA); ArrayList<Map> eventMaps = new ArrayList<Map>(); for (Payload payload : buffer) { eventMaps.add(payload.getMap()); } postPayload.setData(eventMaps); int status_code = sendPostData(postPayload).getStatusLine().getStatusCode(); if (status_code == 200 && requestCallback != null) requestCallback.onSuccess(buffer.size()); else if (requestCallback != null){ unsentPayload.add(postPayload); requestCallback.onFailure(0, unsentPayload); } } } protected HttpResponse sendPostData(Payload payload) { HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); HttpResponse httpResponse = null; try { StringEntity params = new StringEntity(payload.toString()); httpPost.setEntity(params); if (requestMethod == RequestMethod.Asynchronous) { Future<HttpResponse> future = httpAsyncClient.execute(httpPost, null); httpResponse = future.get(); } else { httpResponse = httpClient.execute(httpPost); } logger.debug(httpResponse.getStatusLine().toString()); } catch (UnsupportedEncodingException e) { logger.error("Encoding exception with the payload."); e.printStackTrace(); } catch (IOException e) { logger.error("Error when sending HTTP POST."); e.printStackTrace(); } catch (InterruptedException e) { logger.error("Interruption error when sending HTTP POST request."); e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return httpResponse; } @SuppressWarnings("unchecked") protected HttpResponse sendGetData(Payload payload) { HashMap hashMap = (HashMap) payload.getMap(); Iterator<String> iterator = hashMap.keySet().iterator(); HttpResponse httpResponse = null; while (iterator.hasNext()) { String key = iterator.next(); String value = (String) hashMap.get(key); uri.setParameter(key, value); } try { HttpGet httpGet = new HttpGet(uri.build()); if (requestMethod == RequestMethod.Asynchronous) { Future<HttpResponse> future = httpAsyncClient.execute(httpGet, null); httpResponse = future.get(); } else { httpResponse = httpClient.execute(httpGet); } logger.debug(httpResponse.getStatusLine().toString()); } catch (IOException e) { logger.error("Error when sending HTTP GET error."); e.printStackTrace(); } catch (URISyntaxException e) { logger.error("Error when creating HTTP GET request. Probably parsing error.."); e.printStackTrace(); } catch (InterruptedException e) { logger.error("Interruption error when sending HTTP GET request."); e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return httpResponse; } }
snowplow-java-tracker-core/src/main/java/com/snowplowanalytics/snowplow/tracker/core/emitter/Emitter.java
/* * Copyright (c) 2014 Snowplow Analytics Ltd. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package com.snowplowanalytics.snowplow.tracker.core.emitter; import com.snowplowanalytics.snowplow.tracker.core.Constants; import com.snowplowanalytics.snowplow.tracker.core.payload.Payload; import com.snowplowanalytics.snowplow.tracker.core.payload.SchemaPayload; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; public class Emitter { private URIBuilder uri; private BufferOption option = BufferOption.Default; private HttpMethod httpMethod = HttpMethod.GET; private RequestMethod requestMethod = RequestMethod.Synchronous; private RequestCallback requestCallback; private CloseableHttpClient httpClient; private CloseableHttpAsyncClient httpAsyncClient; private final ArrayList<Payload> buffer = new ArrayList<Payload>(); private final Logger logger = LoggerFactory.getLogger(Emitter.class); /** * Default constructor does nothing. */ public Emitter() { } /** * Create an Emitter instance with a collector URL. * @param URI The collector URL. Don't include "http://" - this is done automatically. */ public Emitter(String URI) { this(URI, HttpMethod.GET, null); } /** * Create an Emitter instance with a collector URL, and callback function. * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param callback The callback function to handle success/failure cases when sending events. */ public Emitter(String URI, RequestCallback callback) { this(URI, HttpMethod.GET, callback); } /** * Create an Emitter instance with a collector URL, * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>. */ public Emitter(String URI, HttpMethod httpMethod) { this(URI, httpMethod, null); } /** * Create an Emitter instance with a collector URL and HttpMethod to send requests. * @param URI The collector URL. Don't include "http://" - this is done automatically. * @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>. * @param callback The callback function to handle success/failure cases when sending events. */ public Emitter(String URI, HttpMethod httpMethod, RequestCallback callback) { if (httpMethod == HttpMethod.GET) { uri = new URIBuilder() .setScheme("http") .setHost(URI) .setPath("/i"); } else { // POST uri = new URIBuilder() .setScheme("http") .setHost(URI) .setPath("/" + Constants.DEFAULT_VENDOR + "/tp2"); } this.requestCallback = callback; this.httpMethod = httpMethod; this.httpClient = HttpClients.createDefault(); if (httpMethod == HttpMethod.GET) { this.setBufferOption(BufferOption.Instant); } } /** * Sets whether the buffer should send events instantly or after the buffer has reached * it's limit. By default, this is set to BufferOption Default. * @param option Set the BufferOption enum to Instant send events upon creation. */ public void setBufferOption(BufferOption option) { this.option = option; } /** * Sets whether requests should be sent synchronously or asynchronously. * @param option The HTTP request method */ public void setRequestMethod(RequestMethod option) { this.requestMethod = option; this.httpAsyncClient = HttpAsyncClients.createDefault(); this.httpAsyncClient.start(); } /** * Add event payloads to the emitter's buffer * @param payload Payload to be added * @return Returns the boolean value if the event was successfully added to the buffer */ public boolean addToBuffer(Payload payload) { boolean ret = buffer.add(payload); if (buffer.size() == option.getCode()) flushBuffer(); return ret; } /** * Sends all events in the buffer to the collector. */ public void flushBuffer() { if (buffer.isEmpty()) { logger.debug("Buffer is empty, exiting flush operation.."); return; } if (httpMethod == HttpMethod.GET) { int success_count = 0; LinkedList<Payload> unsentPayloads = new LinkedList<Payload>(); for (Payload payload : buffer) { int status_code = sendGetData(payload).getStatusLine().getStatusCode(); if (status_code == 200) success_count++; else unsentPayloads.add(payload); } if (unsentPayloads.size() == 0) { if (requestCallback != null) requestCallback.onSuccess(success_count); } else if (requestCallback != null) requestCallback.onFailure(success_count, unsentPayloads); } else if (httpMethod == HttpMethod.POST) { LinkedList<Payload> unsentPayload = new LinkedList<Payload>(); SchemaPayload postPayload = new SchemaPayload(); postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA); ArrayList<Map> eventMaps = new ArrayList<Map>(); for (Payload payload : buffer) { eventMaps.add(payload.getMap()); } postPayload.setData(eventMaps); int status_code = sendPostData(postPayload).getStatusLine().getStatusCode(); if (status_code == 200 && requestCallback != null) requestCallback.onSuccess(buffer.size()); else if (requestCallback != null){ unsentPayload.add(postPayload); requestCallback.onFailure(0, unsentPayload); } } } protected HttpResponse sendPostData(Payload payload) { HttpPost httpPost = new HttpPost(uri.toString()); httpPost.addHeader("Content-Type", "application/json; charset=utf-8"); HttpResponse httpResponse = null; try { StringEntity params = new StringEntity(payload.toString()); httpPost.setEntity(params); if (requestMethod == RequestMethod.Asynchronous) { Future<HttpResponse> future = httpAsyncClient.execute(httpPost, null); httpResponse = future.get(); } else { httpResponse = httpClient.execute(httpPost); } logger.debug(httpResponse.getStatusLine().toString()); } catch (UnsupportedEncodingException e) { logger.error("Encoding exception with the payload."); e.printStackTrace(); } catch (IOException e) { logger.error("Error when sending HTTP POST."); e.printStackTrace(); } catch (InterruptedException e) { logger.error("Interruption error when sending HTTP POST request."); e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return httpResponse; } @SuppressWarnings("unchecked") protected HttpResponse sendGetData(Payload payload) { HashMap hashMap = (HashMap) payload.getMap(); Iterator<String> iterator = hashMap.keySet().iterator(); HttpResponse httpResponse = null; while (iterator.hasNext()) { String key = iterator.next(); String value = (String) hashMap.get(key); uri.setParameter(key, value); } try { HttpGet httpGet = new HttpGet(uri.build()); if (requestMethod == RequestMethod.Asynchronous) { Future<HttpResponse> future = httpAsyncClient.execute(httpGet, null); httpResponse = future.get(); } else { httpResponse = httpClient.execute(httpGet); } logger.debug(httpResponse.getStatusLine().toString()); } catch (IOException e) { logger.error("Error when sending HTTP GET error."); e.printStackTrace(); } catch (URISyntaxException e) { logger.error("Error when creating HTTP GET request. Probably parsing error.."); e.printStackTrace(); } catch (InterruptedException e) { logger.error("Interruption error when sending HTTP GET request."); e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return httpResponse; } }
Made httpMethod protected to access from subclasses
snowplow-java-tracker-core/src/main/java/com/snowplowanalytics/snowplow/tracker/core/emitter/Emitter.java
Made httpMethod protected to access from subclasses
Java
apache-2.0
b9433f1f7556e5ad96e8ae6048eb4d75a7d6d64b
0
jenetics/jpx,jenetics/jpx
/* * Java GPX Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstรถtter * * 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. * * Author: * Franz Wilhelmstรถtter ([email protected]) */ package io.jenetics.jpx; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI; import static javax.xml.stream.XMLInputFactory.IS_NAMESPACE_AWARE; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.DTD; import static javax.xml.stream.XMLStreamConstants.END_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.ENTITY_DECLARATION; import static javax.xml.stream.XMLStreamConstants.ENTITY_REFERENCE; import static javax.xml.stream.XMLStreamConstants.NOTATION_DECLARATION; import static javax.xml.stream.XMLStreamConstants.PROCESSING_INSTRUCTION; import static javax.xml.stream.XMLStreamConstants.SPACE; import static javax.xml.stream.XMLStreamConstants.START_DOCUMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import io.jenetics.jpx.XMLReader.Type; /** * Simplifies the usage of the {@link XMLStreamReader}. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version !__version__! * @since 1.0 */ abstract class XMLReader<T> { /** * Represents the XML element type. */ static enum Type { /** * Denotes a element reader. */ ELEM, /** * Denotes a element attribute reader. */ ATTR, /** * Denotes a reader of elements of the same type. */ LIST, /** * Denotes a reader of the text of a element. */ TEXT } private final String _name; private final Type _type; /** * Create a new XML reader with the given name and type. * * @param name the element name of the reader * @param type the element type of the reader * @throws NullPointerException if one of the give arguments is {@code null} */ XMLReader(final String name, final Type type) { _name = requireNonNull(name); _type = requireNonNull(type); } /** * Read the given type from the underlying XML stream {@code reader}. * * <pre>{@code * try (AutoCloseableXMLStreamReader xml = XML.reader(in)) { * // Move XML stream to first element. * xml.next(); * return reader.read(xml); * } * }</pre> * * @param xml the underlying XML stream {@code reader} * @param lenient lenient read mode * @return the data read from the XML stream, maybe {@code null} * @throws XMLStreamException if an error occurs while reading the value * @throws NullPointerException if the given {@code xml} stream reader is * {@code null} */ public abstract T read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException; /** * Create a new reader for the new mapped type {@code B}. * * @param mapper the mapper function * @param <B> the target type of the new reader * @return a new reader * @throws NullPointerException if the given {@code mapper} function is * {@code null} */ public <B> XMLReader<B> map(final Function<? super T, ? extends B> mapper) { requireNonNull(mapper); return new XMLReader<B>(_name, _type) { @Override public B read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { try { return mapper.apply(XMLReader.this.read(xml, lenient)); } catch (RuntimeException e) { if (!lenient) { throw new XMLStreamException(format( "Invalid value for '%s'.", _name), e ); } else { return null; } } } }; } /** * Return the name of the element processed by this reader. * * @return the element name the reader is processing */ String name() { return _name; } /** * Return the element type of the reader. * * @return the element type of the reader */ Type type() { return _type; } @Override public String toString() { return format("Reader[%s, %s]", name(), type()); } /* ************************************************************************* * Static reader factory methods. * ************************************************************************/ /** * Return a {@code Reader} for reading an attribute of an element. * <p> * <b>XML</b> * <pre> {@code <element length="3"/>}</pre> * * <b>Reader definition</b> * <pre>{@code * final Reader<Integer> reader = * elem( * v -> (Integer)v[0], * "element", * attr("length").map(Integer::parseInt) * ); * }</pre> * * @param name the attribute name * @return an attribute reader * @throws NullPointerException if the given {@code name} is {@code null} */ public static XMLReader<String> attr(final String name) { return new AttrReader(name); } /** * Return a {@code Reader} for reading the text of an element. * <p> * <b>XML</b> * <pre> {@code <element>1234<element>}</pre> * * <b>Reader definition</b> * <pre>{@code * final Reader<Integer> reader = * elem( * v -> (Integer)v[0], * "element", * text().map(Integer::parseInt) * ); * }</pre> * * @return an element text reader */ public static XMLReader<String> text() { return new TextReader(); } /** * Return a {@code Reader} for reading an object of type {@code T} from the * XML element with the given {@code name}. * * <p> * <b>XML</b> * <pre> {@code <property name="size">1234<property>}</pre> * * <b>Reader definition</b> * <pre>{@code * final XMLReader<Property> reader = * elem( * v -> { * final String name = (String)v[0]; * final Integer value = (Integer)v[1]; * return Property.of(name, value); * }, * "property", * attr("name"), * text().map(Integer::parseInt) * ); * }</pre> * * @param generator the generator function, which build the result object * from the given parameter array * @param name the name of the root (sub-tree) element * @param children the child element reader, which creates the values * forwarded to the {@code generator} function * @param <T> the reader result type * @return a node reader * @throws NullPointerException if one of the given arguments is {@code null} * @throws IllegalArgumentException if the given child readers contains more * than one <em>text</em> reader */ public static <T> XMLReader<T> elem( final Function<Object[], T> generator, final String name, final XMLReader<?>... children ) { requireNonNull(name); requireNonNull(generator); Stream.of(requireNonNull(children)).forEach(Objects::requireNonNull); return new ElemReader<>(name, generator, asList(children), Type.ELEM); } /** * Return a {@code Reader} which reads the value from the child elements of * the given parent element {@code name}. * <p> * <b>XML</b> * <pre> {@code <min><property name="size">1234<property></min>}</pre> * * <b>Reader definition</b> * <pre>{@code * final XMLReader<Property> reader = * elem("min", * elem( * v -> { * final String name = (String)v[0]; * final Integer value = (Integer)v[1]; * return Property.of(name, value); * }, * "property", * attr("name"), * text().map(Integer::parseInt) * ) * ); * }</pre> * * @param name the parent element name * @param reader the child elements reader * @param <T> the result type * @return a node reader * @throws NullPointerException if one of the given arguments is {@code null} */ public static <T> XMLReader<T> elem( final String name, final XMLReader<? extends T> reader ) { requireNonNull(name); requireNonNull(reader); return elem( v -> { @SuppressWarnings("unchecked") T value = v.length > 0 ? (T)v[0] : null; return value; }, name, reader ); } public static XMLReader<String> elem(final String name) { return elem(name, text()); } public static XMLReader<Object> ignore(final String name) { return new IgnoreReader(name); } /** * Return a {@code XMLReader} which collects the elements, read by the given * child {@code reader}, and returns it as list of these elements. * <p> * <b>XML</b> * <pre> {@code * <properties length="3"> * <property>-1878762439</property> * <property>-957346595</property> * <property>-88668137</property> * </properties> * }</pre> * * <b>Reader definition</b> * <pre>{@code * XMLReader<List<Integer>> reader = * elem( * v -> (List<Integer>)v[0], * "properties", * elems(elem("property", text().map(Integer::parseInt))) * ); * }</pre> * * @param reader the child element reader * @param <T> the element type * @return a list reader */ public static <T> XMLReader<List<T>> elems(final XMLReader<? extends T> reader) { return new ListReader<T>(reader); } public static XMLReader<List<Node>> nodes(final String name) { return new NodesReader(name); } } /* ***************************************************************************** * XML reader implementations. * ****************************************************************************/ /** * Reader implementation for reading the attribute of the current node. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class AttrReader extends XMLReader<String> { AttrReader(final String name) { super(name, Type.ATTR); } @Override public String read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, null); return xml.getAttributeValue(null, name()); } } /** * Reader implementation for reading the text of the current node. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class TextReader extends XMLReader<String> { TextReader() { super("", Type.TEXT); } @Override public String read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { final StringBuilder out = new StringBuilder(); int type = xml.getEventType(); do { out.append(xml.getText()); } while (xml.hasNext() && (type = xml.next()) == CHARACTERS || type == CDATA); return out.toString(); } } /** * Reader implementation for reading list of elements. * * @param <T> the element type * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ListReader<T> extends XMLReader<List<T>> { private final XMLReader<? extends T> _adoptee; ListReader(final XMLReader<? extends T> adoptee) { super(adoptee.name(), Type.LIST); _adoptee = adoptee; } @Override public List<T> read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, name()); final T element = _adoptee.read(xml, lenient); return element != null ? Collections.singletonList(element) : emptyList(); } XMLReader<? extends T> reader() { return _adoptee; } } /** * This reader implementation ignores the content of the element with the given * name. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class IgnoreReader extends XMLReader<Object> { private final XMLReader<Object> _reader; IgnoreReader(final String name) { super(name, Type.ELEM); _reader = new ElemReader<>(name, o -> o, emptyList(), Type.ELEM); } @Override public Object read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { return _reader.read(xml, true); } } /** * This reader implementation reads the XML nodes from a given base node. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version !__version__! * @since !__version__! */ final class NodesReader extends XMLReader<List<Node>> { NodesReader(final String name) { super(name, Type.ELEM); } @Override public List<Node> read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { final Document doc = builder().newDocument(); read(xml, doc, lenient); final List<Node> elements = new ArrayList<>(); final NodeList children = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < children.getLength(); ++i) { elements.add(children.item(i)); } return elements; } private static DocumentBuilder builder() throws XMLStreamException { try { return DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new XMLStreamException(e); } } private void read( final XMLStreamReader xml, final Document doc, final boolean lenient ) throws XMLStreamException { final boolean complete = xml.getEventType() == START_DOCUMENT; final boolean nsAware = isNamespaceAware(xml); Node current = doc; main: for (int type = xml.getEventType();; type = xml.next()) { Node child; switch (type) { case CDATA: child = doc.createCDATASection(xml.getText()); break; case SPACE: if (current == doc) continue; case CHARACTERS: child = doc.createTextNode(xml.getText()); break; case COMMENT: child = doc.createComment(xml.getText()); break; case END_DOCUMENT: break main; case END_ELEMENT: current = current != null ? current.getParentNode() : null; if (current == null || current == doc) { if (!complete) break main; } continue main; case NOTATION_DECLARATION: case ENTITY_DECLARATION: continue main; case ENTITY_REFERENCE: child = doc.createEntityReference(xml.getLocalName()); break; case PROCESSING_INSTRUCTION: child = doc.createProcessingInstruction( xml.getPITarget(), xml.getPIData() ); break; case START_ELEMENT: { final Element elem = nsAware ? doc.createElementNS(xml.getNamespaceURI(), prefixedName(xml)) : doc.createElement(xml.getLocalName()); for (int i = 0; i < xml.getNamespaceCount(); ++i) { final String prefix = xml.getNamespacePrefix(i); elem.setAttributeNS( XMLNS_ATTRIBUTE_NS_URI, prefix == null || prefix.isEmpty() ? "xmlns" : "xmlns:" + prefix, xml.getNamespaceURI(i) ); } // And then the attributes: for (int i = 0, len = xml.getAttributeCount(); i < len; ++i) { String name = xml.getAttributeLocalName(i); if (nsAware) { final String prefix = xml.getAttributePrefix(i); if (prefix != null && !prefix.isEmpty()) { name = prefix + ":" + name; } elem.setAttributeNS( xml.getAttributeNamespace(i), name, xml.getAttributeValue(i) ); } else { elem.setAttribute(name, xml.getAttributeValue(i)); } } assert current != null; current.appendChild(elem); current = elem; continue main; } case START_DOCUMENT: case DTD: continue main; default: if (!lenient) { throw new XMLStreamException(format( "Unexpected event type: %d.", type )); } else { continue main; } } if (child != null && current != null) { current.appendChild(child); } } } private static String prefixedName(final XMLStreamReader xml) { return xml.getPrefix().isEmpty() ? xml.getLocalName() : xml.getPrefix() + ":" + xml.getLocalName(); } private static boolean isNamespaceAware(final XMLStreamReader xml) { final Object o = xml.getProperty(IS_NAMESPACE_AWARE); return !(o instanceof Boolean) || (Boolean)o; } } /** * The main XML element reader implementation. * * @param <T> the reader data type * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ElemReader<T> extends XMLReader<T> { // Given parameters. private final Function<Object[], T> _creator; private final List<XMLReader<?>> _children; // Derived parameters. private final Map<String, Integer> _readerIndexMapping = new HashMap<>(); private final int[] _attrReaderIndexes; private final int[] _textReaderIndex; ElemReader( final String name, final Function<Object[], T> creator, final List<XMLReader<?>> children, final Type type ) { super(name, type); _creator = requireNonNull(creator); _children = requireNonNull(children); for (int i = 0; i < _children.size(); ++i) { _readerIndexMapping.put(_children.get(i).name(), i); } _attrReaderIndexes = IntStream.range(0, _children.size()) .filter(i -> _children.get(i).type() == Type.ATTR) .toArray(); _textReaderIndex = IntStream.range(0, _children.size()) .filter(i -> _children.get(i).type() == Type.TEXT) .toArray(); if (_textReaderIndex.length > 1) { throw new IllegalArgumentException( "Found more than one TEXT reader." ); } } @Override public T read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, name()); final List<ReaderResult> results = _children.stream() .map(ReaderResult::of) .collect(Collectors.toList()); final ReaderResult text = _textReaderIndex.length == 1 ? results.get(_textReaderIndex[0]) : null; for (int i = 0; i < _attrReaderIndexes.length; ++i) { final ReaderResult result = results.get(_attrReaderIndexes[i]); try { result.put(result.reader().read(xml, lenient)); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) throw e; } } if (xml.hasNext()) { xml.next(); boolean hasNext = false; do { switch (xml.getEventType()) { case COMMENT: if (xml.hasNext()) { xml.next(); } break; case START_ELEMENT: Integer index = _readerIndexMapping .get(xml.getLocalName()); if (index == null && !lenient) { throw new XMLStreamException(format( "Unexpected element <%s>.", xml.getLocalName() )); } final ReaderResult result = index != null ? results.get(index) : ReaderResult.of(elem(xml.getLocalName())); if (result != null) { throwUnexpectedElement(xml, lenient, result); if (xml.hasNext()) { hasNext = true; xml.next(); } else { hasNext = false; } } break; case CHARACTERS: case CDATA: if (text != null) { throwUnexpectedElement(xml, lenient, text); } else { xml.next(); } hasNext = true; break; case END_ELEMENT: if (name().equals(xml.getLocalName())) { try { return _creator.apply( results.stream() .map(ReaderResult::value) .toArray() ); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) { throw new XMLStreamException(format( "Invalid value for '%s'.", name()), e ); } else { return null; } } } } } while (hasNext); } throw new XMLStreamException(format( "Premature end of file while reading '%s'.", name() )); } private void throwUnexpectedElement( final XMLStreamReader xml, final boolean lenient, final ReaderResult text ) throws XMLStreamException { try { text.put(text.reader().read(xml, lenient)); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) { final XMLStreamException exp = new XMLStreamException(format( "Unexpected element <%s>.", xml.getLocalName() )); exp.addSuppressed(e); throw exp; } } } } /** * Helper interface for storing the XML reader (intermediate) results. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ interface ReaderResult { /** * Return the underlying XML reader, which reads the result. * * @return return the underlying XML reader */ XMLReader<?> reader(); /** * Put the given {@code value} to the reader result. * * @param value the reader result */ void put(final Object value); /** * Return the current reader result value. * * @return the current reader result value */ Object value(); /** * Create a reader result for the given XML reader * * @param reader the XML reader * @return a reader result for the given reader */ static ReaderResult of(final XMLReader<?> reader) { return reader.type() == Type.LIST ? new ListResult(reader) : new ValueResult(reader); } } /** * Result object for values read from XML elements. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ValueResult implements ReaderResult { private final XMLReader<?> _reader; private Object _value; ValueResult(final XMLReader<?> reader) { _reader = reader; } @Override public void put(final Object value) { _value = value; } @Override public XMLReader<?> reader() { return _reader; } @Override public Object value() { return _value; } } /** * Result object for list values read from XML elements. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ListResult implements ReaderResult { private final XMLReader<?> _reader; private final List<Object> _value = new ArrayList<>(); ListResult(final XMLReader<?> reader) { _reader = reader; } @Override public void put(final Object value) { if (value instanceof List<?>) { _value.addAll((List<?>)value); } else { _value.add(value); } } @Override public XMLReader<?> reader() { return _reader; } @Override public List<Object> value() { return _value; } }
jpx/src/main/java/io/jenetics/jpx/XMLReader.java
/* * Java GPX Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstรถtter * * 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. * * Author: * Franz Wilhelmstรถtter ([email protected]) */ package io.jenetics.jpx; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Objects.requireNonNull; import static javax.xml.stream.XMLStreamConstants.CDATA; import static javax.xml.stream.XMLStreamConstants.CHARACTERS; import static javax.xml.stream.XMLStreamConstants.COMMENT; import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import io.jenetics.jpx.XMLReader.Type; /** * Simplifies the usage of the {@link XMLStreamReader}. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.0 */ abstract class XMLReader<T> { /** * Represents the XML element type. */ static enum Type { /** * Denotes a element reader. */ ELEM, /** * Denotes a element attribute reader. */ ATTR, /** * Denotes a reader of elements of the same type. */ LIST, /** * Denotes a reader of the text of a element. */ TEXT } private final String _name; private final Type _type; /** * Create a new XML reader with the given name and type. * * @param name the element name of the reader * @param type the element type of the reader * @throws NullPointerException if one of the give arguments is {@code null} */ XMLReader(final String name, final Type type) { _name = requireNonNull(name); _type = requireNonNull(type); } /** * Read the given type from the underlying XML stream {@code reader}. * * <pre>{@code * try (AutoCloseableXMLStreamReader xml = XML.reader(in)) { * // Move XML stream to first element. * xml.next(); * return reader.read(xml); * } * }</pre> * * @param xml the underlying XML stream {@code reader} * @param lenient lenient read mode * @return the data read from the XML stream, maybe {@code null} * @throws XMLStreamException if an error occurs while reading the value * @throws NullPointerException if the given {@code xml} stream reader is * {@code null} */ public abstract T read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException; /** * Create a new reader for the new mapped type {@code B}. * * @param mapper the mapper function * @param <B> the target type of the new reader * @return a new reader * @throws NullPointerException if the given {@code mapper} function is * {@code null} */ public <B> XMLReader<B> map(final Function<? super T, ? extends B> mapper) { requireNonNull(mapper); return new XMLReader<B>(_name, _type) { @Override public B read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { try { return mapper.apply(XMLReader.this.read(xml, lenient)); } catch (RuntimeException e) { if (!lenient) { throw new XMLStreamException(format( "Invalid value for '%s'.", _name), e ); } else { return null; } } } }; } /** * Return the name of the element processed by this reader. * * @return the element name the reader is processing */ String name() { return _name; } /** * Return the element type of the reader. * * @return the element type of the reader */ Type type() { return _type; } @Override public String toString() { return format("Reader[%s, %s]", name(), type()); } /* ************************************************************************* * Static reader factory methods. * ************************************************************************/ /** * Return a {@code Reader} for reading an attribute of an element. * <p> * <b>XML</b> * <pre> {@code <element length="3"/>}</pre> * * <b>Reader definition</b> * <pre>{@code * final Reader<Integer> reader = * elem( * v -> (Integer)v[0], * "element", * attr("length").map(Integer::parseInt) * ); * }</pre> * * @param name the attribute name * @return an attribute reader * @throws NullPointerException if the given {@code name} is {@code null} */ public static XMLReader<String> attr(final String name) { return new AttrReader(name); } /** * Return a {@code Reader} for reading the text of an element. * <p> * <b>XML</b> * <pre> {@code <element>1234<element>}</pre> * * <b>Reader definition</b> * <pre>{@code * final Reader<Integer> reader = * elem( * v -> (Integer)v[0], * "element", * text().map(Integer::parseInt) * ); * }</pre> * * @return an element text reader */ public static XMLReader<String> text() { return new TextReader(); } /** * Return a {@code Reader} for reading an object of type {@code T} from the * XML element with the given {@code name}. * * <p> * <b>XML</b> * <pre> {@code <property name="size">1234<property>}</pre> * * <b>Reader definition</b> * <pre>{@code * final XMLReader<Property> reader = * elem( * v -> { * final String name = (String)v[0]; * final Integer value = (Integer)v[1]; * return Property.of(name, value); * }, * "property", * attr("name"), * text().map(Integer::parseInt) * ); * }</pre> * * @param generator the generator function, which build the result object * from the given parameter array * @param name the name of the root (sub-tree) element * @param children the child element reader, which creates the values * forwarded to the {@code generator} function * @param <T> the reader result type * @return a node reader * @throws NullPointerException if one of the given arguments is {@code null} * @throws IllegalArgumentException if the given child readers contains more * than one <em>text</em> reader */ public static <T> XMLReader<T> elem( final Function<Object[], T> generator, final String name, final XMLReader<?>... children ) { requireNonNull(name); requireNonNull(generator); Stream.of(requireNonNull(children)).forEach(Objects::requireNonNull); return new ElemReader<>(name, generator, asList(children), Type.ELEM); } /** * Return a {@code Reader} which reads the value from the child elements of * the given parent element {@code name}. * <p> * <b>XML</b> * <pre> {@code <min><property name="size">1234<property></min>}</pre> * * <b>Reader definition</b> * <pre>{@code * final XMLReader<Property> reader = * elem("min", * elem( * v -> { * final String name = (String)v[0]; * final Integer value = (Integer)v[1]; * return Property.of(name, value); * }, * "property", * attr("name"), * text().map(Integer::parseInt) * ) * ); * }</pre> * * @param name the parent element name * @param reader the child elements reader * @param <T> the result type * @return a node reader * @throws NullPointerException if one of the given arguments is {@code null} */ public static <T> XMLReader<T> elem( final String name, final XMLReader<? extends T> reader ) { requireNonNull(name); requireNonNull(reader); return elem( v -> { @SuppressWarnings("unchecked") T value = v.length > 0 ? (T)v[0] : null; return value; }, name, reader ); } public static XMLReader<String> elem(final String name) { return elem(name, text()); } public static XMLReader<Object> ignore(final String name) { return new IgnoreReader(name); } /** * Return a {@code XMLReader} which collects the elements, read by the given * child {@code reader}, and returns it as list of these elements. * <p> * <b>XML</b> * <pre> {@code * <properties length="3"> * <property>-1878762439</property> * <property>-957346595</property> * <property>-88668137</property> * </properties> * }</pre> * * <b>Reader definition</b> * <pre>{@code * XMLReader<List<Integer>> reader = * elem( * v -> (List<Integer>)v[0], * "properties", * elems(elem("property", text().map(Integer::parseInt))) * ); * }</pre> * * @param reader the child element reader * @param <T> the element type * @return a list reader */ public static <T> XMLReader<List<T>> elems(final XMLReader<? extends T> reader) { return new ListReader<T>(reader); } } /* ***************************************************************************** * XML reader implementations. * ****************************************************************************/ /** * Reader implementation for reading the attribute of the current node. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class AttrReader extends XMLReader<String> { AttrReader(final String name) { super(name, Type.ATTR); } @Override public String read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, null); return xml.getAttributeValue(null, name()); } } /** * Reader implementation for reading the text of the current node. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class TextReader extends XMLReader<String> { TextReader() { super("", Type.TEXT); } @Override public String read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { final StringBuilder out = new StringBuilder(); int type = xml.getEventType(); do { out.append(xml.getText()); } while (xml.hasNext() && (type = xml.next()) == CHARACTERS || type == CDATA); return out.toString(); } } /** * Reader implementation for reading list of elements. * * @param <T> the element type * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ListReader<T> extends XMLReader<List<T>> { private final XMLReader<? extends T> _adoptee; ListReader(final XMLReader<? extends T> adoptee) { super(adoptee.name(), Type.LIST); _adoptee = adoptee; } @Override public List<T> read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, name()); final T element = _adoptee.read(xml, lenient); return element != null ? Collections.singletonList(element) : emptyList(); } } final class IgnoreReader extends XMLReader<Object> { private final XMLReader<Object> _reader; IgnoreReader(final String name) { super(name, Type.ELEM); _reader = new ElemReader<>(name, o -> o, emptyList(), Type.ELEM); } @Override public Object read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { return _reader.read(xml, true); } } /** * The main XML element reader implementation. * * @param <T> the reader data type * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ElemReader<T> extends XMLReader<T> { // Given parameters. private final Function<Object[], T> _creator; private final List<XMLReader<?>> _children; // Derived parameters. private final Map<String, Integer> _readerIndexMapping = new HashMap<>(); private final int[] _attrReaderIndexes; private final int[] _textReaderIndex; ElemReader( final String name, final Function<Object[], T> creator, final List<XMLReader<?>> children, final Type type ) { super(name, type); _creator = requireNonNull(creator); _children = requireNonNull(children); for (int i = 0; i < _children.size(); ++i) { _readerIndexMapping.put(_children.get(i).name(), i); } _attrReaderIndexes = IntStream.range(0, _children.size()) .filter(i -> _children.get(i).type() == Type.ATTR) .toArray(); _textReaderIndex = IntStream.range(0, _children.size()) .filter(i -> _children.get(i).type() == Type.TEXT) .toArray(); if (_textReaderIndex.length > 1) { throw new IllegalArgumentException( "Found more than one TEXT reader." ); } } @Override public T read(final XMLStreamReader xml, final boolean lenient) throws XMLStreamException { xml.require(START_ELEMENT, null, name()); final List<ReaderResult> results = _children.stream() .map(ReaderResult::of) .collect(Collectors.toList()); final ReaderResult text = _textReaderIndex.length == 1 ? results.get(_textReaderIndex[0]) : null; for (int i = 0; i < _attrReaderIndexes.length; ++i) { final ReaderResult result = results.get(_attrReaderIndexes[i]); try { result.put(result.reader().read(xml, lenient)); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) throw e; } } if (xml.hasNext()) { xml.next(); boolean hasNext = false; do { switch (xml.getEventType()) { case COMMENT: if (xml.hasNext()) { xml.next(); } break; case START_ELEMENT: final Integer index = _readerIndexMapping .get(xml.getLocalName()); if (index == null && !lenient) { throw new XMLStreamException(format( "Unexpected element <%s>.", xml.getLocalName() )); } final ReaderResult result = index != null ? results.get(index) : ReaderResult.of(elem(xml.getLocalName())); if (result != null) { throwUnexpectedElement(xml, lenient, result); if (xml.hasNext()) { hasNext = true; xml.next(); } else { hasNext = false; } } break; case CHARACTERS: case CDATA: if (text != null) { throwUnexpectedElement(xml, lenient, text); } else { xml.next(); } hasNext = true; break; case END_ELEMENT: if (name().equals(xml.getLocalName())) { try { return _creator.apply( results.stream() .map(ReaderResult::value) .toArray() ); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) { throw new XMLStreamException(format( "Invalid value for '%s'.", name()), e ); } else { return null; } } } } } while (hasNext); } throw new XMLStreamException(format( "Premature end of file while reading '%s'.", name() )); } private void throwUnexpectedElement( final XMLStreamReader xml, final boolean lenient, final ReaderResult text ) throws XMLStreamException { try { text.put(text.reader().read(xml, lenient)); } catch (IllegalArgumentException|NullPointerException e) { if (!lenient) { final XMLStreamException exp = new XMLStreamException(format( "Unexpected element <%s>.", xml.getLocalName() )); exp.addSuppressed(e); throw exp; } } } } /** * Helper interface for storing the XML reader (intermediate) results. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ interface ReaderResult { /** * Return the underlying XML reader, which reads the result. * * @return return the underlying XML reader */ XMLReader<?> reader(); /** * Put the given {@code value} to the reader result. * * @param value the reader result */ void put(final Object value); /** * Return the current reader result value. * * @return the current reader result value */ Object value(); /** * Create a reader result for the given XML reader * * @param reader the XML reader * @return a reader result for the given reader */ static ReaderResult of(final XMLReader<?> reader) { return reader.type() == Type.LIST ? new ListResult(reader) : new ValueResult(reader); } } /** * Result object for values read from XML elements. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ValueResult implements ReaderResult { private final XMLReader<?> _reader; private Object _value; ValueResult(final XMLReader<?> reader) { _reader = reader; } @Override public void put(final Object value) { _value = value; } @Override public XMLReader<?> reader() { return _reader; } @Override public Object value() { return _value; } } /** * Result object for list values read from XML elements. * * @author <a href="mailto:[email protected]">Franz Wilhelmstรถtter</a> * @version 1.2 * @since 1.2 */ final class ListResult implements ReaderResult { private final XMLReader<?> _reader; private final List<Object> _value = new ArrayList<>(); ListResult(final XMLReader<?> reader) { _reader = reader; } @Override public void put(final Object value) { if (value instanceof List<?>) { _value.addAll((List<?>)value); } else { _value.add(value); } } @Override public XMLReader<?> reader() { return _reader; } @Override public List<Object> value() { return _value; } }
#59: Implement general XML nodes reader.
jpx/src/main/java/io/jenetics/jpx/XMLReader.java
#59: Implement general XML nodes reader.
Java
apache-2.0
d95f349733bbeedfea53bacf020ab1da36ebd121
0
OpenXIP/xip-host,OpenXIP/xip-host
/** * Copyright (c) 2008 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.dcm4che2.data.Tag; import org.jdom.Document; import org.nema.dicom.wg23.ArrayOfString; import org.nema.dicom.wg23.ArrayOfUUID; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Host; import org.nema.dicom.wg23.ModelSetDescriptor; import org.nema.dicom.wg23.ObjectDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.QueryResult; import org.nema.dicom.wg23.Rectangle; import org.nema.dicom.wg23.State; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.dataAccess.DataAccessListener; import edu.wustl.xipHost.dataAccess.DataSource; import edu.wustl.xipHost.dataAccess.Query; import edu.wustl.xipHost.dataAccess.QueryEvent; import edu.wustl.xipHost.dataAccess.Retrieve; import edu.wustl.xipHost.dataAccess.RetrieveEvent; import edu.wustl.xipHost.dataAccess.RetrieveFactory; import edu.wustl.xipHost.dataAccess.RetrieveListener; import edu.wustl.xipHost.dataAccess.RetrieveTarget; import edu.wustl.xipHost.iterator.Criteria; import edu.wustl.xipHost.iterator.IteratorUtil; import edu.wustl.xipHost.iterator.IterationTarget; import edu.wustl.xipHost.iterator.IteratorElementEvent; import edu.wustl.xipHost.iterator.IteratorEvent; import edu.wustl.xipHost.iterator.NotificationRunner; import edu.wustl.xipHost.iterator.TargetElement; import edu.wustl.xipHost.iterator.TargetIteratorRunner; import edu.wustl.xipHost.iterator.TargetIteratorListener; import edu.wustl.xipHost.localFileSystem.LocalFileSystemRetrieve; import edu.wustl.xipHost.dataModel.Item; import edu.wustl.xipHost.dataModel.Patient; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dataModel.Series; import edu.wustl.xipHost.dataModel.Study; import edu.wustl.xipHost.dicom.DicomUtil; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.hostControl.Util; import edu.wustl.xipHost.hostControl.XindiceManager; import edu.wustl.xipHost.hostControl.XindiceManagerFactory; import edu.wustl.xipHost.wg23.ClientToApplication; import edu.wustl.xipHost.wg23.HostImpl; import edu.wustl.xipHost.wg23.NativeModelListener; import edu.wustl.xipHost.wg23.NativeModelRunner; import edu.wustl.xipHost.wg23.StateExecutor; import edu.wustl.xipHost.wg23.WG23DataModel; public class Application implements NativeModelListener, TargetIteratorListener, DataAccessListener, RetrieveListener { final static Logger logger = Logger.getLogger(Application.class); UUID id; String name; File exePath; String vendor; String version; File iconFile; String type; boolean requiresGUI; String wg23DataModelType; int concurrentInstances; IterationTarget iterationTarget; int numStateNotificationThreads = 2; ExecutorService exeService = Executors.newFixedThreadPool(numStateNotificationThreads); /* Application is a WG23 compatibile application*/ public Application(String name, File exePath, String vendor, String version, File iconFile, String type, boolean requiresGUI, String wg23DataModelType, int concurrentInstances, IterationTarget iterationTarget){ if(name == null || exePath == null || vendor == null || version == null || type == null || wg23DataModelType == null || iterationTarget == null){ throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath + " , " + vendor + " , " + version + type + " , " + requiresGUI + " , " + wg23DataModelType + " , " + iterationTarget); } else if(name.isEmpty() || name.trim().length() == 0 || exePath.exists() == false || type.isEmpty() || wg23DataModelType.isEmpty() || concurrentInstances == 0){ try { throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath.getCanonicalPath() + " , " + vendor + " , " + version); } catch (IOException e) { throw new IllegalArgumentException("Application exePath is invalid. Application name: " + name); } } else{ id = UUID.randomUUID(); this.name = name; this.exePath = exePath; this.vendor = vendor; this.version = version; if(iconFile != null && iconFile.exists()){ this.iconFile = iconFile; }else{ this.iconFile = null; } this.type = type; this.requiresGUI = requiresGUI; this.wg23DataModelType = wg23DataModelType; this.concurrentInstances = concurrentInstances; this.iterationTarget = iterationTarget; } } //verify this pattern /*public boolean verifyFileName(String fileName){ String str = "/ \\ : * ? \" < > | , "; Pattern filePattern = Pattern.compile(str); boolean matches = filePattern.matcher(fileName).matches(); return matches; } public static void main (String args[]){ Application app = new Application("ApplicationTest", new File("test.txt"), "", ""); System.out.println(app.getExePath().getName()); System.out.println(app.verifyFileName(app.getExePath().getName())); }*/ public UUID getID(){ return id; } public String getName(){ return name; } public void setName(String name){ if(name == null || name.isEmpty() || name.trim().length() == 0){ throw new IllegalArgumentException("Invalid application name: " + name); }else{ this.name = name; } } public File getExePath(){ return exePath; } public void setExePath(File path){ if(path == null){ throw new IllegalArgumentException("Invalid exePath name: " + path); }else{ exePath = path; } } public String getVendor(){ return vendor; } public void setVendor(String vendor){ if(vendor == null){ throw new IllegalArgumentException("Invalid vendor: " + vendor); }else{ this.vendor = vendor; } } public String getVersion(){ return version; } public void setVersion(String version){ if(version == null){ throw new IllegalArgumentException("Invalid version: " + version); }else{ this.version = version; } } public File getIconFile(){ return iconFile; } public void setIconFile(File iconFile){ if(iconFile == null){ throw new IllegalArgumentException("Invalid exePath name: " + iconFile); }else{ this.iconFile = iconFile; } } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean requiresGUI() { return requiresGUI; } public void setRequiresGUI(boolean requiresGUI) { this.requiresGUI = requiresGUI; } public String getWG23DataModelType() { return wg23DataModelType; } public void setWG23DataModelType(String wg23DataModelType) { this.wg23DataModelType = wg23DataModelType; } public int getConcurrentInstances() { return concurrentInstances; } public void setConcurrentInstances(int concurrentInstances) { this.concurrentInstances = concurrentInstances; } public IterationTarget getIterationTarget() { return iterationTarget; } public void setIterationTarget(IterationTarget iterationTarget) { this.iterationTarget = iterationTarget; } //Each application has: //1. Out directories assigned //2. clientToApplication //3. Host scheleton (reciever) //4. Data assigned for processing //5. Data produced //when launching diploy service and set URLs ClientToApplication clientToApplication; public void startClientToApplication(){ clientToApplication = new ClientToApplication(getApplicationServiceURL()); } public ClientToApplication getClientToApplication(){ return clientToApplication; } //Implementation HostImpl is used to be able to add WG23Listener //It is eventually casted to Host type Host host; //All loaded application by default will be saved again. //New instances of an application will be saved only when the save checkbox is selected Boolean doSave = true; public void setDoSave(boolean doSave){ this.doSave = doSave; } public boolean getDoSave(){ return doSave; } Endpoint hostEndpoint; URL hostServiceURL; URL appServiceURL; Thread threadNotification; public void launch(URL hostServiceURL, URL appServiceURL){ this.hostServiceURL = hostServiceURL; this.appServiceURL = appServiceURL; setApplicationOutputDir(ApplicationManagerFactory.getInstance().getOutputDir()); setApplicationPreferredSize(HostMainWindow.getApplicationPreferredSize()); //prepare native models //createNativeModels(getWG23DataModel()); //diploy host service host = new HostImpl(this); hostEndpoint = Endpoint.publish(hostServiceURL.toString(), host); // Ways of launching XIP application: exe, bat, class or jar //if(((String)getExePath().getName()).endsWith(".exe") || ((String)getExePath().getName()).endsWith(".bat")){ try { if(getExePath().toURI().toURL().toExternalForm().endsWith(".exe") || getExePath().toURI().toURL().toExternalForm().endsWith(".bat")){ try { Runtime.getRuntime().exec("cmd /c start /min " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } else if (getExePath().toURI().toURL().toExternalForm().endsWith(".sh")){ //Mac OS X compatible //To be able to run Runtime.exec() on the Mac OS X parameters must be passed via String[] instead of one String // sh files must have a executable mode and reside in XIPApp/bin directory try { String[] cmdarray = {getExePath().getAbsolutePath(), "--hostURL", hostServiceURL.toURI().toURL().toExternalForm(), "--applicationURL", appServiceURL.toURI().toURL().toExternalForm()}; logger.debug("Launching hosted application. Application name: " + getName() + " --hostURL " + hostServiceURL.toURI().toURL().toExternalForm() + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); Runtime.getRuntime().exec(cmdarray) ; } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } else { try { Runtime.getRuntime().exec(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } } catch (MalformedURLException e) { logger.error(e, e); } TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, getIterationTarget(), query, this); try { Thread t = new Thread(targetIter); t.start(); } catch(Exception e) { logger.error(e, e); } } public Endpoint getHostEndpoint(){ return hostEndpoint; } File appOutputDir; public void setApplicationOutputDir(File outDir){ try { appOutputDir = Util.create("xipOUT_" + getName() + "_", "", outDir); } catch (IOException e) { logger.error(e, e); } } public File getApplicationOutputDir() { return appOutputDir; } File appTmpDir; public void setApplicationTmpDir(File tmpDir){ appTmpDir = tmpDir; } public File getApplicationTmpDir() { return appTmpDir; } java.awt.Rectangle preferredSize; public void setApplicationPreferredSize(java.awt.Rectangle preferredSize){ this.preferredSize = preferredSize; } State priorState = null; State state = null; boolean firstLaunch = true; int numberOfSentNotifications = 0; public void setState(State state){ priorState = this.state; this.state = state; logger.debug("\"" + getName() + "\"" + " state changed to: " + this.state); if (state.equals(State.IDLE)){ if(firstLaunch){ startClientToApplication(); notifyAddSideTab(); firstLaunch = false; StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } else { //Check if prior State was CANSELED, If yes proceed with change state to EXIT. If not to INPROGRESS. if(priorState.equals(State.CANCELED)){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.EXIT); exeService.execute(stateExecutor); return; } synchronized(this){ if(iter != null){ boolean doInprogress = true; synchronized(targetElements){ if(numberOfSentNotifications == targetElements.size()){ doInprogress = false; } } if(doInprogress == false){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.EXIT); exeService.execute(stateExecutor); } else { StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } } else { StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } } } } else if(state.equals(State.INPROGRESS)){ synchronized(targetElements){ while(targetElements.size() == 0 || targetElements.size() <= numberOfSentNotifications){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } TargetElement element = targetElements.get(numberOfSentNotifications); AvailableData availableData = IteratorUtil.getAvailableData(element); NotificationRunner runner = new NotificationRunner(this); //runner.setAvailableData(wg23data.getAvailableData()); runner.setAvailableData(availableData); threadNotification = new Thread(runner); threadNotification.start(); numberOfSentNotifications++; } } else if (state.equals(State.CANCELED)){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.IDLE); exeService.execute(stateExecutor); } else if (state.equals(State.EXIT)){ //Application runShutDownSequence goes through ApplicationTerminator and Application Scheduler //ApplicationScheduler time is set to zero but other value could be used when shutdown delay is needed. ApplicationTerminator terminator = new ApplicationTerminator(this); Thread t = new Thread(terminator); t.start(); //reset application parameters for subsequent launch firstLaunch = true; retrievedTargetElements.clear(); targetElements.clear(); iter = null; numberOfSentNotifications = 0; retrievedTargetElements.clear(); } } public State getState(){ return state; } public State getPriorState(){ return priorState; } WG23DataModel wg23dm = null; public void setData(WG23DataModel wg23DataModel){ this.wg23dm = wg23DataModel; } public WG23DataModel getWG23DataModel(){ return wg23dm; } SearchResult selectedDataSearchResult; public void setSelectedDataSearchResult(SearchResult selectedDataSearchResult){ this.selectedDataSearchResult = selectedDataSearchResult; } Query query; public void setQueryDataSource(Query query){ this.query = query; } Retrieve retrieve; public void setRetrieveDataSource(Retrieve retrieve){ this.retrieve = retrieve; } public Rectangle getApplicationPreferredSize() { double x = preferredSize.getX(); double y = preferredSize.getY(); double width = preferredSize.getWidth(); double height = preferredSize.getHeight(); Rectangle rect = new Rectangle(); rect.setRefPointX(new Double(x).intValue()); rect.setRefPointY(new Double(y).intValue()); rect.setWidth(new Double(width).intValue()); rect.setHeight(new Double(height).intValue()); return rect; } public URL getApplicationServiceURL(){ return appServiceURL; } public void notifyAddSideTab(){ HostMainWindow.addTab(getName(), getID()); } public void bringToFront(){ clientToApplication.bringToFront(); } public boolean shutDown(){ if(getState().equals(State.IDLE)){ if(getClientToApplication().setState(State.EXIT)){ return true; } }else{ cancelProcessing(); /*if(cancelProcessing()){ return shutDown(); } */ } return false; } public void runShutDownSequence(){ HostMainWindow.removeTab(getID()); if(getHostEndpoint() != null){ getHostEndpoint().stop(); } fireTerminateApplication(); /* voided to make compatibile with the iterator //Delete documents from Xindice created for this application XindiceManagerFactory.getInstance().deleteAllDocuments(getID().toString()); //Delete collection created for this application XindiceManagerFactory.getInstance().deleteCollection(getID().toString()); */ } public boolean cancelProcessing(){ if(getState().equals(State.INPROGRESS) || getState().equals(State.SUSPENDED)){ return getClientToApplication().setState(State.CANCELED); }else{ return false; } } public boolean suspendProcessing(){ if(getState().equals(State.INPROGRESS)){ return getClientToApplication().setState(State.SUSPENDED); }else{ return false; } } /** * Method is used to create XML native models for all object locators * found in WG23DataModel. * It uses threads and add NativeModelListener to the NativeModelRunner * @param wg23dm */ void createNativeModels(WG23DataModel wg23dm){ if(XindiceManagerFactory.getInstance().createCollection(getID().toString())){ ObjectLocator[] objLocs = wg23dm.getObjectLocators(); for (int i = 0; i < objLocs.length; i++){ boolean isDICOM = false; try { isDICOM = DicomUtil.isDICOM(new File(new URI(objLocs[i].getUri()))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(isDICOM){ NativeModelRunner nmRunner; nmRunner = new NativeModelRunner(objLocs[i]); nmRunner.addNativeModelListener(this); Thread t = new Thread(nmRunner); t.start(); } } }else{ //TODO //Action when system cannot create collection } } /** * Adds JDOM Document to Xindice collection. * Only valid documents (e.g. not null, with root element) will be added * (non-Javadoc) * @see edu.wustl.xipHost.wg23.NativeModelListener#nativeModelAvailable(org.jdom.Document, org.nema.dicom.wg23.Uuid) */ public void nativeModelAvailable(Document doc, Uuid objUUID) { XindiceManagerFactory.getInstance().addDocument(doc, getID().toString(), objUUID); } public void nativeModelAvailable(String xmlNativeModel) { // Ignore in XIP Host. // Used by AVT AD } /** * Method returns ModelSetDescriptor containing UUID of native models * as well as UUID of object locators for which native models could * not be created * @param objUUIDs * @return */ public ModelSetDescriptor getModelSetDescriptor(List<Uuid> objUUIDs){ String[] models = XindiceManagerFactory.getInstance().getModelUUIDs(getID().toString()); List<String> listModels = Arrays.asList(models); ModelSetDescriptor msd = new ModelSetDescriptor(); ArrayOfUUID uuidsModels = new ArrayOfUUID(); List<Uuid> listUUIDs = uuidsModels.getUuid(); ArrayOfUUID uuidsFailed = new ArrayOfUUID(); List<Uuid> listUUIDsFailed = uuidsFailed.getUuid(); for(int i = 0; i < objUUIDs.size(); i++){ Uuid uuid = new Uuid(); if(objUUIDs.get(i) == null || objUUIDs.get(i).getUuid() == null){ //do not add anything to model set descriptor }else if(objUUIDs.get(i).getUuid().toString().trim().isEmpty()){ //do not add anything to model set descriptor }else if(listModels.contains("wg23NM-"+ objUUIDs.get(i).getUuid())){ int index = listModels.indexOf("wg23NM-"+ objUUIDs.get(i).getUuid()); uuid.setUuid(listModels.get(index)); listUUIDs.add(uuid); }else{ uuid.setUuid(objUUIDs.get(i).getUuid()); listUUIDsFailed.add(uuid); } } msd.setModels(uuidsModels); msd.setFailedSourceObjects(uuidsFailed); return msd; } /** * queryResults list hold teh values from queryResultAvailable */ List<QueryResult> queryResults; public List<QueryResult> queryModel(List<Uuid> modelUUIDs, List<String> listXPaths){ queryResults = new ArrayList<QueryResult>(); if(modelUUIDs == null || listXPaths == null){ return queryResults; } String collectionName = getID().toString(); XindiceManager xm = XindiceManagerFactory.getInstance(); for(int i = 0; i < listXPaths.size(); i++){ for(int j = 0; j < modelUUIDs.size(); j++){ //String[] results = xm.query(service, collectionName, modelUUIDs.get(j), listXPaths.get(i)); String[] results = xm.query(collectionName, modelUUIDs.get(j), listXPaths.get(i)); QueryResult queryResult = new QueryResult(); queryResult.setModel(modelUUIDs.get(j)); queryResult.setXpath(listXPaths.get(i)); ArrayOfString arrayOfString = new ArrayOfString(); List<String> listString = arrayOfString.getString(); for(int k = 0; k < results.length; k++){ listString.add(results[k]); } queryResult.setResults(arrayOfString); queryResults.add(queryResult); } } return queryResults; } Iterator<TargetElement> iter; @SuppressWarnings("unchecked") @Override public void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>)e.getSource(); logger.debug("Full TargetIterator available at time " + System.currentTimeMillis()); } List<TargetElement> targetElements = new ArrayList<TargetElement>(); @Override public void targetElementAvailable(IteratorElementEvent e) { synchronized(targetElements){ TargetElement element = (TargetElement) e.getSource(); logger.debug("TargetElement available. ID: " + element.getId() + " at time " + System.currentTimeMillis()); targetElements.add(element); targetElements.notify(); } } String dataSourceDomainName; public void setDataSourceDomainName(String dataSourceDomainName){ this.dataSourceDomainName = dataSourceDomainName; } DataSource dataSource; public void setDataSource(DataSource dataSource){ this.dataSource = dataSource; } RetrieveTarget retrieveTarget; public void setRetrieveTarget(RetrieveTarget retrieveTarget){ this.retrieveTarget = retrieveTarget; } public List<ObjectLocator> retrieveAndGetLocators(List<Uuid> listUUIDs){ //First check if data was already retrieved boolean retrieveComplete = true; List<ObjectLocator> listObjLocs = new ArrayList<ObjectLocator>(); if(!retrievedData.isEmpty()){ for(Uuid uuid : listUUIDs){ String strUuid = uuid.getUuid(); ObjectLocator objLoc = retrievedData.get(strUuid); if(objLoc != null){ logger.debug(strUuid + " " + objLoc.getUri()); listObjLocs.add(objLoc); } else { retrieveComplete = false; listObjLocs.clear(); break; } } if(retrieveComplete){ return listObjLocs; } } //Start data retrieval related to the element //RetrieveTarget retrieveTarget = RetrieveTarget.DICOM_AND_AIM; TargetElement element = null; synchronized(targetElements){ element = targetElements.get(numberOfSentNotifications - 1); //1. Find targetElement where uuids are; Optimization task Retrieve retrieve = RetrieveFactory.getInstance(dataSourceDomainName); File importDir = getApplicationTmpDir(); retrieve.setImportDir(importDir); retrieve.setRetrieveTarget(retrieveTarget); retrieve.setDataSource(dataSource); retrieve.addRetrieveListener(this); SearchResult subSearchResult = element.getSubSearchResult(); Criteria originalCriteria = subSearchResult.getOriginalCriteria(); Map<Integer, Object> dicomCriteria = originalCriteria.getDICOMCriteria(); Map<String, Object> aimCriteria = originalCriteria.getAIMCriteria(); List<Patient> patients = subSearchResult.getPatients(); for(Patient patient : patients){ dicomCriteria.put(Tag.PatientName, patient.getPatientName()); dicomCriteria.put(Tag.PatientID, patient.getPatientID()); List<Study> studies = patient.getStudies(); for(Study study : studies){ dicomCriteria.put(Tag.StudyInstanceUID, study.getStudyInstanceUID()); List<Series> series = study.getSeries(); for(Series oneSeries : series){ dicomCriteria.put(Tag.SeriesInstanceUID, oneSeries.getSeriesInstanceUID()); if(aimCriteria == null){ logger.debug("AD AIM criteria: " + aimCriteria); }else{ logger.debug("AD AIM retrieve criteria:"); Set<String> keys = aimCriteria.keySet(); Iterator<String> iter = keys.iterator(); while(iter.hasNext()){ String key = iter.next(); String value = (String) aimCriteria.get(key); if(!value.isEmpty()){ logger.debug("Key: " + key + " Value: " + value); } } } List<ObjectDescriptor> objectDescriptors = new ArrayList<ObjectDescriptor>(); List<Item> items = oneSeries.getItems(); for(Item item : items){ objectDescriptors.add(item.getObjectDescriptor()); } //If oneSeries contains subset of items, narrow dicomCriteria to individual SOPInstanceUIDs //Then retrieve data item by item if(oneSeries.containsSubsetOfItems()){ for(Item item : items){ String itemSOPInstanceUID = item.getItemID(); dicomCriteria.put(Tag.SOPInstanceUID, itemSOPInstanceUID); if(retrieve instanceof LocalFileSystemRetrieve){ retrieve.setCriteria(selectedDataSearchResult); } else { retrieve.setCriteria(dicomCriteria, aimCriteria); } List<ObjectDescriptor> objectDesc = new ArrayList<ObjectDescriptor>(); objectDesc.add(item.getObjectDescriptor()); retrieve.setObjectDescriptors(objectDesc); Thread t = new Thread(retrieve); t.start(); //dicomCriteria.remove(Tag.SOPInstanceUID); try { t.join(); //Reset value of SOPInstanceUID in dicomCriteria dicomCriteria.remove(Tag.SOPInstanceUID); } catch (InterruptedException e) { logger.error(e, e); } } } else { dicomCriteria.put(Tag.SOPInstanceUID, "*"); if(retrieve instanceof LocalFileSystemRetrieve){ retrieve.setCriteria(selectedDataSearchResult); } else { retrieve.setCriteria(dicomCriteria, aimCriteria); retrieve.setObjectDescriptors(objectDescriptors); } Thread t = new Thread(retrieve); t.start(); try { t.join(); } catch (InterruptedException e) { logger.error(e, e); } } //Reset Series level dicomCriteria dicomCriteria.remove(Tag.SeriesInstanceUID); } //Reset Study level dicomCriteria dicomCriteria.remove(Tag.StudyInstanceUID); } //Reset Patient level dicomCriteria dicomCriteria.remove(Tag.PatientName); dicomCriteria.remove(Tag.PatientID); } } //Wait for actual data being retrieved before sending file pointers synchronized(retrievedData){ while(retrievedData.isEmpty()){ try { retrievedData.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } if(listUUIDs == null){ return new ArrayList<ObjectLocator>(); } else { for(Uuid uuid : listUUIDs){ String strUuid = uuid.getUuid(); ObjectLocator objLoc = retrievedData.get(strUuid); logger.debug(strUuid + " " + objLoc.getUri()); listObjLocs.add(objLoc); } return listObjLocs; } } @Override public void notifyException(String message) { // TODO Auto-generated method stub } @Override public void queryResultsAvailable(QueryEvent e) { // TODO Auto-generated method stub } List<String> retrievedTargetElements = new ArrayList<String>(); Map <String, ObjectLocator> retrievedData = new HashMap<String, ObjectLocator>(); @SuppressWarnings("unchecked") @Override public void retrieveResultsAvailable(RetrieveEvent e) { synchronized(retrievedData){ Map<String, ObjectLocator> objectLocators = (Map<String, ObjectLocator>) e.getSource(); retrievedData.putAll(objectLocators); Iterator<String> keySet = objectLocators.keySet().iterator(); logger.debug("Items retrieved: "); while(keySet.hasNext()){ String uuid = keySet.next(); ObjectLocator objLoc = objectLocators.get(uuid); logger.debug("UUID: " + uuid + " Item location: " + objLoc.getUri()); } retrievedData.notify(); } } ApplicationTerminationListener applicationTerminationListener; public void addApplicationTerminationListener(ApplicationTerminationListener applicationTerminationListener){ this.applicationTerminationListener = applicationTerminationListener; } void fireTerminateApplication(){ ApplicationTerminationEvent event = new ApplicationTerminationEvent(this); applicationTerminationListener.applicationTerminated(event); } }
src/edu/wustl/xipHost/application/Application.java
/** * Copyright (c) 2008 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.application; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.xml.ws.Endpoint; import org.apache.log4j.Logger; import org.dcm4che2.data.Tag; import org.jdom.Document; import org.nema.dicom.wg23.ArrayOfString; import org.nema.dicom.wg23.ArrayOfUUID; import org.nema.dicom.wg23.AvailableData; import org.nema.dicom.wg23.Host; import org.nema.dicom.wg23.ModelSetDescriptor; import org.nema.dicom.wg23.ObjectDescriptor; import org.nema.dicom.wg23.ObjectLocator; import org.nema.dicom.wg23.QueryResult; import org.nema.dicom.wg23.Rectangle; import org.nema.dicom.wg23.State; import org.nema.dicom.wg23.Uuid; import edu.wustl.xipHost.dataAccess.DataAccessListener; import edu.wustl.xipHost.dataAccess.DataSource; import edu.wustl.xipHost.dataAccess.Query; import edu.wustl.xipHost.dataAccess.QueryEvent; import edu.wustl.xipHost.dataAccess.Retrieve; import edu.wustl.xipHost.dataAccess.RetrieveEvent; import edu.wustl.xipHost.dataAccess.RetrieveFactory; import edu.wustl.xipHost.dataAccess.RetrieveListener; import edu.wustl.xipHost.dataAccess.RetrieveTarget; import edu.wustl.xipHost.iterator.Criteria; import edu.wustl.xipHost.iterator.IteratorUtil; import edu.wustl.xipHost.iterator.IterationTarget; import edu.wustl.xipHost.iterator.IteratorElementEvent; import edu.wustl.xipHost.iterator.IteratorEvent; import edu.wustl.xipHost.iterator.NotificationRunner; import edu.wustl.xipHost.iterator.TargetElement; import edu.wustl.xipHost.iterator.TargetIteratorRunner; import edu.wustl.xipHost.iterator.TargetIteratorListener; import edu.wustl.xipHost.localFileSystem.LocalFileSystemRetrieve; import edu.wustl.xipHost.dataModel.Item; import edu.wustl.xipHost.dataModel.Patient; import edu.wustl.xipHost.dataModel.SearchResult; import edu.wustl.xipHost.dataModel.Series; import edu.wustl.xipHost.dataModel.Study; import edu.wustl.xipHost.dicom.DicomUtil; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.hostControl.Util; import edu.wustl.xipHost.hostControl.XindiceManager; import edu.wustl.xipHost.hostControl.XindiceManagerFactory; import edu.wustl.xipHost.wg23.ClientToApplication; import edu.wustl.xipHost.wg23.HostImpl; import edu.wustl.xipHost.wg23.NativeModelListener; import edu.wustl.xipHost.wg23.NativeModelRunner; import edu.wustl.xipHost.wg23.StateExecutor; import edu.wustl.xipHost.wg23.WG23DataModel; public class Application implements NativeModelListener, TargetIteratorListener, DataAccessListener, RetrieveListener { final static Logger logger = Logger.getLogger(Application.class); UUID id; String name; File exePath; String vendor; String version; File iconFile; String type; boolean requiresGUI; String wg23DataModelType; int concurrentInstances; IterationTarget iterationTarget; int numStateNotificationThreads = 2; ExecutorService exeService = Executors.newFixedThreadPool(numStateNotificationThreads); /* Application is a WG23 compatibile application*/ public Application(String name, File exePath, String vendor, String version, File iconFile, String type, boolean requiresGUI, String wg23DataModelType, int concurrentInstances, IterationTarget iterationTarget){ if(name == null || exePath == null || vendor == null || version == null || type == null || wg23DataModelType == null || iterationTarget == null){ throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath + " , " + vendor + " , " + version + type + " , " + requiresGUI + " , " + wg23DataModelType + " , " + iterationTarget); } else if(name.isEmpty() || name.trim().length() == 0 || exePath.exists() == false || type.isEmpty() || wg23DataModelType.isEmpty() || concurrentInstances == 0){ try { throw new IllegalArgumentException("Application parameters are invalid: " + name + " , " + exePath.getCanonicalPath() + " , " + vendor + " , " + version); } catch (IOException e) { throw new IllegalArgumentException("Application exePath is invalid. Application name: " + name); } } else{ id = UUID.randomUUID(); this.name = name; this.exePath = exePath; this.vendor = vendor; this.version = version; if(iconFile != null && iconFile.exists()){ this.iconFile = iconFile; }else{ this.iconFile = null; } this.type = type; this.requiresGUI = requiresGUI; this.wg23DataModelType = wg23DataModelType; this.concurrentInstances = concurrentInstances; this.iterationTarget = iterationTarget; } } //verify this pattern /*public boolean verifyFileName(String fileName){ String str = "/ \\ : * ? \" < > | , "; Pattern filePattern = Pattern.compile(str); boolean matches = filePattern.matcher(fileName).matches(); return matches; } public static void main (String args[]){ Application app = new Application("ApplicationTest", new File("test.txt"), "", ""); System.out.println(app.getExePath().getName()); System.out.println(app.verifyFileName(app.getExePath().getName())); }*/ public UUID getID(){ return id; } public String getName(){ return name; } public void setName(String name){ if(name == null || name.isEmpty() || name.trim().length() == 0){ throw new IllegalArgumentException("Invalid application name: " + name); }else{ this.name = name; } } public File getExePath(){ return exePath; } public void setExePath(File path){ if(path == null){ throw new IllegalArgumentException("Invalid exePath name: " + path); }else{ exePath = path; } } public String getVendor(){ return vendor; } public void setVendor(String vendor){ if(vendor == null){ throw new IllegalArgumentException("Invalid vendor: " + vendor); }else{ this.vendor = vendor; } } public String getVersion(){ return version; } public void setVersion(String version){ if(version == null){ throw new IllegalArgumentException("Invalid version: " + version); }else{ this.version = version; } } public File getIconFile(){ return iconFile; } public void setIconFile(File iconFile){ if(iconFile == null){ throw new IllegalArgumentException("Invalid exePath name: " + iconFile); }else{ this.iconFile = iconFile; } } public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean requiresGUI() { return requiresGUI; } public void setRequiresGUI(boolean requiresGUI) { this.requiresGUI = requiresGUI; } public String getWG23DataModelType() { return wg23DataModelType; } public void setWG23DataModelType(String wg23DataModelType) { this.wg23DataModelType = wg23DataModelType; } public int getConcurrentInstances() { return concurrentInstances; } public void setConcurrentInstances(int concurrentInstances) { this.concurrentInstances = concurrentInstances; } public IterationTarget getIterationTarget() { return iterationTarget; } public void setIterationTarget(IterationTarget iterationTarget) { this.iterationTarget = iterationTarget; } //Each application has: //1. Out directories assigned //2. clientToApplication //3. Host scheleton (reciever) //4. Data assigned for processing //5. Data produced //when launching diploy service and set URLs ClientToApplication clientToApplication; public void startClientToApplication(){ clientToApplication = new ClientToApplication(getApplicationServiceURL()); } public ClientToApplication getClientToApplication(){ return clientToApplication; } //Implementation HostImpl is used to be able to add WG23Listener //It is eventually casted to Host type Host host; //All loaded application by default will be saved again. //New instances of an application will be saved only when the save checkbox is selected Boolean doSave = true; public void setDoSave(boolean doSave){ this.doSave = doSave; } public boolean getDoSave(){ return doSave; } Endpoint hostEndpoint; URL hostServiceURL; URL appServiceURL; Thread threadNotification; public void launch(URL hostServiceURL, URL appServiceURL){ this.hostServiceURL = hostServiceURL; this.appServiceURL = appServiceURL; setApplicationOutputDir(ApplicationManagerFactory.getInstance().getOutputDir()); setApplicationPreferredSize(HostMainWindow.getApplicationPreferredSize()); //prepare native models //createNativeModels(getWG23DataModel()); //diploy host service host = new HostImpl(this); hostEndpoint = Endpoint.publish(hostServiceURL.toString(), host); // Ways of launching XIP application: exe, bat, class or jar //if(((String)getExePath().getName()).endsWith(".exe") || ((String)getExePath().getName()).endsWith(".bat")){ try { if(getExePath().toURI().toURL().toExternalForm().endsWith(".exe") || getExePath().toURI().toURL().toExternalForm().endsWith(".bat")){ try { Runtime.getRuntime().exec("cmd /c start /min " + getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } else if (getExePath().toURI().toURL().toExternalForm().endsWith(".sh")){ //Mac OS X compatible //To be able to run Runtime.exec() on the Mac OS X parameters must be passed via String[] instead of one String // sh files must have a executable mode and reside in XIPApp/bin directory try { String[] cmdarray = {getExePath().getAbsolutePath(), "--hostURL", hostServiceURL.toURI().toURL().toExternalForm(), "--applicationURL", appServiceURL.toURI().toURL().toExternalForm()}; logger.debug("Launching hosted application. Application name: " + getName() + " --hostURL " + hostServiceURL.toURI().toURL().toExternalForm() + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); Runtime.getRuntime().exec(cmdarray) ; } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } else { try { Runtime.getRuntime().exec(getExePath().toURI().toURL().toExternalForm() + " " + "--hostURL" + " " + hostServiceURL.toURI().toURL().toExternalForm() + " " + "--applicationURL" + " " + appServiceURL.toURI().toURL().toExternalForm()); } catch (IOException e) { logger.error(e, e); } catch (URISyntaxException e) { logger.error(e, e); } } } catch (MalformedURLException e) { logger.error(e, e); } TargetIteratorRunner targetIter = new TargetIteratorRunner(selectedDataSearchResult, getIterationTarget(), query, this); try { Thread t = new Thread(targetIter); t.start(); } catch(Exception e) { logger.error(e, e); } } public Endpoint getHostEndpoint(){ return hostEndpoint; } File appOutputDir; public void setApplicationOutputDir(File outDir){ try { appOutputDir = Util.create("xipOUT_" + getName() + "_", "", outDir); } catch (IOException e) { logger.error(e, e); } } public File getApplicationOutputDir() { return appOutputDir; } File appTmpDir; public void setApplicationTmpDir(File tmpDir){ appTmpDir = tmpDir; } public File getApplicationTmpDir() { return appTmpDir; } java.awt.Rectangle preferredSize; public void setApplicationPreferredSize(java.awt.Rectangle preferredSize){ this.preferredSize = preferredSize; } State priorState = null; State state = null; boolean firstLaunch = true; int numberOfSentNotifications = 0; public void setState(State state){ priorState = this.state; this.state = state; logger.debug("\"" + getName() + "\"" + " state changed to: " + this.state); if (state.equals(State.IDLE)){ if(firstLaunch){ startClientToApplication(); notifyAddSideTab(); firstLaunch = false; StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } else { //Check if prior State was CANSELED, If yes proceed with change state to EXIT. If not to INPROGRESS. if(priorState.equals(State.CANCELED)){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.EXIT); exeService.execute(stateExecutor); return; } synchronized(this){ if(iter != null){ boolean doInprogress = true; synchronized(targetElements){ if(numberOfSentNotifications == targetElements.size()){ doInprogress = false; } } if(doInprogress == false){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.EXIT); exeService.execute(stateExecutor); } else { StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } } else { StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.INPROGRESS); exeService.execute(stateExecutor); } } } } else if(state.equals(State.INPROGRESS)){ synchronized(targetElements){ while(targetElements.size() == 0 || targetElements.size() <= numberOfSentNotifications){ try { targetElements.wait(); } catch (InterruptedException e) { logger.error(e, e); } } TargetElement element = targetElements.get(numberOfSentNotifications); AvailableData availableData = IteratorUtil.getAvailableData(element); NotificationRunner runner = new NotificationRunner(this); //runner.setAvailableData(wg23data.getAvailableData()); runner.setAvailableData(availableData); threadNotification = new Thread(runner); threadNotification.start(); numberOfSentNotifications++; } } else if (state.equals(State.CANCELED)){ StateExecutor stateExecutor = new StateExecutor(this); stateExecutor.setState(State.IDLE); exeService.execute(stateExecutor); } else if (state.equals(State.EXIT)){ //Application runShutDownSequence goes through ApplicationTerminator and Application Scheduler //ApplicationScheduler time is set to zero but other value could be used when shutdown delay is needed. ApplicationTerminator terminator = new ApplicationTerminator(this); Thread t = new Thread(terminator); t.start(); //reset application parameters for subsequent launch firstLaunch = true; retrievedTargetElements.clear(); targetElements.clear(); iter = null; numberOfSentNotifications = 0; retrievedTargetElements.clear(); } } public State getState(){ return state; } public State getPriorState(){ return priorState; } WG23DataModel wg23dm = null; public void setData(WG23DataModel wg23DataModel){ this.wg23dm = wg23DataModel; } public WG23DataModel getWG23DataModel(){ return wg23dm; } SearchResult selectedDataSearchResult; public void setSelectedDataSearchResult(SearchResult selectedDataSearchResult){ this.selectedDataSearchResult = selectedDataSearchResult; } Query query; public void setQueryDataSource(Query query){ this.query = query; } Retrieve retrieve; public void setRetrieveDataSource(Retrieve retrieve){ this.retrieve = retrieve; } public Rectangle getApplicationPreferredSize() { double x = preferredSize.getX(); double y = preferredSize.getY(); double width = preferredSize.getWidth(); double height = preferredSize.getHeight(); Rectangle rect = new Rectangle(); rect.setRefPointX(new Double(x).intValue()); rect.setRefPointY(new Double(y).intValue()); rect.setWidth(new Double(width).intValue()); rect.setHeight(new Double(height).intValue()); return rect; } public URL getApplicationServiceURL(){ return appServiceURL; } public void notifyAddSideTab(){ HostMainWindow.addTab(getName(), getID()); } public void bringToFront(){ clientToApplication.bringToFront(); } public boolean shutDown(){ if(getState().equals(State.IDLE)){ if(getClientToApplication().setState(State.EXIT)){ return true; } }else{ cancelProcessing(); /*if(cancelProcessing()){ return shutDown(); } */ } return false; } public void runShutDownSequence(){ HostMainWindow.removeTab(getID()); if(getHostEndpoint() != null){ getHostEndpoint().stop(); } /* voided to make compatibile with the iterator //Delete documents from Xindice created for this application XindiceManagerFactory.getInstance().deleteAllDocuments(getID().toString()); //Delete collection created for this application XindiceManagerFactory.getInstance().deleteCollection(getID().toString()); */ } public boolean cancelProcessing(){ if(getState().equals(State.INPROGRESS) || getState().equals(State.SUSPENDED)){ return getClientToApplication().setState(State.CANCELED); }else{ return false; } } public boolean suspendProcessing(){ if(getState().equals(State.INPROGRESS)){ return getClientToApplication().setState(State.SUSPENDED); }else{ return false; } } /** * Method is used to create XML native models for all object locators * found in WG23DataModel. * It uses threads and add NativeModelListener to the NativeModelRunner * @param wg23dm */ void createNativeModels(WG23DataModel wg23dm){ if(XindiceManagerFactory.getInstance().createCollection(getID().toString())){ ObjectLocator[] objLocs = wg23dm.getObjectLocators(); for (int i = 0; i < objLocs.length; i++){ boolean isDICOM = false; try { isDICOM = DicomUtil.isDICOM(new File(new URI(objLocs[i].getUri()))); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(isDICOM){ NativeModelRunner nmRunner; nmRunner = new NativeModelRunner(objLocs[i]); nmRunner.addNativeModelListener(this); Thread t = new Thread(nmRunner); t.start(); } } }else{ //TODO //Action when system cannot create collection } } /** * Adds JDOM Document to Xindice collection. * Only valid documents (e.g. not null, with root element) will be added * (non-Javadoc) * @see edu.wustl.xipHost.wg23.NativeModelListener#nativeModelAvailable(org.jdom.Document, org.nema.dicom.wg23.Uuid) */ public void nativeModelAvailable(Document doc, Uuid objUUID) { XindiceManagerFactory.getInstance().addDocument(doc, getID().toString(), objUUID); } public void nativeModelAvailable(String xmlNativeModel) { // Ignore in XIP Host. // Used by AVT AD } /** * Method returns ModelSetDescriptor containing UUID of native models * as well as UUID of object locators for which native models could * not be created * @param objUUIDs * @return */ public ModelSetDescriptor getModelSetDescriptor(List<Uuid> objUUIDs){ String[] models = XindiceManagerFactory.getInstance().getModelUUIDs(getID().toString()); List<String> listModels = Arrays.asList(models); ModelSetDescriptor msd = new ModelSetDescriptor(); ArrayOfUUID uuidsModels = new ArrayOfUUID(); List<Uuid> listUUIDs = uuidsModels.getUuid(); ArrayOfUUID uuidsFailed = new ArrayOfUUID(); List<Uuid> listUUIDsFailed = uuidsFailed.getUuid(); for(int i = 0; i < objUUIDs.size(); i++){ Uuid uuid = new Uuid(); if(objUUIDs.get(i) == null || objUUIDs.get(i).getUuid() == null){ //do not add anything to model set descriptor }else if(objUUIDs.get(i).getUuid().toString().trim().isEmpty()){ //do not add anything to model set descriptor }else if(listModels.contains("wg23NM-"+ objUUIDs.get(i).getUuid())){ int index = listModels.indexOf("wg23NM-"+ objUUIDs.get(i).getUuid()); uuid.setUuid(listModels.get(index)); listUUIDs.add(uuid); }else{ uuid.setUuid(objUUIDs.get(i).getUuid()); listUUIDsFailed.add(uuid); } } msd.setModels(uuidsModels); msd.setFailedSourceObjects(uuidsFailed); return msd; } /** * queryResults list hold teh values from queryResultAvailable */ List<QueryResult> queryResults; public List<QueryResult> queryModel(List<Uuid> modelUUIDs, List<String> listXPaths){ queryResults = new ArrayList<QueryResult>(); if(modelUUIDs == null || listXPaths == null){ return queryResults; } String collectionName = getID().toString(); XindiceManager xm = XindiceManagerFactory.getInstance(); for(int i = 0; i < listXPaths.size(); i++){ for(int j = 0; j < modelUUIDs.size(); j++){ //String[] results = xm.query(service, collectionName, modelUUIDs.get(j), listXPaths.get(i)); String[] results = xm.query(collectionName, modelUUIDs.get(j), listXPaths.get(i)); QueryResult queryResult = new QueryResult(); queryResult.setModel(modelUUIDs.get(j)); queryResult.setXpath(listXPaths.get(i)); ArrayOfString arrayOfString = new ArrayOfString(); List<String> listString = arrayOfString.getString(); for(int k = 0; k < results.length; k++){ listString.add(results[k]); } queryResult.setResults(arrayOfString); queryResults.add(queryResult); } } return queryResults; } Iterator<TargetElement> iter; @SuppressWarnings("unchecked") @Override public void fullIteratorAvailable(IteratorEvent e) { iter = (Iterator<TargetElement>)e.getSource(); logger.debug("Full TargetIterator available at time " + System.currentTimeMillis()); } List<TargetElement> targetElements = new ArrayList<TargetElement>(); @Override public void targetElementAvailable(IteratorElementEvent e) { synchronized(targetElements){ TargetElement element = (TargetElement) e.getSource(); logger.debug("TargetElement available. ID: " + element.getId() + " at time " + System.currentTimeMillis()); targetElements.add(element); targetElements.notify(); } } String dataSourceDomainName; public void setDataSourceDomainName(String dataSourceDomainName){ this.dataSourceDomainName = dataSourceDomainName; } DataSource dataSource; public void setDataSource(DataSource dataSource){ this.dataSource = dataSource; } RetrieveTarget retrieveTarget; public void setRetrieveTarget(RetrieveTarget retrieveTarget){ this.retrieveTarget = retrieveTarget; } public List<ObjectLocator> retrieveAndGetLocators(List<Uuid> listUUIDs){ //First check if data was already retrieved boolean retrieveComplete = true; List<ObjectLocator> listObjLocs = new ArrayList<ObjectLocator>(); if(!retrievedData.isEmpty()){ for(Uuid uuid : listUUIDs){ String strUuid = uuid.getUuid(); ObjectLocator objLoc = retrievedData.get(strUuid); if(objLoc != null){ logger.debug(strUuid + " " + objLoc.getUri()); listObjLocs.add(objLoc); } else { retrieveComplete = false; listObjLocs.clear(); break; } } if(retrieveComplete){ return listObjLocs; } } //Start data retrieval related to the element //RetrieveTarget retrieveTarget = RetrieveTarget.DICOM_AND_AIM; TargetElement element = null; synchronized(targetElements){ element = targetElements.get(numberOfSentNotifications - 1); //1. Find targetElement where uuids are; Optimization task Retrieve retrieve = RetrieveFactory.getInstance(dataSourceDomainName); File importDir = getApplicationTmpDir(); retrieve.setImportDir(importDir); retrieve.setRetrieveTarget(retrieveTarget); retrieve.setDataSource(dataSource); retrieve.addRetrieveListener(this); SearchResult subSearchResult = element.getSubSearchResult(); Criteria originalCriteria = subSearchResult.getOriginalCriteria(); Map<Integer, Object> dicomCriteria = originalCriteria.getDICOMCriteria(); Map<String, Object> aimCriteria = originalCriteria.getAIMCriteria(); List<Patient> patients = subSearchResult.getPatients(); for(Patient patient : patients){ dicomCriteria.put(Tag.PatientName, patient.getPatientName()); dicomCriteria.put(Tag.PatientID, patient.getPatientID()); List<Study> studies = patient.getStudies(); for(Study study : studies){ dicomCriteria.put(Tag.StudyInstanceUID, study.getStudyInstanceUID()); List<Series> series = study.getSeries(); for(Series oneSeries : series){ dicomCriteria.put(Tag.SeriesInstanceUID, oneSeries.getSeriesInstanceUID()); if(aimCriteria == null){ logger.debug("AD AIM criteria: " + aimCriteria); }else{ logger.debug("AD AIM retrieve criteria:"); Set<String> keys = aimCriteria.keySet(); Iterator<String> iter = keys.iterator(); while(iter.hasNext()){ String key = iter.next(); String value = (String) aimCriteria.get(key); if(!value.isEmpty()){ logger.debug("Key: " + key + " Value: " + value); } } } List<ObjectDescriptor> objectDescriptors = new ArrayList<ObjectDescriptor>(); List<Item> items = oneSeries.getItems(); for(Item item : items){ objectDescriptors.add(item.getObjectDescriptor()); } //If oneSeries contains subset of items, narrow dicomCriteria to individual SOPInstanceUIDs //Then retrieve data item by item if(oneSeries.containsSubsetOfItems()){ for(Item item : items){ String itemSOPInstanceUID = item.getItemID(); dicomCriteria.put(Tag.SOPInstanceUID, itemSOPInstanceUID); if(retrieve instanceof LocalFileSystemRetrieve){ retrieve.setCriteria(selectedDataSearchResult); } else { retrieve.setCriteria(dicomCriteria, aimCriteria); } List<ObjectDescriptor> objectDesc = new ArrayList<ObjectDescriptor>(); objectDesc.add(item.getObjectDescriptor()); retrieve.setObjectDescriptors(objectDesc); Thread t = new Thread(retrieve); t.start(); //dicomCriteria.remove(Tag.SOPInstanceUID); try { t.join(); //Reset value of SOPInstanceUID in dicomCriteria dicomCriteria.remove(Tag.SOPInstanceUID); } catch (InterruptedException e) { logger.error(e, e); } } } else { dicomCriteria.put(Tag.SOPInstanceUID, "*"); if(retrieve instanceof LocalFileSystemRetrieve){ retrieve.setCriteria(selectedDataSearchResult); } else { retrieve.setCriteria(dicomCriteria, aimCriteria); retrieve.setObjectDescriptors(objectDescriptors); } Thread t = new Thread(retrieve); t.start(); try { t.join(); } catch (InterruptedException e) { logger.error(e, e); } } //Reset Series level dicomCriteria dicomCriteria.remove(Tag.SeriesInstanceUID); } //Reset Study level dicomCriteria dicomCriteria.remove(Tag.StudyInstanceUID); } //Reset Patient level dicomCriteria dicomCriteria.remove(Tag.PatientName); dicomCriteria.remove(Tag.PatientID); } } //Wait for actual data being retrieved before sending file pointers synchronized(retrievedData){ while(retrievedData.isEmpty()){ try { retrievedData.wait(); } catch (InterruptedException e) { logger.error(e, e); } } } if(listUUIDs == null){ return new ArrayList<ObjectLocator>(); } else { for(Uuid uuid : listUUIDs){ String strUuid = uuid.getUuid(); ObjectLocator objLoc = retrievedData.get(strUuid); logger.debug(strUuid + " " + objLoc.getUri()); listObjLocs.add(objLoc); } return listObjLocs; } } @Override public void notifyException(String message) { // TODO Auto-generated method stub } @Override public void queryResultsAvailable(QueryEvent e) { // TODO Auto-generated method stub } List<String> retrievedTargetElements = new ArrayList<String>(); Map <String, ObjectLocator> retrievedData = new HashMap<String, ObjectLocator>(); @SuppressWarnings("unchecked") @Override public void retrieveResultsAvailable(RetrieveEvent e) { synchronized(retrievedData){ Map<String, ObjectLocator> objectLocators = (Map<String, ObjectLocator>) e.getSource(); retrievedData.putAll(objectLocators); Iterator<String> keySet = objectLocators.keySet().iterator(); logger.debug("Items retrieved: "); while(keySet.hasNext()){ String uuid = keySet.next(); ObjectLocator objLoc = objectLocators.get(uuid); logger.debug("UUID: " + uuid + " Item location: " + objLoc.getUri()); } retrievedData.notify(); } } }
Added addApplicationTerminationListener() and fireTerminateApplication() methods to Application class. SVN-Revision: 997
src/edu/wustl/xipHost/application/Application.java
Added addApplicationTerminationListener() and fireTerminateApplication() methods to Application class.
Java
apache-2.0
b1d2b89190c5e344e0e42248a0ff04376eea13d3
0
roikku/swift-explorer,webs86/swift-explorer,webs86/swift-explorer,roikku/swift-explorer
/* * Copyright 2014 Loic Merckel * Copyright 2012-2013 E.Hooijmeijer * * 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. */ /* * * The original version of this file (i.e., the one that is copyrighted 2012-2013 E.Hooijmeijer) * can be found here: * * https://github.com/javaswift/cloudie * package (src/main/java): org.javaswift.cloudie; * * Note: the class has been renamed from CloudiePanel * to MainPanel * * Various changes were made, such as: * - adding new menu items * - adding the tree view * - adding the proxy setting * - adding the hubiC login function * - adding simulator login function * - adding localization * - adding various options * - and many others... * */ package org.swiftexplorer.gui; import org.swiftexplorer.SwiftExplorer; import org.swiftexplorer.config.Configuration; import org.swiftexplorer.config.HasConfiguration; import org.swiftexplorer.config.localization.HasLocalizationSettings.LanguageCode; import org.swiftexplorer.config.localization.HasLocalizationSettings.RegionCode; import org.swiftexplorer.config.proxy.Proxy; import org.swiftexplorer.gui.localization.HasLocalizedStrings; import org.swiftexplorer.gui.login.CloudieCallbackWrapper; import org.swiftexplorer.gui.login.CredentialsStore; import org.swiftexplorer.gui.login.CredentialsStore.Credentials; import org.swiftexplorer.gui.login.LoginPanel; import org.swiftexplorer.gui.login.LoginPanel.LoginCallback; import org.swiftexplorer.gui.preview.PreviewPanel; import org.swiftexplorer.gui.settings.PreferencesPanel; import org.swiftexplorer.gui.settings.PreferencesPanel.PreferencesCallback; import org.swiftexplorer.gui.settings.ProxiesStore; import org.swiftexplorer.gui.settings.ProxyPanel; import org.swiftexplorer.gui.settings.ProxyPanel.ProxyCallback; import org.swiftexplorer.gui.util.AsyncWrapper; import org.swiftexplorer.gui.util.DoubleClickListener; import org.swiftexplorer.gui.util.FileTypeIconFactory; import org.swiftexplorer.gui.util.GuiTreadingUtils; import org.swiftexplorer.gui.util.LabelComponentPanel; import org.swiftexplorer.gui.util.PopupTrigger; import org.swiftexplorer.gui.util.ReflectionAction; import org.swiftexplorer.swift.SwiftAccess; import org.swiftexplorer.swift.client.factory.AccountConfigFactory; import org.swiftexplorer.swift.operations.ContainerSpecification; import org.swiftexplorer.swift.operations.SwiftOperations; import org.swiftexplorer.swift.operations.SwiftOperations.SwiftCallback; import org.swiftexplorer.swift.operations.SwiftOperationsImpl; import org.swiftexplorer.swift.util.HubicSwift; import org.swiftexplorer.swift.util.SwiftUtils; import org.swiftexplorer.util.FileUtils; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Window; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.apache.commons.io.IOUtils; import org.javaswift.joss.exception.CommandException; import org.javaswift.joss.model.Container; import org.javaswift.joss.model.StoredObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.ParameterException; /** * MainPanel. * * @author Erik Hooijmeijer * @author Loic Merckel * */ public class MainPanel extends JPanel implements SwiftOperations.SwiftCallback { private static final long serialVersionUID = 1L; final private Logger logger = LoggerFactory.getLogger(MainPanel.class); private HasConfiguration config = null ; private static final Border LR_PADDING = BorderFactory.createEmptyBorder(0, 2, 0, 2); private final DefaultListModel<Container> containers = new DefaultListModel<Container>(); private final JList<Container> containersList = new JList<Container>(containers); private final DefaultListModel<StoredObject> storedObjects = new DefaultListModel<StoredObject>(); private final JList<StoredObject> storedObjectsList = new JList<StoredObject>(storedObjects); private final List<StoredObject> allStoredObjects = Collections.synchronizedList(new ArrayList<StoredObject>()); private final JTree tree = new JTree (new Object[] {}) ; private final JTextField searchTextField = new JTextField(16); private final JButton progressButton = new JButton() ; private final JProgressBar progressBar = new JProgressBar (0, 100) ; private final JLabel progressLabel = new JLabel () ; private final JTabbedPane objectViewTabbedPane = new JTabbedPane (); @SuppressWarnings("unused") private final int treeviewTabIndex ; private final int listviewTabIndex ; private Action accountHubicLoginAction = null ; private Action accountGenericLoginAction = null ; private Action accountSimulatorLoginAction = null ; private Action accountLogoutAction = null ; private Action accountQuitAction = null ; private Action containerRefreshAction = null ; private Action containerCreateAction = null ; private Action containerDeleteAction = null ; private Action containerPurgeAction = null ; private Action containerEmptyAction = null ; private Action containerViewMetaData = null ; private Action containerGetInfoAction = null ; private Action storedObjectOpenAction = null ; private Action storedObjectPreviewAction = null ; private Action storedObjectUploadFilesAction = null ; private Action storedObjectDownloadFilesAction = null ; private Action storedObjectDeleteFilesAction = null ; private Action storedObjectDeleteDirectoryAction = null ; private Action storedObjectViewMetaData = null ; private Action storedObjectGetInfoAction = null ; private Action storedObjectUploadDirectoryAction = null ; private Action storedObjectCreateDirectoryAction = null ; private Action storedObjectDownloadDirectoryAction = null ; private Action settingProxyAction = null ; private Action settingPreferencesAction = null ; private Action aboutAction = null ; private Action jvmInfoAction = null ; private Action searchAction = null ; private Action progressButtonAction = null ; private JFrame owner; private final SwiftOperations ops; private SwiftOperations.SwiftCallback callback; private PreviewPanel previewPanel = new PreviewPanel(); private StatusPanel statusPanel; private boolean loggedIn; private final AtomicInteger busyCnt = new AtomicInteger(); private CredentialsStore credentialsStore = new CredentialsStore(); private File lastFolder = null; private final HasLocalizedStrings stringsBundle ; private final boolean nativeMacOsX = SwiftExplorer.isMacOsX() ; private final boolean createDefaultContainerInMockMode = true ; /** * creates MainPanel and immediately logs in using the given credentials. * @param login the login credentials. */ public MainPanel(List<String> login, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); ops.login(AccountConfigFactory.getKeystoneAccountConfig(), login.get(0), login.get(1), login.get(2), login.get(3), callback); } public MainPanel(SwiftAccess swiftAccess, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); ops.login(AccountConfigFactory.getHubicAccountConfig(), swiftAccess, callback); } /** * creates MainPanel and immediately logs in using the given previously stored * profile. * @param profile the profile. */ public MainPanel(String profile, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); CredentialsStore store = new CredentialsStore(); Credentials found = null; for (Credentials cr : store.getAvailableCredentials()) { if (cr.toString().equals(profile)) { found = cr; } } if (found == null) { throw new ParameterException("Unknown profile '" + profile + "'."); } else { ops.login(AccountConfigFactory.getKeystoneAccountConfig(), found.authUrl, found.tenant, found.username, String.valueOf(found.password), callback); } } /** * creates MainPanel and does not login. */ public MainPanel(HasConfiguration config, HasLocalizedStrings stringsBundle) { super(new BorderLayout()); // this.config = config ; this.stringsBundle = stringsBundle ; initMenuActions () ; // ops = createSwiftOperations(); callback = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, this); // statusPanel = new StatusPanel(ops, callback); // JScrollPane left = new JScrollPane(containersList); // tree.setEditable(false); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setShowsRootHandles(true); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // we reflect the change to storedObjectsList TreePath tps = tree.getSelectionPath() ; if (tps == null) return ; Object sel = tps.getLastPathComponent() ; if (sel == null || !(sel instanceof StoredObjectsTreeModel.TreeNode)) return ; StoredObjectsTreeModel.TreeNode node = (StoredObjectsTreeModel.TreeNode)sel; if (node.isRoot()) storedObjectsList.clearSelection(); else if (node.getStoredObject() != null) storedObjectsList.setSelectedValue(node.getStoredObject(), true); }}); tree.setCellRenderer(new DefaultTreeCellRenderer () { private static final long serialVersionUID = 1L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel lbl = (JLabel) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); lbl.setBorder(LR_PADDING); if (value == null || !(value instanceof StoredObjectsTreeModel.TreeNode)) return lbl ; StoredObject storedObject = ((StoredObjectsTreeModel.TreeNode)value).getStoredObject() ; lbl.setText(((StoredObjectsTreeModel.TreeNode)value).getNodeName()); lbl.setToolTipText(lbl.getText()); if (((StoredObjectsTreeModel.TreeNode)value).isRoot()) lbl.setIcon(getContainerIcon (((StoredObjectsTreeModel.TreeNode)value).getContainer())) ; else if (((StoredObjectsTreeModel.TreeNode)value).isVirtual()) lbl.setIcon(getVirtualDirectoryIcon ()) ; else lbl.setIcon(getContentTypeIcon (storedObject)) ; return lbl; } }); // set the pane objectViewTabbedPane.add(getLocalizedString("Tree_View"), new JScrollPane (tree)) ; objectViewTabbedPane.add(getLocalizedString("List_View"), new JScrollPane (storedObjectsList)) ; // set the index accordingly treeviewTabIndex = 0 ; listviewTabIndex = 1 ; // storedObjectsList.setMinimumSize(new Dimension(420, 320)); JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, objectViewTabbedPane, new JScrollPane(previewPanel)); center.setDividerLocation(450); // add(createToolBar (), BorderLayout.NORTH); // JSplitPane main = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, center); main.setDividerLocation(272); add(main, BorderLayout.CENTER); // add(statusPanel, BorderLayout.SOUTH); // searchTextField.setAction(searchAction); progressButton.setAction(progressButtonAction) ; progressButton.setEnabled(false); progressButton.setToolTipText(getLocalizedString("Show_Progress")); progressBar.setStringPainted(true); progressLabel.setMinimumSize(new Dimension (200, 10)) ; progressLabel.setPreferredSize(new Dimension (400, 30)) ; progressLabel.setMaximumSize(new Dimension (Integer.MAX_VALUE, Integer.MAX_VALUE)) ; // createLists(); // storedObjectsList.addMouseListener(new PopupTrigger<MainPanel>(createStoredObjectPopupMenu(), this, "enableDisableStoredObjectMenu")); storedObjectsList.addMouseListener(new DoubleClickListener(storedObjectPreviewAction)); containersList.addMouseListener(new PopupTrigger<MainPanel>(createContainerPopupMenu(), this, "enableDisableContainerMenu")); tree.addMouseListener(new PopupTrigger<MainPanel>(createStoredObjectPopupMenu(), this, "enableDisableStoredObjectMenu")); tree.addMouseListener(new DoubleClickListener(storedObjectPreviewAction)); if (nativeMacOsX) { //new MacOsMenuHandler(this); // http://www.kfu.com/~nsayer/Java/reflection.html try { Object[] args = {this}; @SuppressWarnings("rawtypes") Class[] arglist = {MainPanel.class} ; Class<?> mac_class ; mac_class = Class.forName("org.swiftexplorer.gui.MacOsMenuHandler") ; Constructor<?> new_one = mac_class.getConstructor(arglist) ; new_one.newInstance(args) ; } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { logger.error("Error occurred while creating mac os specific menu", ex); } } // bind(); // enableDisable(); } private JToolBar createToolBar () { JToolBar toolBar = new JToolBar(getLocalizedString("StoredObject")); toolBar.add(storedObjectPreviewAction).setToolTipText(getLocalizedString("Preview")); toolBar.add(storedObjectOpenAction).setToolTipText(getLocalizedString("Open_in_Browser")); toolBar.add(storedObjectViewMetaData).setToolTipText(getLocalizedString("View_Metadata")); toolBar.addSeparator(); toolBar.add(storedObjectGetInfoAction).setToolTipText(getLocalizedString("Get_Info")); toolBar.addSeparator(); toolBar.add(storedObjectUploadFilesAction).setToolTipText(getLocalizedString("Upload_Files")); toolBar.add(storedObjectDownloadFilesAction).setToolTipText(getLocalizedString("Download_Files")); toolBar.addSeparator(); toolBar.add(storedObjectCreateDirectoryAction).setToolTipText(getLocalizedString("Create_Directory")); toolBar.add(storedObjectUploadDirectoryAction).setToolTipText(getLocalizedString("Upload_Directory")); toolBar.add(storedObjectDownloadDirectoryAction).setToolTipText(getLocalizedString("Download_Directory")); toolBar.addSeparator(); toolBar.add(progressButton) ; //if (nativeMacOsX) addSearchPanel (toolBar) ; return (toolBar) ; } private void initMenuActions () { accountHubicLoginAction = new ReflectionAction<MainPanel>(getLocalizedString("hubiC_Login"), getIcon("server_connect.png"), this, "onHubicLogin"); accountGenericLoginAction = new ReflectionAction<MainPanel>(getLocalizedString("Generic_Login"), getIcon("server_connect.png"), this, "onLogin"); accountLogoutAction = new ReflectionAction<MainPanel>(getLocalizedString("Logout"), getIcon("disconnect.png"), this, "onLogout"); accountQuitAction = new ReflectionAction<MainPanel>(getLocalizedString("Quit"), getIcon("weather_rain.png"), this, "onQuit"); accountSimulatorLoginAction= new ReflectionAction<MainPanel>(getLocalizedString("Simulator_Login"), getIcon("server_connect.png"), this, "onSimulatorLogin"); containerRefreshAction = new ReflectionAction<MainPanel>(getLocalizedString("Refresh"), getIcon("arrow_refresh.png"), this, "onRefreshContainers"); containerCreateAction = new ReflectionAction<MainPanel>(getLocalizedString("Create"), getIcon("folder_add.png"), this, "onCreateContainer"); containerDeleteAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete"), getIcon("folder_delete.png"), this, "onDeleteContainer"); containerPurgeAction = new ReflectionAction<MainPanel>(getLocalizedString("Purge"), getIcon("delete.png"), this, "onPurgeContainer"); containerEmptyAction = new ReflectionAction<MainPanel>(getLocalizedString("Empty"), getIcon("bin_empty.png"), this, "onEmptyContainer"); containerViewMetaData = new ReflectionAction<MainPanel>(getLocalizedString("View_Metadata"), getIcon("page_gear.png"), this, "onViewMetaDataContainer"); containerGetInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("Get_Info"), getIcon("information.png"), this, "onGetInfoContainer"); storedObjectOpenAction = new ReflectionAction<MainPanel>(getLocalizedString("Open_in_Browser"), getIcon("application_view_icons.png"), this, "onOpenInBrowserStoredObject"); storedObjectPreviewAction = new ReflectionAction<MainPanel>(getLocalizedString("Preview"), getIcon("images.png"), this, "onPreviewStoredObject"); storedObjectUploadFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Upload_Files"), getIcon("file_upload.png"), this, "onCreateStoredObject"); storedObjectDownloadFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Download_Files"), getIcon("file_download.png"), this, "onDownloadStoredObject"); storedObjectDeleteFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete_Files"), getIcon("page_delete.png"), this, "onDeleteStoredObject"); storedObjectViewMetaData = new ReflectionAction<MainPanel>(getLocalizedString("View_Metadata"), getIcon("page_gear.png"), this, "onViewMetaDataStoredObject"); storedObjectGetInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("Get_Info"), getIcon("information.png"), this, "onGetInfoStoredObject"); storedObjectUploadDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Upload_Directory"), getIcon("folder_upload.png"), this, "onUploadDirectory"); storedObjectCreateDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Create_Directory"), getIcon("folder_add.png"), this, "onCreateDirectory"); storedObjectDownloadDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Download_Directory"), getIcon("folder_download.png"), this, "onDownloadStoredObjectDirectory"); storedObjectDeleteDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete_Directory"), getIcon("folder_delete.png"), this, "onDeleteStoredObjectDirectory"); settingProxyAction = new ReflectionAction<MainPanel>(getLocalizedString("Proxy"), getIcon("server_link.png"), this, "onProxy"); settingPreferencesAction = new ReflectionAction<MainPanel>(getLocalizedString("Preferences"), getIcon("wrench.png"), this, "onPreferences"); aboutAction = new ReflectionAction<MainPanel>(getLocalizedString("About"), getIcon("logo_16.png"), this, "onAbout"); jvmInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("JVM_Info"), getIcon("chart_bar.png"), this, "onJvmInfo"); searchAction = new ReflectionAction<MainPanel>(getLocalizedString("Search"), null, this, "onSearch"); progressButtonAction = new ReflectionAction<MainPanel>("", getIcon("progressbar.png"), this, "onProgressButton"); } private SwiftOperations createSwiftOperations() { SwiftOperationsImpl lops = new SwiftOperationsImpl(); return AsyncWrapper.async(lops); } public void setOwner(JFrame owner) { this.owner = owner; } private void createLists() { containersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); containersList.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); lbl.setBorder(LR_PADDING); Container c = (Container) value; lbl.setText(c.getName()); lbl.setToolTipText(lbl.getText()); // Add the icon lbl.setIcon(getContainerIcon (c)); return lbl; } }); containersList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { enableDisableContainerMenu(); updateStatusPanelForContainer(); } }); // storedObjectsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); storedObjectsList.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); lbl.setBorder(LR_PADDING); StoredObject so = (StoredObject) value; lbl.setText(so.getName()); lbl.setToolTipText(lbl.getText()); lbl.setIcon(getContentTypeIcon (so)) ; return lbl; } }); storedObjectsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { enableDisableStoredObjectMenu(); updateStatusPanelForStoredObject(); } }); } public static Icon getContainerIcon(Container container) { if (container == null) return MainPanel.getIcon("box.png") ; if (!container.isPublic()) return MainPanel.getIcon("box_closed.png") ; else return MainPanel.getIcon("box_open.png") ; } public static Icon getVirtualDirectoryIcon() { return MainPanel.getIcon("folder_error.png") ; } public static Icon getContentTypeIcon(StoredObject storedObject) { if (storedObject == null) return MainPanel.getIcon("folder_error.png"); ; Icon ret = null ; String contentType = storedObject.getContentType() ; if (contentType != null && !contentType.isEmpty()) { ret = FileTypeIconFactory.getFileTypeIcon(contentType, storedObject.getName()) ; } return ret ; } public void onJvmInfo () { StringBuilder sb = new StringBuilder(); boolean si = true; // Total number of processors or cores available to the JVM sb.append(getLocalizedString("Available_processors") + ": "); sb.append(Runtime.getRuntime().availableProcessors()); sb.append(System.lineSeparator()); // Total amount of free memory available to the JVM sb.append(getLocalizedString("Free_memory_available_to_the_JVM") + ": "); sb.append(FileUtils.humanReadableByteCount(Runtime.getRuntime().freeMemory(), si)); sb.append(System.lineSeparator()); // Maximum amount of memory the JVM will attempt to use long maxMemory = Runtime.getRuntime().maxMemory(); sb.append(getLocalizedString("Maximum_memory_the_JVM_will_attempt_to_use") + ": "); sb.append((maxMemory == Long.MAX_VALUE ? "no limit" : FileUtils.humanReadableByteCount(maxMemory, si))); sb.append(System.lineSeparator()); // Total memory currently in use by the JVM sb.append(getLocalizedString("Total_memory_currently_in_use_by_the_JVM") + ": "); sb.append(FileUtils.humanReadableByteCount(Runtime.getRuntime().totalMemory(), si)); sb.append(System.lineSeparator()); JOptionPane.showMessageDialog(this, sb.toString(), getLocalizedString("Information"), JOptionPane.INFORMATION_MESSAGE); } private void buildTree () { Container selectedContainer = getSelectedContainer() ; if (selectedContainer == null) return ; final List<StoredObject> storedObjectsList ; String filter = searchTextField.getText(); synchronized (allStoredObjects) { if (filter != null && !filter.isEmpty()) { storedObjectsList = new ArrayList<StoredObject> () ; for (StoredObject storedObject : allStoredObjects) { if (isFilterIncluded(storedObject)) { storedObjectsList.add(storedObject); } } } else storedObjectsList = allStoredObjects ; //StoredObjectsTreeModel nm = new StoredObjectsTreeModel (storedObjectsList) ; //nm.setRootContainer(getSelectedContainer()); StoredObjectsTreeModel nm = new StoredObjectsTreeModel (selectedContainer, storedObjectsList) ; tree.setRootVisible(!allStoredObjects.isEmpty()) ; tree.setModel(nm) ; } } private void updateTree (Collection<StoredObject> list) { TreeModel tm = tree.getModel() ; if (tm == null) return ; if (!(tm instanceof StoredObjectsTreeModel)) return ; ((StoredObjectsTreeModel)tm).addAll(list) ; tree.setRootVisible(!allStoredObjects.isEmpty()) ; //tree.updateUI() ; } public static Icon getIcon(String string) { return new ImageIcon(MainPanel.class.getResource("/icons/" + string)); } private String getLocalizedString (String key) { if (stringsBundle == null) return key.replace("_", " ") ; return stringsBundle.getLocalizedString(key) ; } public boolean isContainerSelected() { return containersList.getSelectedIndex() >= 0; } public Container getSelectedContainer() { return isContainerSelected() ? (Container) containers.get(containersList.getSelectedIndex()) : null; } public boolean isSingleStoredObjectSelected() { return storedObjectsList.getSelectedIndices().length == 1; } public boolean isStoredObjectsSelected() { return storedObjectsList.getSelectedIndices().length > 0; } public List<StoredObject> getSelectedStoredObjects() { List<StoredObject> results = new ArrayList<StoredObject>(); for (int idx : storedObjectsList.getSelectedIndices()) { results.add((StoredObject) storedObjects.get(idx)); } return results; } public <A> A single(List<A> list) { return list.isEmpty() ? null : list.get(0); } public void enableDisable() { enableDisableAccountMenu(); enableDisableContainerMenu(); enableDisableStoredObjectMenu(); } public void enableDisableAccountMenu() { accountHubicLoginAction.setEnabled(!loggedIn); accountGenericLoginAction.setEnabled(!loggedIn); accountSimulatorLoginAction.setEnabled(!loggedIn); accountLogoutAction.setEnabled(loggedIn); accountQuitAction.setEnabled(true); } public void enableDisableContainerMenu() { boolean containerSelected = isContainerSelected(); Container selected = getSelectedContainer(); boolean isBusy = busyCnt.get() > 0 ; containerRefreshAction.setEnabled(loggedIn && !isBusy); containerCreateAction.setEnabled(loggedIn && !isBusy); containerDeleteAction.setEnabled(containerSelected && !isBusy); containerPurgeAction.setEnabled(containerSelected && !isBusy); containerEmptyAction.setEnabled(containerSelected && !isBusy); containerViewMetaData.setEnabled(containerSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty()); containerGetInfoAction.setEnabled(containerSelected); } public void enableDisableStoredObjectMenu() { boolean singleObjectSelected = isSingleStoredObjectSelected(); boolean objectsSelected = isStoredObjectsSelected(); boolean containerSelected = isContainerSelected(); StoredObject selected = single(getSelectedStoredObjects()); Container selectedContainer = getSelectedContainer(); boolean isBusy = busyCnt.get() > 0 ; boolean isSelectedDir = SwiftUtils.isDirectory(selected) ; storedObjectPreviewAction.setEnabled(singleObjectSelected && selected.isInfoRetrieved()); storedObjectUploadFilesAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectDownloadFilesAction.setEnabled(containerSelected && objectsSelected && !isBusy && !isSelectedDir); storedObjectViewMetaData.setEnabled(containerSelected && singleObjectSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty()); storedObjectOpenAction.setEnabled(objectsSelected && containerSelected && selectedContainer.isPublic() && !isBusy); storedObjectDeleteFilesAction.setEnabled(containerSelected && objectsSelected && !isBusy && !isSelectedDir); storedObjectUploadDirectoryAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectGetInfoAction.setEnabled(containerSelected && objectsSelected); storedObjectCreateDirectoryAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectDownloadDirectoryAction.setEnabled(containerSelected && singleObjectSelected && !isBusy && isSelectedDir); storedObjectDeleteDirectoryAction.setEnabled(containerSelected && singleObjectSelected && !isBusy && isSelectedDir); } protected void updateStatusPanelForStoredObject() { if (isStoredObjectsSelected()) { statusPanel.onSelectStoredObjects(getSelectedStoredObjects()); } } protected void updateStatusPanelForContainer() { if (isContainerSelected()) { statusPanel.onSelectContainer(getSelectedContainer()); } } @Override public void onNumberOfCalls(int nrOfCalls) { statusPanel.onNumberOfCalls(nrOfCalls); } public void onHubicLogin() { accountHubicLoginAction.setEnabled(false); accountGenericLoginAction.setEnabled(false); accountSimulatorLoginAction.setEnabled(false); new SwingWorker<SwiftAccess, Object>() { @Override protected SwiftAccess doInBackground() throws Exception { return HubicSwift.getSwiftAccess() ; } @Override protected void done() { SwiftAccess sa = null ; try { sa = get(); } catch (InterruptedException | ExecutionException e) { logger.error("Error occurred while authentifying.", e); } accountHubicLoginAction.setEnabled(true); accountGenericLoginAction.setEnabled(true); accountSimulatorLoginAction.setEnabled(false); if (sa == null) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n", getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } else { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe( SwiftCallback.class, new CloudieCallbackWrapper( callback) { @Override public void onLoginSuccess() { super.onLoginSuccess(); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); ops.login(AccountConfigFactory.getHubicAccountConfig(), sa, cb); } enableDisable(); if (owner != null) owner.toFront(); } }.execute(); } public void onLogin() { final JDialog loginDialog = new JDialog(owner, getLocalizedString("Login")); final LoginPanel loginPanel = new LoginPanel(new LoginCallback() { @Override public void doLogin(String authUrl, String tenant, String username, char[] pass) { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, new CloudieCallbackWrapper(callback) { @Override public void onLoginSuccess() { loginDialog.setVisible(false); super.onLoginSuccess(); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(loginDialog, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); ops.login(AccountConfigFactory.getKeystoneAccountConfig(), authUrl, tenant, username, new String(pass), cb); } }, credentialsStore, stringsBundle); try { loginPanel.setOwner(loginDialog); loginDialog.getContentPane().add(loginPanel); loginDialog.setModal(true); loginDialog.setSize(480, 280); loginDialog.setResizable(false); loginDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); center(loginDialog); loginDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { loginPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { loginPanel.onShow(); } }); loginDialog.setVisible(true); } finally { loginDialog.dispose(); } } public void onSimulatorLogin() { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, new CloudieCallbackWrapper(callback) { @Override public void onLoginSuccess() { super.onLoginSuccess(); if (createDefaultContainerInMockMode) ops.createContainer(new ContainerSpecification("default", true), callback); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); if (confirm (getLocalizedString("confirm_connection_to_simulator"))) ops.login(AccountConfigFactory.getMockAccountConfig(), "http://localhost:8080/", "user", "pass", "secret", cb); } private void center(JDialog dialog) { int x = owner.getLocation().x + (owner.getWidth() - dialog.getWidth()) / 2; int y = owner.getLocation().y + (owner.getHeight() - dialog.getHeight()) / 2; dialog.setLocation(x, y); } @Override public void onLoginSuccess() { this.onNewStoredObjects(); ops.refreshContainers(callback); loggedIn = true; enableDisable(); } public void onAbout() { StringBuilder sb = loadResource("/about.html"); JLabel label = new JLabel(sb.toString()); String msg = MessageFormat.format (getLocalizedString("About_dlg_title"), " " + Configuration.INSTANCE.getAppName()) ; JOptionPane.showMessageDialog(this, label, msg, JOptionPane.INFORMATION_MESSAGE, getIcon("logo.png")); } private StringBuilder loadResource(String resource) { StringBuilder sb = new StringBuilder(); InputStream input = MainPanel.class.getResourceAsStream(resource); try { try { List<String> lines = IOUtils.readLines(input); for (String line : lines) { sb.append(line); } } finally { input.close(); } } catch (IOException ex) { logger.error("Error occurred while loading resources.", ex); throw new RuntimeException(ex); } return sb; } public void onLogout() { ops.logout(callback); } @Override public void onLogoutSuccess() { this.onUpdateContainers(Collections.<Container> emptyList()); this.onNewStoredObjects(); statusPanel.onDeselect(); loggedIn = false; enableDisable(); } public void onQuit() { if (onClose()) { System.exit(0); } } public void onPreferences () { final JDialog prefDialog = new JDialog(owner, getLocalizedString("Preferences")); final PreferencesPanel prefPanel = new PreferencesPanel(new PreferencesCallback() { @Override public void setLanguage(LanguageCode lang, RegionCode reg) { // set the new language setting if (config != null) { config.updateLanguage(lang, reg); info (getLocalizedString("info_new_setting_effective_next_start")) ; } prefDialog.setVisible(false); } }, config, stringsBundle); try { prefPanel.setOwner(prefDialog); prefDialog.getContentPane().add(prefPanel); prefDialog.setModal(true); //prefDialog.setSize(300, 150); prefDialog.setResizable(false); prefDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); prefDialog.pack(); center(prefDialog); prefDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { prefPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { prefPanel.onShow(); } }); prefDialog.setVisible(true); } finally { prefDialog.dispose(); } } public void onProxy() { final ProxiesStore proxiesStore = new ProxiesStore (config) ; final JDialog proxyDialog = new JDialog(owner, getLocalizedString("Proxy_Setting")); final ProxyPanel proxyPanel = new ProxyPanel(new ProxyCallback() { @Override public void setProxy(Set<Proxy> newProxies) { if (config == null) return ; if (newProxies == null || newProxies.isEmpty()) return ; for (Proxy proxy : newProxies) config.updateProxy(proxy) ; proxyDialog.setVisible(false); } }, proxiesStore, stringsBundle); try { proxyPanel.setOwner(proxyDialog); proxyDialog.getContentPane().add(proxyPanel); proxyDialog.setModal(true); proxyDialog.setSize(600, 210); proxyDialog.setResizable(false); proxyDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); center(proxyDialog); proxyDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { proxyPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { proxyPanel.onShow(); } }); proxyDialog.setVisible(true); } finally { proxyDialog.dispose(); } } private JPopupMenu createContainerPopupMenu() { JPopupMenu pop = new JPopupMenu("Container"); pop.add(new JMenuItem(containerRefreshAction)); pop.add(new JMenuItem(containerViewMetaData)); pop.addSeparator(); pop.add(new JMenuItem(containerCreateAction)); pop.add(new JMenuItem(containerDeleteAction)); pop.addSeparator(); pop.add(new JMenuItem(containerEmptyAction)); pop.addSeparator(); pop.add(new JMenuItem(containerPurgeAction)); return pop; } protected void onPurgeContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_purging_container"), c.getName()) ; if (confirm(msg)) { ops.purgeContainer(c, callback); } } protected void onEmptyContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_empty_container"), c.getName()) ; if (confirm(msg)) { ops.emptyContainer(c, callback); } } protected void onRefreshContainers() { int idx = containersList.getSelectedIndex(); refreshContainers(); containersList.setSelectedIndex(idx); } protected void onDeleteContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_delete_container"), c.getName()) ; if (confirm(msg)) { ops.deleteContainer(c, callback); } } protected void onCreateContainer() { ContainerSpecification spec = doGetContainerSpec(); ops.createContainer(spec, callback); } private ContainerSpecification doGetContainerSpec() { JTextField nameTf = new JTextField(); JCheckBox priv = new JCheckBox(getLocalizedString("private_container")); while (true) { if (JOptionPane.showConfirmDialog(this, new Object[] { getLocalizedString("Name"), nameTf, priv }, getLocalizedString("Create_Container"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { String name = nameTf.getText() ; if (name == null || name.trim().isEmpty()) { JOptionPane.showMessageDialog(this, getLocalizedString("please_enter_non_empty_directory_name")); continue ; } return new ContainerSpecification(name.trim(), priv.isSelected()); } break ; } return null; } /** * @return */ private JPopupMenu createStoredObjectPopupMenu() { JPopupMenu pop = new JPopupMenu(getLocalizedString("StoredObject")); pop.add(new JMenuItem(storedObjectPreviewAction)); pop.add(new JMenuItem(storedObjectOpenAction)); pop.add(new JMenuItem(storedObjectViewMetaData)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectGetInfoAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectUploadFilesAction)); pop.add(new JMenuItem(storedObjectDownloadFilesAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectCreateDirectoryAction)) ; pop.add(new JMenuItem(storedObjectUploadDirectoryAction)); pop.add(new JMenuItem(storedObjectDownloadDirectoryAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectDeleteFilesAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectDeleteDirectoryAction)); return pop; } public JMenuBar createMenuBar() { JMenuBar bar = new JMenuBar(); JMenu accountMenu = new JMenu(getLocalizedString("Account")); JMenu containerMenu = new JMenu(getLocalizedString("Container")); JMenu storedObjectMenu = new JMenu(getLocalizedString("StoredObject")); JMenu settingsMenu = new JMenu(getLocalizedString("Settings")); JMenu helpMenu = new JMenu(getLocalizedString("Help")); accountMenu.setMnemonic('A'); containerMenu.setMnemonic('C'); storedObjectMenu.setMnemonic('O'); helpMenu.setMnemonic('H'); bar.add(accountMenu); bar.add(containerMenu); bar.add(storedObjectMenu); bar.add(settingsMenu); bar.add(helpMenu); //if (!nativeMacOsX) // addSearchPanel (bar) ; // accountMenu.add(new JMenuItem(accountHubicLoginAction)); accountMenu.add(new JMenuItem(accountGenericLoginAction)); accountMenu.add(new JMenuItem(accountSimulatorLoginAction)); accountMenu.addSeparator(); accountMenu.add(new JMenuItem(accountLogoutAction)); if (!nativeMacOsX) { accountMenu.addSeparator(); accountMenu.add(new JMenuItem(accountQuitAction)); } // containerMenu.add(new JMenuItem(containerRefreshAction)); containerMenu.add(new JMenuItem(containerViewMetaData)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerGetInfoAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerCreateAction)); containerMenu.add(new JMenuItem(containerDeleteAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerEmptyAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerPurgeAction)); // storedObjectMenu.add(new JMenuItem(storedObjectPreviewAction)); storedObjectMenu.add(new JMenuItem(storedObjectOpenAction)); storedObjectMenu.add(new JMenuItem(storedObjectViewMetaData)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectGetInfoAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectUploadFilesAction)); storedObjectMenu.add(new JMenuItem(storedObjectDownloadFilesAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectCreateDirectoryAction)) ; storedObjectMenu.add(new JMenuItem(storedObjectUploadDirectoryAction)); storedObjectMenu.add(new JMenuItem(storedObjectDownloadDirectoryAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectDeleteFilesAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectDeleteDirectoryAction)); // settingsMenu.add(new JMenuItem(settingProxyAction)) ; if (!nativeMacOsX) { settingsMenu.addSeparator(); settingsMenu.add(new JMenuItem(settingPreferencesAction)) ; } // helpMenu.add(new JMenuItem(jvmInfoAction)); if (!nativeMacOsX) { helpMenu.addSeparator(); helpMenu.add(new JMenuItem(aboutAction)); } // return bar; } private void addSearchPanel (JComponent parent) { JPanel panel = new JPanel(new FlowLayout(SwingConstants.RIGHT, 0, 0)); JLabel label = new JLabel(getIcon("zoom.png")); label.setLabelFor(searchTextField); label.setDisplayedMnemonic('f'); panel.add(label); panel.add(searchTextField); parent.add(panel); } protected void onOpenInBrowserStoredObject() { Container container = getSelectedContainer(); List<StoredObject> objects = getSelectedStoredObjects(); if (container.isPublic()) { for (StoredObject obj : objects) { String publicURL = obj.getPublicURL(); if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI(publicURL)); } catch (Exception e) { logger.error("Error occurred while opening the browser.", e); } } } } } protected void onPreviewStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); if (obj.getContentLength() < 16 * 1024 * 1024) { previewPanel.preview(obj.getContentType(), obj.downloadObject()); } } protected void onViewMetaDataStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); Map<String, Object> metadata = obj.getMetadata(); List<LabelComponentPanel> panels = buildMetaDataPanels(metadata); JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE); } private List<LabelComponentPanel> buildMetaDataPanels(Map<String, Object> metadata) { List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); for (Map.Entry<String, Object> entry : metadata.entrySet()) { JLabel comp = new JLabel(String.valueOf(entry.getValue())); comp.setFont(comp.getFont().deriveFont(Font.PLAIN)); panels.add(new LabelComponentPanel(entry.getKey(), comp)); } return panels; } protected void onViewMetaDataContainer() { Container obj = getSelectedContainer(); Map<String, Object> metadata = obj.getMetadata(); List<LabelComponentPanel> panels = buildMetaDataPanels(metadata); JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE); } protected void onDownloadStoredObjectDirectory() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() != 1) return ; // should never happen, because in such a case the menu is disable StoredObject obj = sltObj.get(0) ; if (!SwiftUtils.isDirectory(obj)) return ; // should never happen, because in such a case the menu is disable Container container = getSelectedContainer(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(lastFolder); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File selectedDest = chooser.getSelectedFile(); File target = new File(selectedDest, obj.getName()); if (target.exists()) { String msg = MessageFormat.format (getLocalizedString("confirm_file_already_exists_overwite"), target.getName()) ; if (!confirm(msg)) return ; } doSaveStoredObject(selectedDest, container, obj); onProgressButton() ; lastFolder = selectedDest; } } protected void onDownloadStoredObject() { Container container = getSelectedContainer(); List<StoredObject> obj = getSelectedStoredObjects(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(lastFolder); if (obj.size() == 1) { chooser.setSelectedFile(new File(obj.get(0).getName())); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); } else { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File selected = chooser.getSelectedFile(); for (StoredObject so : obj) { // We skip the directories if (SwiftUtils.isDirectory(so)) continue ; File target = selected; if (target.isDirectory()) { target = new File(selected, so.getName()); } if (target.exists()) { String msg = MessageFormat.format (getLocalizedString("confirm_file_already_exists_overwite"), target.getName()) ; if (confirm(msg)) { doSaveStoredObject(target, container, so); } } else { doSaveStoredObject(target, container, so); } } lastFolder = selected.isFile() ? selected.getParentFile() : selected; } } private void doSaveStoredObject(File target, Container container, StoredObject obj) { try { ops.downloadStoredObject(container, obj, target, callback); } catch (IOException e) { logger.error(String.format("Error occurred while downloading the objects '%s'", obj.getName()), e); } } protected void onDeleteStoredObjectDirectory () { Container container = getSelectedContainer(); List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() != 1) return ; // should never happen, because in such a case the menu is disable StoredObject obj = sltObj.get(0) ; if (!SwiftUtils.isDirectory(obj)) return ; // should never happen, because in such a case the menu is disable doDeleteObjectDirectory(container, obj) ; onProgressButton() ; } protected void doDeleteObjectDirectory(Container container, StoredObject obj) { String msg = MessageFormat.format (getLocalizedString("confirm_one_directory_delete_from_container"), obj.getName(), container.getName()) ; if (confirm(msg)) { ops.deleteDirectory(container, obj, callback) ; } } protected void onDeleteStoredObject() { Container container = getSelectedContainer(); List<StoredObject> objects = getSelectedStoredObjects(); if (objects.size() == 1) { doDeleteSingleObject(container, single(objects)); } else { doDeleteMultipleObjects(container, objects); } } protected void doDeleteSingleObject(Container container, StoredObject obj) { String msg = MessageFormat.format (getLocalizedString("confirm_one_file_delete_from_container"), obj.getName(), container.getName()) ; if (confirm(msg)) { ops.deleteStoredObjects(container, Collections.singletonList(obj), callback); } } protected void doDeleteMultipleObjects(Container container, List<StoredObject> obj) { String msg = MessageFormat.format (getLocalizedString("confirm_many_files_delete_from_container"), String.valueOf(obj.size()), container.getName()) ; if (confirm(msg)) { ops.deleteStoredObjects(container, obj, callback); } } protected void onCreateStoredObject() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; Container container = getSelectedContainer(); JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); chooser.setCurrentDirectory(lastFolder); final JPanel optionPanel = getOptionPanel (); chooser.setAccessory(optionPanel); AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ; if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File[] selectedFiles = chooser.getSelectedFiles(); try { boolean overwriteAll = overwriteCheck.isSelected() ; if (overwriteAll) { if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files"))) return ; } ops.uploadFiles(container, parentObject, selectedFiles, overwriteAll, callback); // We open the progress window, for it is likely that this operation // will take a while if (selectedFiles != null && selectedFiles.length > 1) { onProgressButton () ; } } catch (IOException e) { logger.error("Error occurred while uploading a files.", e); } lastFolder = chooser.getCurrentDirectory(); } } private LabelComponentPanel buildLabelComponentPanel (String str, Object obj) { JLabel comp = new JLabel(String.valueOf(obj)); comp.setFont(comp.getFont().deriveFont(Font.PLAIN)); return new LabelComponentPanel(str, comp); } protected void onGetInfoContainer() { Container obj = getSelectedContainer(); List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); panels.add(buildLabelComponentPanel("Container name", obj.getName())); panels.add(buildLabelComponentPanel("Bytes used", FileUtils.humanReadableByteCount(obj.getBytesUsed(), true))); panels.add(buildLabelComponentPanel("Object count", obj.getCount())); panels.add(buildLabelComponentPanel("Path", obj.getPath())); panels.add(buildLabelComponentPanel("Max page size", obj.getMaxPageSize())); panels.add(buildLabelComponentPanel("Is Public?", ((obj.isPublic())?("Yes"):("No")))); //TODO: more info // ... JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " Info", JOptionPane.INFORMATION_MESSAGE); } protected void onGetInfoStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); panels.add(buildLabelComponentPanel("Object name", obj.getName())); panels.add(buildLabelComponentPanel("Object path", obj.getPath())); panels.add(buildLabelComponentPanel("Content type", obj.getContentType())); panels.add(buildLabelComponentPanel("Content length", FileUtils.humanReadableByteCount(obj.getContentLength(), true))); panels.add(buildLabelComponentPanel("E-tag", obj.getEtag())); panels.add(buildLabelComponentPanel("Last modified", obj.getLastModified())); //TODO: more info // ... JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " Info", JOptionPane.INFORMATION_MESSAGE); } protected void onCreateDirectory() { Container container = getSelectedContainer(); if (container == null) return ; List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; JTextField directoryName = new JTextField(); while (true) { if (JOptionPane.showConfirmDialog(this, new Object[] { getLocalizedString("Directory_Name"), directoryName}, getLocalizedString("Create_Directory"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { String name = directoryName.getText() ; if (name == null || name.trim().isEmpty()) { JOptionPane.showMessageDialog(this, getLocalizedString("please_enter_non_empty_directory_name")); continue ; } else ops.createDirectory(container, parentObject, name.trim(), callback); } break ; } } private AbstractButton setOverwriteOption (JPanel optionPanel) { if (optionPanel == null) return null ; final JCheckBox overwriteCheck = new JCheckBox(getLocalizedString("Overwrite_existing_files")); overwriteCheck.addItemListener(new ItemListener (){ @Override public void itemStateChanged(ItemEvent e) { if (overwriteCheck.isSelected()) { overwriteCheck.setOpaque(true); overwriteCheck.setBackground(Color.RED); } else overwriteCheck.setOpaque(false); }}) ; optionPanel.add(overwriteCheck); return overwriteCheck ; } private JPanel getOptionPanel () { final JPanel optionPanel = new JPanel(); optionPanel.setBorder(BorderFactory.createTitledBorder(getLocalizedString("Options"))); return optionPanel ; } protected void onUploadDirectory() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; final Container container = getSelectedContainer(); final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setCurrentDirectory(lastFolder); chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY); final JPanel optionPanel = getOptionPanel (); chooser.setAccessory(optionPanel); AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ; if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { final File selectedDir = chooser.getSelectedFile(); try { boolean overwriteAll = overwriteCheck.isSelected() ; if (overwriteAll) { if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files"))) return ; } ops.uploadDirectory(container, parentObject, selectedDir, overwriteAll, callback); // We open the progress window, for it is likely that this operation // will take a while onProgressButton () ; } catch (IOException e) { logger.error("Error occurred while uploading a directory.", e); } lastFolder = chooser.getCurrentDirectory(); } } public void bind() { containersList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } else { int idx = containersList.getSelectedIndex(); if (idx >= 0) { refreshFiles((Container) containers.get(idx)); } } } }); // Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable ex) { if (ex instanceof CommandException) { showError((CommandException) ex); } else { ex.printStackTrace(); } } }); // containersList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); containersList.getActionMap().put("refresh", containerRefreshAction); // storedObjectsList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); storedObjectsList.getActionMap().put("refresh", containerRefreshAction); // } public void refreshContainers() { containers.clear(); storedObjects.clear(); ops.refreshContainers(callback); } public void refreshFiles(Container selected) { storedObjects.clear(); ops.refreshStoredObjects(selected, callback); } public void onProgressButton () { if (progressBar.isShowing()) return ; final int border = 15 ; Box box = Box.createVerticalBox() ; box.setBorder(BorderFactory.createEmptyBorder(border, border, border, border)); box.add (progressLabel) ; box.add (progressBar) ; JDialog dlg = new JDialog (owner) ; dlg.setContentPane(box); dlg.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); dlg.setSize(200, 100) ; dlg.pack(); center (dlg) ; dlg.setVisible(true); } public void onSearch() { storedObjects.clear(); synchronized (allStoredObjects) { for (StoredObject storedObject : allStoredObjects) { if (isFilterIncluded(storedObject)) { storedObjects.addElement(storedObject); } } } //set the tablist if (allStoredObjects.size() != storedObjects.size()) objectViewTabbedPane.setSelectedIndex(listviewTabIndex); buildTree () ; } private boolean isFilterIncluded(StoredObject obj) { String filter = searchTextField.getText(); if (filter.isEmpty()) { return true; } else { return obj.getName().contains(filter); } } // // Callback // /** * {@inheritDoc}. */ @Override public void onStart() { if (busyCnt.getAndIncrement() == 0) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); statusPanel.onStart(); progressButton.setEnabled(true); progressBar.setValue(0); progressLabel.setText("Processing"); progressBar.setIndeterminate(true) ; enableDisable(); } } /** * {@inheritDoc}. */ @Override public void onDone() { if (busyCnt.decrementAndGet() == 0) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); statusPanel.onEnd(); progressButton.setEnabled(false); progressBar.setValue(100); Window progressWindow = SwingUtilities.getWindowAncestor(progressBar); if (progressWindow != null) progressWindow.setVisible(false) ; } enableDisable(); } /** * {@inheritDoc}. */ @Override public void onError(final CommandException ex) { showError(ex); } /** * {@inheritDoc}. */ @Override public void onUpdateContainers(final Collection<Container> cs) { containers.clear(); for (Container container : cs) { containers.addElement(container); } statusPanel.onDeselectContainer(); } /** * {@inheritDoc}. */ @Override public void onStoredObjectDeleted(final Container container, final StoredObject storedObject) { if (isContainerSelected() && getSelectedContainer().equals(container)) { int idx = storedObjects.indexOf(storedObject); if (idx >= 0) { storedObjectsList.getSelectionModel().removeIndexInterval(idx, idx); } storedObjects.removeElement(storedObject); allStoredObjects.remove(storedObject); buildTree () ; } } /** * {@inheritDoc}. */ @Override public void onNewStoredObjects() { searchTextField.setText(""); storedObjects.clear(); allStoredObjects.clear(); statusPanel.onDeselectStoredObject(); buildTree () ; } /** * {@inheritDoc}. */ @Override public void onAppendStoredObjects(final Container container, int page, final Collection<StoredObject> sos) { if (isContainerSelected() && getSelectedContainer().equals(container)) { allStoredObjects.addAll(sos); for (StoredObject storedObject : sos) { if (isFilterIncluded(storedObject)) { storedObjects.addElement(storedObject); } } updateTree (sos) ; // TODO: seems to be necessary to avoid freezing for huge amount of objects // Must be checked // ... System.gc() ; } } /** * {@inheritDoc}. */ @Override public void onProgress(final double p, final String msg) { int currValue = (int) (p * 100) ; if (progressBar.isIndeterminate()) progressBar.setIndeterminate(false) ; progressBar.setValue(currValue); progressLabel.setText(msg); if (progressBar.getValue() == progressBar.getMaximum()) progressBar.setIndeterminate(true) ; } /** * {@inheritDoc}. */ @Override public void onContainerUpdate(final Container container) { statusPanel.onSelectContainer(container); } /** * {@inheritDoc}. */ @Override public void onStoredObjectUpdate(final StoredObject obj) { statusPanel.onSelectStoredObjects(Collections.singletonList(obj)); } // // // /** * @return true if the window can close. */ public boolean onClose() { return (loggedIn && confirm(getLocalizedString("confirm_quit_application"))) || (!loggedIn); } public boolean confirm(String message) { return JOptionPane.showConfirmDialog(this, message, getLocalizedString("Confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION; } public void info(String message) { JOptionPane.showMessageDialog(this, message) ; } protected void showError(CommandException ex) { JOptionPane.showMessageDialog(this, ex.toString(), getLocalizedString("Error"), JOptionPane.OK_OPTION); } }
src/main/java/org/swiftexplorer/gui/MainPanel.java
/* * Copyright 2014 Loic Merckel * Copyright 2012-2013 E.Hooijmeijer * * 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. */ /* * * The original version of this file (i.e., the one that is copyrighted 2012-2013 E.Hooijmeijer) * can be found here: * * https://github.com/javaswift/cloudie * package (src/main/java): org.javaswift.cloudie; * * Note: the class has been renamed from CloudiePanel * to MainPanel * * Various changes were made, such as: * - adding new menu items * - adding the tree view * - adding the proxy setting * - adding the hubiC login function * - adding simulator login function * - adding localization * - adding various options * - and many others... * */ package org.swiftexplorer.gui; import org.swiftexplorer.SwiftExplorer; import org.swiftexplorer.config.Configuration; import org.swiftexplorer.config.HasConfiguration; import org.swiftexplorer.config.localization.HasLocalizationSettings.LanguageCode; import org.swiftexplorer.config.localization.HasLocalizationSettings.RegionCode; import org.swiftexplorer.config.proxy.Proxy; import org.swiftexplorer.gui.localization.HasLocalizedStrings; import org.swiftexplorer.gui.login.CloudieCallbackWrapper; import org.swiftexplorer.gui.login.CredentialsStore; import org.swiftexplorer.gui.login.CredentialsStore.Credentials; import org.swiftexplorer.gui.login.LoginPanel; import org.swiftexplorer.gui.login.LoginPanel.LoginCallback; import org.swiftexplorer.gui.preview.PreviewPanel; import org.swiftexplorer.gui.settings.PreferencesPanel; import org.swiftexplorer.gui.settings.PreferencesPanel.PreferencesCallback; import org.swiftexplorer.gui.settings.ProxiesStore; import org.swiftexplorer.gui.settings.ProxyPanel; import org.swiftexplorer.gui.settings.ProxyPanel.ProxyCallback; import org.swiftexplorer.gui.util.AsyncWrapper; import org.swiftexplorer.gui.util.DoubleClickListener; import org.swiftexplorer.gui.util.FileTypeIconFactory; import org.swiftexplorer.gui.util.GuiTreadingUtils; import org.swiftexplorer.gui.util.LabelComponentPanel; import org.swiftexplorer.gui.util.PopupTrigger; import org.swiftexplorer.gui.util.ReflectionAction; import org.swiftexplorer.swift.SwiftAccess; import org.swiftexplorer.swift.client.factory.AccountConfigFactory; import org.swiftexplorer.swift.operations.ContainerSpecification; import org.swiftexplorer.swift.operations.SwiftOperations; import org.swiftexplorer.swift.operations.SwiftOperations.SwiftCallback; import org.swiftexplorer.swift.operations.SwiftOperationsImpl; import org.swiftexplorer.swift.util.HubicSwift; import org.swiftexplorer.swift.util.SwiftUtils; import org.swiftexplorer.util.FileUtils; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Window; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.net.URI; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.DefaultListCellRenderer; import javax.swing.DefaultListModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import org.apache.commons.io.IOUtils; import org.javaswift.joss.exception.CommandException; import org.javaswift.joss.model.Container; import org.javaswift.joss.model.StoredObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.ParameterException; /** * MainPanel. * * @author Erik Hooijmeijer * @author Loic Merckel * */ public class MainPanel extends JPanel implements SwiftOperations.SwiftCallback { private static final long serialVersionUID = 1L; final private Logger logger = LoggerFactory.getLogger(MainPanel.class); private HasConfiguration config = null ; private static final Border LR_PADDING = BorderFactory.createEmptyBorder(0, 2, 0, 2); private final DefaultListModel<Container> containers = new DefaultListModel<Container>(); private final JList<Container> containersList = new JList<Container>(containers); private final DefaultListModel<StoredObject> storedObjects = new DefaultListModel<StoredObject>(); private final JList<StoredObject> storedObjectsList = new JList<StoredObject>(storedObjects); private final List<StoredObject> allStoredObjects = Collections.synchronizedList(new ArrayList<StoredObject>()); private final JTree tree = new JTree (new Object[] {}) ; private final JTextField searchTextField = new JTextField(16); private final JButton progressButton = new JButton() ; private final JProgressBar progressBar = new JProgressBar (0, 100) ; private final JLabel progressLabel = new JLabel () ; private final JTabbedPane objectViewTabbedPane = new JTabbedPane (); @SuppressWarnings("unused") private final int treeviewTabIndex ; private final int listviewTabIndex ; private Action accountHubicLoginAction = null ; private Action accountGenericLoginAction = null ; private Action accountSimulatorLoginAction = null ; private Action accountLogoutAction = null ; private Action accountQuitAction = null ; private Action containerRefreshAction = null ; private Action containerCreateAction = null ; private Action containerDeleteAction = null ; private Action containerPurgeAction = null ; private Action containerEmptyAction = null ; private Action containerViewMetaData = null ; private Action containerGetInfoAction = null ; private Action storedObjectOpenAction = null ; private Action storedObjectPreviewAction = null ; private Action storedObjectUploadFilesAction = null ; private Action storedObjectDownloadFilesAction = null ; private Action storedObjectDeleteFilesAction = null ; private Action storedObjectDeleteDirectoryAction = null ; private Action storedObjectViewMetaData = null ; private Action storedObjectGetInfoAction = null ; private Action storedObjectUploadDirectoryAction = null ; private Action storedObjectCreateDirectoryAction = null ; private Action storedObjectDownloadDirectoryAction = null ; private Action settingProxyAction = null ; private Action settingPreferencesAction = null ; private Action aboutAction = null ; private Action jvmInfoAction = null ; private Action searchAction = null ; private Action progressButtonAction = null ; private JFrame owner; private final SwiftOperations ops; private SwiftOperations.SwiftCallback callback; private PreviewPanel previewPanel = new PreviewPanel(); private StatusPanel statusPanel; private boolean loggedIn; private final AtomicInteger busyCnt = new AtomicInteger(); private CredentialsStore credentialsStore = new CredentialsStore(); private File lastFolder = null; private final HasLocalizedStrings stringsBundle ; private final boolean nativeMacOsX = SwiftExplorer.isMacOsX() ; private final boolean createDefaultContainerInMockMode = true ; /** * creates MainPanel and immediately logs in using the given credentials. * @param login the login credentials. */ public MainPanel(List<String> login, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); ops.login(AccountConfigFactory.getKeystoneAccountConfig(), login.get(0), login.get(1), login.get(2), login.get(3), callback); } public MainPanel(SwiftAccess swiftAccess, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); ops.login(AccountConfigFactory.getHubicAccountConfig(), swiftAccess, callback); } /** * creates MainPanel and immediately logs in using the given previously stored * profile. * @param profile the profile. */ public MainPanel(String profile, HasConfiguration config, HasLocalizedStrings stringsBundle) { this(config, stringsBundle); CredentialsStore store = new CredentialsStore(); Credentials found = null; for (Credentials cr : store.getAvailableCredentials()) { if (cr.toString().equals(profile)) { found = cr; } } if (found == null) { throw new ParameterException("Unknown profile '" + profile + "'."); } else { ops.login(AccountConfigFactory.getKeystoneAccountConfig(), found.authUrl, found.tenant, found.username, String.valueOf(found.password), callback); } } /** * creates MainPanel and does not login. */ public MainPanel(HasConfiguration config, HasLocalizedStrings stringsBundle) { super(new BorderLayout()); // this.config = config ; this.stringsBundle = stringsBundle ; initMenuActions () ; // ops = createSwiftOperations(); callback = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, this); // statusPanel = new StatusPanel(ops, callback); // JScrollPane left = new JScrollPane(containersList); // tree.setEditable(false); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.setShowsRootHandles(true); tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // we reflect the change to storedObjectsList TreePath tps = tree.getSelectionPath() ; if (tps == null) return ; Object sel = tps.getLastPathComponent() ; if (sel == null || !(sel instanceof StoredObjectsTreeModel.TreeNode)) return ; StoredObjectsTreeModel.TreeNode node = (StoredObjectsTreeModel.TreeNode)sel; if (node.isRoot()) storedObjectsList.clearSelection(); else if (node.getStoredObject() != null) storedObjectsList.setSelectedValue(node.getStoredObject(), true); }}); tree.setCellRenderer(new DefaultTreeCellRenderer () { private static final long serialVersionUID = 1L; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel lbl = (JLabel) super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); lbl.setBorder(LR_PADDING); if (value == null || !(value instanceof StoredObjectsTreeModel.TreeNode)) return lbl ; StoredObject storedObject = ((StoredObjectsTreeModel.TreeNode)value).getStoredObject() ; lbl.setText(((StoredObjectsTreeModel.TreeNode)value).getNodeName()); lbl.setToolTipText(lbl.getText()); if (((StoredObjectsTreeModel.TreeNode)value).isRoot()) lbl.setIcon(getContainerIcon (((StoredObjectsTreeModel.TreeNode)value).getContainer())) ; else if (((StoredObjectsTreeModel.TreeNode)value).isVirtual()) lbl.setIcon(getVirtualDirectoryIcon ()) ; else lbl.setIcon(getContentTypeIcon (storedObject)) ; return lbl; } }); // set the pane objectViewTabbedPane.add(getLocalizedString("Tree_View"), new JScrollPane (tree)) ; objectViewTabbedPane.add(getLocalizedString("List_View"), new JScrollPane (storedObjectsList)) ; // set the index accordingly treeviewTabIndex = 0 ; listviewTabIndex = 1 ; // storedObjectsList.setMinimumSize(new Dimension(420, 320)); JSplitPane center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, objectViewTabbedPane, new JScrollPane(previewPanel)); center.setDividerLocation(450); // add(createToolBar (), BorderLayout.NORTH); // JSplitPane main = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, center); main.setDividerLocation(272); add(main, BorderLayout.CENTER); // add(statusPanel, BorderLayout.SOUTH); // searchTextField.setAction(searchAction); progressButton.setAction(progressButtonAction) ; progressButton.setEnabled(false); progressButton.setToolTipText(getLocalizedString("Show_Progress")); progressBar.setStringPainted(true); progressLabel.setMinimumSize(new Dimension (200, 10)) ; progressLabel.setPreferredSize(new Dimension (400, 30)) ; progressLabel.setMaximumSize(new Dimension (Integer.MAX_VALUE, Integer.MAX_VALUE)) ; // createLists(); // storedObjectsList.addMouseListener(new PopupTrigger<MainPanel>(createStoredObjectPopupMenu(), this, "enableDisableStoredObjectMenu")); storedObjectsList.addMouseListener(new DoubleClickListener(storedObjectPreviewAction)); containersList.addMouseListener(new PopupTrigger<MainPanel>(createContainerPopupMenu(), this, "enableDisableContainerMenu")); tree.addMouseListener(new PopupTrigger<MainPanel>(createStoredObjectPopupMenu(), this, "enableDisableStoredObjectMenu")); tree.addMouseListener(new DoubleClickListener(storedObjectPreviewAction)); if (nativeMacOsX) { //new MacOsMenuHandler(this); // http://www.kfu.com/~nsayer/Java/reflection.html try { Object[] args = {this}; @SuppressWarnings("rawtypes") Class[] arglist = {MainPanel.class} ; Class<?> mac_class ; mac_class = Class.forName("org.swiftexplorer.gui.MacOsMenuHandler") ; Constructor<?> new_one = mac_class.getConstructor(arglist) ; new_one.newInstance(args) ; } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { logger.error("Error occurred while creating mac os specific menu", ex); } } // bind(); // enableDisable(); } private JToolBar createToolBar () { JToolBar toolBar = new JToolBar(getLocalizedString("StoredObject")); toolBar.add(storedObjectPreviewAction).setToolTipText(getLocalizedString("Preview")); toolBar.add(storedObjectOpenAction).setToolTipText(getLocalizedString("Open_in_Browser")); toolBar.add(storedObjectViewMetaData).setToolTipText(getLocalizedString("View_Metadata")); toolBar.addSeparator(); toolBar.add(storedObjectGetInfoAction).setToolTipText(getLocalizedString("Get_Info")); toolBar.addSeparator(); toolBar.add(storedObjectUploadFilesAction).setToolTipText(getLocalizedString("Upload_Files")); toolBar.add(storedObjectDownloadFilesAction).setToolTipText(getLocalizedString("Download_Files")); toolBar.addSeparator(); toolBar.add(storedObjectCreateDirectoryAction).setToolTipText(getLocalizedString("Create_Directory")); toolBar.add(storedObjectUploadDirectoryAction).setToolTipText(getLocalizedString("Upload_Directory")); toolBar.add(storedObjectDownloadDirectoryAction).setToolTipText(getLocalizedString("Download_Directory")); toolBar.addSeparator(); toolBar.add(progressButton) ; //if (nativeMacOsX) addSearchPanel (toolBar) ; return (toolBar) ; } private void initMenuActions () { accountHubicLoginAction = new ReflectionAction<MainPanel>(getLocalizedString("hubiC_Login"), getIcon("server_connect.png"), this, "onHubicLogin"); accountGenericLoginAction = new ReflectionAction<MainPanel>(getLocalizedString("Generic_Login"), getIcon("server_connect.png"), this, "onLogin"); accountLogoutAction = new ReflectionAction<MainPanel>(getLocalizedString("Logout"), getIcon("disconnect.png"), this, "onLogout"); accountQuitAction = new ReflectionAction<MainPanel>(getLocalizedString("Quit"), getIcon("weather_rain.png"), this, "onQuit"); accountSimulatorLoginAction= new ReflectionAction<MainPanel>(getLocalizedString("Simulator_Login"), getIcon("server_connect.png"), this, "onSimulatorLogin"); containerRefreshAction = new ReflectionAction<MainPanel>(getLocalizedString("Refresh"), getIcon("arrow_refresh.png"), this, "onRefreshContainers"); containerCreateAction = new ReflectionAction<MainPanel>(getLocalizedString("Create"), getIcon("folder_add.png"), this, "onCreateContainer"); containerDeleteAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete"), getIcon("folder_delete.png"), this, "onDeleteContainer"); containerPurgeAction = new ReflectionAction<MainPanel>(getLocalizedString("Purge"), getIcon("delete.png"), this, "onPurgeContainer"); containerEmptyAction = new ReflectionAction<MainPanel>(getLocalizedString("Empty"), getIcon("bin_empty.png"), this, "onEmptyContainer"); containerViewMetaData = new ReflectionAction<MainPanel>(getLocalizedString("View_Metadata"), getIcon("page_gear.png"), this, "onViewMetaDataContainer"); containerGetInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("Get_Info"), getIcon("information.png"), this, "onGetInfoContainer"); storedObjectOpenAction = new ReflectionAction<MainPanel>(getLocalizedString("Open_in_Browser"), getIcon("application_view_icons.png"), this, "onOpenInBrowserStoredObject"); storedObjectPreviewAction = new ReflectionAction<MainPanel>(getLocalizedString("Preview"), getIcon("images.png"), this, "onPreviewStoredObject"); storedObjectUploadFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Upload_Files"), getIcon("file_upload.png"), this, "onCreateStoredObject"); storedObjectDownloadFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Download_Files"), getIcon("file_download.png"), this, "onDownloadStoredObject"); storedObjectDeleteFilesAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete_Files"), getIcon("page_delete.png"), this, "onDeleteStoredObject"); storedObjectViewMetaData = new ReflectionAction<MainPanel>(getLocalizedString("View_Metadata"), getIcon("page_gear.png"), this, "onViewMetaDataStoredObject"); storedObjectGetInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("Get_Info"), getIcon("information.png"), this, "onGetInfoStoredObject"); storedObjectUploadDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Upload_Directory"), getIcon("folder_upload.png"), this, "onUploadDirectory"); storedObjectCreateDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Create_Directory"), getIcon("folder_add.png"), this, "onCreateDirectory"); storedObjectDownloadDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Download_Directory"), getIcon("folder_download.png"), this, "onDownloadStoredObjectDirectory"); storedObjectDeleteDirectoryAction = new ReflectionAction<MainPanel>(getLocalizedString("Delete_Directory"), getIcon("folder_delete.png"), this, "onDeleteStoredObjectDirectory"); settingProxyAction = new ReflectionAction<MainPanel>(getLocalizedString("Proxy"), getIcon("server_link.png"), this, "onProxy"); settingPreferencesAction = new ReflectionAction<MainPanel>(getLocalizedString("Preferences"), getIcon("wrench.png"), this, "onPreferences"); aboutAction = new ReflectionAction<MainPanel>(getLocalizedString("About"), getIcon("logo_16.png"), this, "onAbout"); jvmInfoAction = new ReflectionAction<MainPanel>(getLocalizedString("JVM_Info"), getIcon("chart_bar.png"), this, "onJvmInfo"); searchAction = new ReflectionAction<MainPanel>(getLocalizedString("Search"), null, this, "onSearch"); progressButtonAction = new ReflectionAction<MainPanel>("", getIcon("progressbar.png"), this, "onProgressButton"); } private SwiftOperations createSwiftOperations() { SwiftOperationsImpl lops = new SwiftOperationsImpl(); return AsyncWrapper.async(lops); } public void setOwner(JFrame owner) { this.owner = owner; } private void createLists() { containersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); containersList.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); lbl.setBorder(LR_PADDING); Container c = (Container) value; lbl.setText(c.getName()); lbl.setToolTipText(lbl.getText()); // Add the icon lbl.setIcon(getContainerIcon (c)); return lbl; } }); containersList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { enableDisableContainerMenu(); updateStatusPanelForContainer(); } }); // storedObjectsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); storedObjectsList.setCellRenderer(new DefaultListCellRenderer() { private static final long serialVersionUID = 1L; @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel lbl = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); lbl.setBorder(LR_PADDING); StoredObject so = (StoredObject) value; lbl.setText(so.getName()); lbl.setToolTipText(lbl.getText()); lbl.setIcon(getContentTypeIcon (so)) ; return lbl; } }); storedObjectsList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { enableDisableStoredObjectMenu(); updateStatusPanelForStoredObject(); } }); } public static Icon getContainerIcon(Container container) { if (container == null) return MainPanel.getIcon("box.png") ; if (!container.isPublic()) return MainPanel.getIcon("box_closed.png") ; else return MainPanel.getIcon("box_open.png") ; } public static Icon getVirtualDirectoryIcon() { return MainPanel.getIcon("folder_error.png") ; } public static Icon getContentTypeIcon(StoredObject storedObject) { if (storedObject == null) return MainPanel.getIcon("folder_error.png"); ; Icon ret = null ; String contentType = storedObject.getContentType() ; if (contentType != null && !contentType.isEmpty()) { ret = FileTypeIconFactory.getFileTypeIcon(contentType, storedObject.getName()) ; } return ret ; } public void onJvmInfo () { StringBuilder sb = new StringBuilder(); boolean si = true; // Total number of processors or cores available to the JVM sb.append(getLocalizedString("Available_processors") + ": "); sb.append(Runtime.getRuntime().availableProcessors()); sb.append(System.lineSeparator()); // Total amount of free memory available to the JVM sb.append(getLocalizedString("Free_memory_available_to_the_JVM") + ": "); sb.append(FileUtils.humanReadableByteCount(Runtime.getRuntime().freeMemory(), si)); sb.append(System.lineSeparator()); // Maximum amount of memory the JVM will attempt to use long maxMemory = Runtime.getRuntime().maxMemory(); sb.append(getLocalizedString("Maximum_memory_the_JVM_will_attempt_to_use") + ": "); sb.append((maxMemory == Long.MAX_VALUE ? "no limit" : FileUtils.humanReadableByteCount(maxMemory, si))); sb.append(System.lineSeparator()); // Total memory currently in use by the JVM sb.append(getLocalizedString("Total_memory_currently_in_use_by_the_JVM") + ": "); sb.append(FileUtils.humanReadableByteCount(Runtime.getRuntime().totalMemory(), si)); sb.append(System.lineSeparator()); JOptionPane.showMessageDialog(this, sb.toString(), getLocalizedString("Information"), JOptionPane.INFORMATION_MESSAGE); } private void buildTree () { Container selectedContainer = getSelectedContainer() ; if (selectedContainer == null) return ; final List<StoredObject> storedObjectsList ; String filter = searchTextField.getText(); synchronized (allStoredObjects) { if (filter != null && !filter.isEmpty()) { storedObjectsList = new ArrayList<StoredObject> () ; for (StoredObject storedObject : allStoredObjects) { if (isFilterIncluded(storedObject)) { storedObjectsList.add(storedObject); } } } else storedObjectsList = allStoredObjects ; //StoredObjectsTreeModel nm = new StoredObjectsTreeModel (storedObjectsList) ; //nm.setRootContainer(getSelectedContainer()); StoredObjectsTreeModel nm = new StoredObjectsTreeModel (selectedContainer, storedObjectsList) ; tree.setRootVisible(!allStoredObjects.isEmpty()) ; tree.setModel(nm) ; } } private void updateTree (Collection<StoredObject> list) { TreeModel tm = tree.getModel() ; if (tm == null) return ; if (!(tm instanceof StoredObjectsTreeModel)) return ; ((StoredObjectsTreeModel)tm).addAll(list) ; tree.setRootVisible(!allStoredObjects.isEmpty()) ; //tree.updateUI() ; } public static Icon getIcon(String string) { return new ImageIcon(MainPanel.class.getResource("/icons/" + string)); } private String getLocalizedString (String key) { if (stringsBundle == null) return key.replace("_", " ") ; return stringsBundle.getLocalizedString(key) ; } public boolean isContainerSelected() { return containersList.getSelectedIndex() >= 0; } public Container getSelectedContainer() { return isContainerSelected() ? (Container) containers.get(containersList.getSelectedIndex()) : null; } public boolean isSingleStoredObjectSelected() { return storedObjectsList.getSelectedIndices().length == 1; } public boolean isStoredObjectsSelected() { return storedObjectsList.getSelectedIndices().length > 0; } public List<StoredObject> getSelectedStoredObjects() { List<StoredObject> results = new ArrayList<StoredObject>(); for (int idx : storedObjectsList.getSelectedIndices()) { results.add((StoredObject) storedObjects.get(idx)); } return results; } public <A> A single(List<A> list) { return list.isEmpty() ? null : list.get(0); } public void enableDisable() { enableDisableAccountMenu(); enableDisableContainerMenu(); enableDisableStoredObjectMenu(); } public void enableDisableAccountMenu() { accountHubicLoginAction.setEnabled(!loggedIn); accountGenericLoginAction.setEnabled(!loggedIn); accountSimulatorLoginAction.setEnabled(!loggedIn); accountLogoutAction.setEnabled(loggedIn); accountQuitAction.setEnabled(true); } public void enableDisableContainerMenu() { boolean containerSelected = isContainerSelected(); Container selected = getSelectedContainer(); boolean isBusy = busyCnt.get() > 0 ; containerRefreshAction.setEnabled(loggedIn && !isBusy); containerCreateAction.setEnabled(loggedIn && !isBusy); containerDeleteAction.setEnabled(containerSelected && !isBusy); containerPurgeAction.setEnabled(containerSelected && !isBusy); containerEmptyAction.setEnabled(containerSelected && !isBusy); containerViewMetaData.setEnabled(containerSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty()); containerGetInfoAction.setEnabled(containerSelected); } public void enableDisableStoredObjectMenu() { boolean singleObjectSelected = isSingleStoredObjectSelected(); boolean objectsSelected = isStoredObjectsSelected(); boolean containerSelected = isContainerSelected(); StoredObject selected = single(getSelectedStoredObjects()); Container selectedContainer = getSelectedContainer(); boolean isBusy = busyCnt.get() > 0 ; boolean isSelectedDir = SwiftUtils.isDirectory(selected) ; storedObjectPreviewAction.setEnabled(singleObjectSelected && selected.isInfoRetrieved()); storedObjectUploadFilesAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectDownloadFilesAction.setEnabled(containerSelected && objectsSelected && !isBusy && !isSelectedDir); storedObjectViewMetaData.setEnabled(containerSelected && singleObjectSelected && selected.isInfoRetrieved() && !selected.getMetadata().isEmpty()); storedObjectOpenAction.setEnabled(objectsSelected && containerSelected && selectedContainer.isPublic() && !isBusy); storedObjectDeleteFilesAction.setEnabled(containerSelected && objectsSelected && !isBusy && !isSelectedDir); storedObjectUploadDirectoryAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectGetInfoAction.setEnabled(containerSelected && objectsSelected); storedObjectCreateDirectoryAction.setEnabled(containerSelected && (singleObjectSelected || !objectsSelected) && !isBusy); storedObjectDownloadDirectoryAction.setEnabled(containerSelected && singleObjectSelected && !isBusy && isSelectedDir); storedObjectDeleteDirectoryAction.setEnabled(containerSelected && singleObjectSelected && !isBusy && isSelectedDir); } protected void updateStatusPanelForStoredObject() { if (isStoredObjectsSelected()) { statusPanel.onSelectStoredObjects(getSelectedStoredObjects()); } } protected void updateStatusPanelForContainer() { if (isContainerSelected()) { statusPanel.onSelectContainer(getSelectedContainer()); } } @Override public void onNumberOfCalls(int nrOfCalls) { statusPanel.onNumberOfCalls(nrOfCalls); } public void onHubicLogin() { accountHubicLoginAction.setEnabled(false); accountGenericLoginAction.setEnabled(false); accountSimulatorLoginAction.setEnabled(false); new SwingWorker<SwiftAccess, Object>() { @Override protected SwiftAccess doInBackground() throws Exception { return HubicSwift.getSwiftAccess() ; } @Override protected void done() { SwiftAccess sa = null ; try { sa = get(); } catch (InterruptedException | ExecutionException e) { logger.error("Error occurred while authentifying.", e); } accountHubicLoginAction.setEnabled(true); accountGenericLoginAction.setEnabled(true); accountSimulatorLoginAction.setEnabled(false); if (sa == null) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n", getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } else { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe( SwiftCallback.class, new CloudieCallbackWrapper( callback) { @Override public void onLoginSuccess() { super.onLoginSuccess(); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); ops.login(AccountConfigFactory.getHubicAccountConfig(), sa, cb); } enableDisable(); if (owner != null) owner.toFront(); } }.execute(); } public void onLogin() { final JDialog loginDialog = new JDialog(owner, getLocalizedString("Login")); final LoginPanel loginPanel = new LoginPanel(new LoginCallback() { @Override public void doLogin(String authUrl, String tenant, String username, char[] pass) { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, new CloudieCallbackWrapper(callback) { @Override public void onLoginSuccess() { loginDialog.setVisible(false); super.onLoginSuccess(); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(loginDialog, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); ops.login(AccountConfigFactory.getKeystoneAccountConfig(), authUrl, tenant, username, new String(pass), cb); } }, credentialsStore, stringsBundle); try { loginPanel.setOwner(loginDialog); loginDialog.getContentPane().add(loginPanel); loginDialog.setModal(true); loginDialog.setSize(480, 280); loginDialog.setResizable(false); loginDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); center(loginDialog); loginDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { loginPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { loginPanel.onShow(); } }); loginDialog.setVisible(true); } finally { loginDialog.dispose(); } } public void onSimulatorLogin() { SwiftCallback cb = GuiTreadingUtils.guiThreadSafe(SwiftCallback.class, new CloudieCallbackWrapper(callback) { @Override public void onLoginSuccess() { super.onLoginSuccess(); if (createDefaultContainerInMockMode) ops.createContainer(new ContainerSpecification("default", true), callback); } @Override public void onError(CommandException ex) { JOptionPane.showMessageDialog(null, getLocalizedString("Login_Failed") + "\n" + ex.toString(), getLocalizedString("Error"), JOptionPane.ERROR_MESSAGE); } }); if (confirm (getLocalizedString("confirm_connection_to_simulator"))) ops.login(AccountConfigFactory.getMockAccountConfig(), "http://localhost:8080/", "user", "pass", "secret", cb); } private void center(JDialog dialog) { int x = owner.getLocation().x + (owner.getWidth() - dialog.getWidth()) / 2; int y = owner.getLocation().y + (owner.getHeight() - dialog.getHeight()) / 2; dialog.setLocation(x, y); } @Override public void onLoginSuccess() { this.onNewStoredObjects(); ops.refreshContainers(callback); loggedIn = true; enableDisable(); } public void onAbout() { StringBuilder sb = loadResource("/about.html"); JLabel label = new JLabel(sb.toString()); String msg = MessageFormat.format (getLocalizedString("About_dlg_title"), " " + Configuration.INSTANCE.getAppName()) ; JOptionPane.showMessageDialog(this, label, msg, JOptionPane.INFORMATION_MESSAGE, getIcon("logo.png")); } private StringBuilder loadResource(String resource) { StringBuilder sb = new StringBuilder(); InputStream input = MainPanel.class.getResourceAsStream(resource); try { try { List<String> lines = IOUtils.readLines(input); for (String line : lines) { sb.append(line); } } finally { input.close(); } } catch (IOException ex) { logger.error("Error occurred while loading resources.", ex); throw new RuntimeException(ex); } return sb; } public void onLogout() { ops.logout(callback); } @Override public void onLogoutSuccess() { this.onUpdateContainers(Collections.<Container> emptyList()); this.onNewStoredObjects(); statusPanel.onDeselect(); loggedIn = false; enableDisable(); } public void onQuit() { if (onClose()) { System.exit(0); } } public void onPreferences () { final JDialog prefDialog = new JDialog(owner, getLocalizedString("Preferences")); final PreferencesPanel prefPanel = new PreferencesPanel(new PreferencesCallback() { @Override public void setLanguage(LanguageCode lang, RegionCode reg) { // set the new language setting if (config != null) { config.updateLanguage(lang, reg); info (getLocalizedString("info_new_setting_effective_next_start")) ; } prefDialog.setVisible(false); } }, config, stringsBundle); try { prefPanel.setOwner(prefDialog); prefDialog.getContentPane().add(prefPanel); prefDialog.setModal(true); //prefDialog.setSize(300, 150); prefDialog.setResizable(false); prefDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); prefDialog.pack(); center(prefDialog); prefDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { prefPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { prefPanel.onShow(); } }); prefDialog.setVisible(true); } finally { prefDialog.dispose(); } } public void onProxy() { final ProxiesStore proxiesStore = new ProxiesStore (config) ; final JDialog proxyDialog = new JDialog(owner, getLocalizedString("Proxy_Setting")); final ProxyPanel proxyPanel = new ProxyPanel(new ProxyCallback() { @Override public void setProxy(Set<Proxy> newProxies) { if (config == null) return ; if (newProxies == null || newProxies.isEmpty()) return ; for (Proxy proxy : newProxies) config.updateProxy(proxy) ; proxyDialog.setVisible(false); } }, proxiesStore, stringsBundle); try { proxyPanel.setOwner(proxyDialog); proxyDialog.getContentPane().add(proxyPanel); proxyDialog.setModal(true); proxyDialog.setSize(600, 210); proxyDialog.setResizable(false); proxyDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); center(proxyDialog); proxyDialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { proxyPanel.onCancel(); } @Override public void windowOpened(WindowEvent e) { proxyPanel.onShow(); } }); proxyDialog.setVisible(true); } finally { proxyDialog.dispose(); } } private JPopupMenu createContainerPopupMenu() { JPopupMenu pop = new JPopupMenu("Container"); pop.add(new JMenuItem(containerRefreshAction)); pop.add(new JMenuItem(containerViewMetaData)); pop.addSeparator(); pop.add(new JMenuItem(containerCreateAction)); pop.add(new JMenuItem(containerDeleteAction)); pop.addSeparator(); pop.add(new JMenuItem(containerEmptyAction)); pop.addSeparator(); pop.add(new JMenuItem(containerPurgeAction)); return pop; } protected void onPurgeContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_purging_container"), c.getName()) ; if (confirm(msg)) { ops.purgeContainer(c, callback); } } protected void onEmptyContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_empty_container"), c.getName()) ; if (confirm(msg)) { ops.emptyContainer(c, callback); } } protected void onRefreshContainers() { int idx = containersList.getSelectedIndex(); refreshContainers(); containersList.setSelectedIndex(idx); } protected void onDeleteContainer() { Container c = getSelectedContainer(); String msg = MessageFormat.format (getLocalizedString("confirm_msg_delete_container"), c.getName()) ; if (confirm(msg)) { ops.deleteContainer(c, callback); } } protected void onCreateContainer() { ContainerSpecification spec = doGetContainerSpec(); ops.createContainer(spec, callback); } private ContainerSpecification doGetContainerSpec() { JTextField nameTf = new JTextField(); JCheckBox priv = new JCheckBox(getLocalizedString("private_container")); while (true) { if (JOptionPane.showConfirmDialog(this, new Object[] { getLocalizedString("Name"), nameTf, priv }, getLocalizedString("Create_Container"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { String name = nameTf.getText() ; if (name == null || name.isEmpty()) { JOptionPane.showMessageDialog(this, getLocalizedString("please_enter_non_empty_directory_name")); continue ; } return new ContainerSpecification(name, priv.isSelected()); } break ; } return null; } /** * @return */ private JPopupMenu createStoredObjectPopupMenu() { JPopupMenu pop = new JPopupMenu(getLocalizedString("StoredObject")); pop.add(new JMenuItem(storedObjectPreviewAction)); pop.add(new JMenuItem(storedObjectOpenAction)); pop.add(new JMenuItem(storedObjectViewMetaData)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectGetInfoAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectUploadFilesAction)); pop.add(new JMenuItem(storedObjectDownloadFilesAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectCreateDirectoryAction)) ; pop.add(new JMenuItem(storedObjectUploadDirectoryAction)); pop.add(new JMenuItem(storedObjectDownloadDirectoryAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectDeleteFilesAction)); pop.addSeparator(); pop.add(new JMenuItem(storedObjectDeleteDirectoryAction)); return pop; } public JMenuBar createMenuBar() { JMenuBar bar = new JMenuBar(); JMenu accountMenu = new JMenu(getLocalizedString("Account")); JMenu containerMenu = new JMenu(getLocalizedString("Container")); JMenu storedObjectMenu = new JMenu(getLocalizedString("StoredObject")); JMenu settingsMenu = new JMenu(getLocalizedString("Settings")); JMenu helpMenu = new JMenu(getLocalizedString("Help")); accountMenu.setMnemonic('A'); containerMenu.setMnemonic('C'); storedObjectMenu.setMnemonic('O'); helpMenu.setMnemonic('H'); bar.add(accountMenu); bar.add(containerMenu); bar.add(storedObjectMenu); bar.add(settingsMenu); bar.add(helpMenu); //if (!nativeMacOsX) // addSearchPanel (bar) ; // accountMenu.add(new JMenuItem(accountHubicLoginAction)); accountMenu.add(new JMenuItem(accountGenericLoginAction)); accountMenu.add(new JMenuItem(accountSimulatorLoginAction)); accountMenu.addSeparator(); accountMenu.add(new JMenuItem(accountLogoutAction)); if (!nativeMacOsX) { accountMenu.addSeparator(); accountMenu.add(new JMenuItem(accountQuitAction)); } // containerMenu.add(new JMenuItem(containerRefreshAction)); containerMenu.add(new JMenuItem(containerViewMetaData)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerGetInfoAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerCreateAction)); containerMenu.add(new JMenuItem(containerDeleteAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerEmptyAction)); containerMenu.addSeparator(); containerMenu.add(new JMenuItem(containerPurgeAction)); // storedObjectMenu.add(new JMenuItem(storedObjectPreviewAction)); storedObjectMenu.add(new JMenuItem(storedObjectOpenAction)); storedObjectMenu.add(new JMenuItem(storedObjectViewMetaData)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectGetInfoAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectUploadFilesAction)); storedObjectMenu.add(new JMenuItem(storedObjectDownloadFilesAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectCreateDirectoryAction)) ; storedObjectMenu.add(new JMenuItem(storedObjectUploadDirectoryAction)); storedObjectMenu.add(new JMenuItem(storedObjectDownloadDirectoryAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectDeleteFilesAction)); storedObjectMenu.addSeparator(); storedObjectMenu.add(new JMenuItem(storedObjectDeleteDirectoryAction)); // settingsMenu.add(new JMenuItem(settingProxyAction)) ; if (!nativeMacOsX) { settingsMenu.addSeparator(); settingsMenu.add(new JMenuItem(settingPreferencesAction)) ; } // helpMenu.add(new JMenuItem(jvmInfoAction)); if (!nativeMacOsX) { helpMenu.addSeparator(); helpMenu.add(new JMenuItem(aboutAction)); } // return bar; } private void addSearchPanel (JComponent parent) { JPanel panel = new JPanel(new FlowLayout(SwingConstants.RIGHT, 0, 0)); JLabel label = new JLabel(getIcon("zoom.png")); label.setLabelFor(searchTextField); label.setDisplayedMnemonic('f'); panel.add(label); panel.add(searchTextField); parent.add(panel); } protected void onOpenInBrowserStoredObject() { Container container = getSelectedContainer(); List<StoredObject> objects = getSelectedStoredObjects(); if (container.isPublic()) { for (StoredObject obj : objects) { String publicURL = obj.getPublicURL(); if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI(publicURL)); } catch (Exception e) { logger.error("Error occurred while opening the browser.", e); } } } } } protected void onPreviewStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); if (obj.getContentLength() < 16 * 1024 * 1024) { previewPanel.preview(obj.getContentType(), obj.downloadObject()); } } protected void onViewMetaDataStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); Map<String, Object> metadata = obj.getMetadata(); List<LabelComponentPanel> panels = buildMetaDataPanels(metadata); JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE); } private List<LabelComponentPanel> buildMetaDataPanels(Map<String, Object> metadata) { List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); for (Map.Entry<String, Object> entry : metadata.entrySet()) { JLabel comp = new JLabel(String.valueOf(entry.getValue())); comp.setFont(comp.getFont().deriveFont(Font.PLAIN)); panels.add(new LabelComponentPanel(entry.getKey(), comp)); } return panels; } protected void onViewMetaDataContainer() { Container obj = getSelectedContainer(); Map<String, Object> metadata = obj.getMetadata(); List<LabelComponentPanel> panels = buildMetaDataPanels(metadata); JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " metadata.", JOptionPane.INFORMATION_MESSAGE); } protected void onDownloadStoredObjectDirectory() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() != 1) return ; // should never happen, because in such a case the menu is disable StoredObject obj = sltObj.get(0) ; if (!SwiftUtils.isDirectory(obj)) return ; // should never happen, because in such a case the menu is disable Container container = getSelectedContainer(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(lastFolder); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File selectedDest = chooser.getSelectedFile(); File target = new File(selectedDest, obj.getName()); if (target.exists()) { String msg = MessageFormat.format (getLocalizedString("confirm_file_already_exists_overwite"), target.getName()) ; if (!confirm(msg)) return ; } doSaveStoredObject(selectedDest, container, obj); onProgressButton() ; lastFolder = selectedDest; } } protected void onDownloadStoredObject() { Container container = getSelectedContainer(); List<StoredObject> obj = getSelectedStoredObjects(); JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(lastFolder); if (obj.size() == 1) { chooser.setSelectedFile(new File(obj.get(0).getName())); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); } else { chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); } if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { File selected = chooser.getSelectedFile(); for (StoredObject so : obj) { // We skip the directories if (SwiftUtils.isDirectory(so)) continue ; File target = selected; if (target.isDirectory()) { target = new File(selected, so.getName()); } if (target.exists()) { String msg = MessageFormat.format (getLocalizedString("confirm_file_already_exists_overwite"), target.getName()) ; if (confirm(msg)) { doSaveStoredObject(target, container, so); } } else { doSaveStoredObject(target, container, so); } } lastFolder = selected.isFile() ? selected.getParentFile() : selected; } } private void doSaveStoredObject(File target, Container container, StoredObject obj) { try { ops.downloadStoredObject(container, obj, target, callback); } catch (IOException e) { logger.error(String.format("Error occurred while downloading the objects '%s'", obj.getName()), e); } } protected void onDeleteStoredObjectDirectory () { Container container = getSelectedContainer(); List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() != 1) return ; // should never happen, because in such a case the menu is disable StoredObject obj = sltObj.get(0) ; if (!SwiftUtils.isDirectory(obj)) return ; // should never happen, because in such a case the menu is disable doDeleteObjectDirectory(container, obj) ; onProgressButton() ; } protected void doDeleteObjectDirectory(Container container, StoredObject obj) { String msg = MessageFormat.format (getLocalizedString("confirm_one_directory_delete_from_container"), obj.getName(), container.getName()) ; if (confirm(msg)) { ops.deleteDirectory(container, obj, callback) ; } } protected void onDeleteStoredObject() { Container container = getSelectedContainer(); List<StoredObject> objects = getSelectedStoredObjects(); if (objects.size() == 1) { doDeleteSingleObject(container, single(objects)); } else { doDeleteMultipleObjects(container, objects); } } protected void doDeleteSingleObject(Container container, StoredObject obj) { String msg = MessageFormat.format (getLocalizedString("confirm_one_file_delete_from_container"), obj.getName(), container.getName()) ; if (confirm(msg)) { ops.deleteStoredObjects(container, Collections.singletonList(obj), callback); } } protected void doDeleteMultipleObjects(Container container, List<StoredObject> obj) { String msg = MessageFormat.format (getLocalizedString("confirm_many_files_delete_from_container"), String.valueOf(obj.size()), container.getName()) ; if (confirm(msg)) { ops.deleteStoredObjects(container, obj, callback); } } protected void onCreateStoredObject() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; Container container = getSelectedContainer(); JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); chooser.setCurrentDirectory(lastFolder); final JPanel optionPanel = getOptionPanel (); chooser.setAccessory(optionPanel); AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ; if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { File[] selectedFiles = chooser.getSelectedFiles(); try { boolean overwriteAll = overwriteCheck.isSelected() ; if (overwriteAll) { if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files"))) return ; } ops.uploadFiles(container, parentObject, selectedFiles, overwriteAll, callback); // We open the progress window, for it is likely that this operation // will take a while if (selectedFiles != null && selectedFiles.length > 1) { onProgressButton () ; } } catch (IOException e) { logger.error("Error occurred while uploading a files.", e); } lastFolder = chooser.getCurrentDirectory(); } } private LabelComponentPanel buildLabelComponentPanel (String str, Object obj) { JLabel comp = new JLabel(String.valueOf(obj)); comp.setFont(comp.getFont().deriveFont(Font.PLAIN)); return new LabelComponentPanel(str, comp); } protected void onGetInfoContainer() { Container obj = getSelectedContainer(); List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); panels.add(buildLabelComponentPanel("Container name", obj.getName())); panels.add(buildLabelComponentPanel("Bytes used", FileUtils.humanReadableByteCount(obj.getBytesUsed(), true))); panels.add(buildLabelComponentPanel("Object count", obj.getCount())); panels.add(buildLabelComponentPanel("Path", obj.getPath())); panels.add(buildLabelComponentPanel("Max page size", obj.getMaxPageSize())); panels.add(buildLabelComponentPanel("Is Public?", ((obj.isPublic())?("Yes"):("No")))); //TODO: more info // ... JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " Info", JOptionPane.INFORMATION_MESSAGE); } protected void onGetInfoStoredObject() { StoredObject obj = single(getSelectedStoredObjects()); List<LabelComponentPanel> panels = new ArrayList<LabelComponentPanel>(); panels.add(buildLabelComponentPanel("Object name", obj.getName())); panels.add(buildLabelComponentPanel("Object path", obj.getPath())); panels.add(buildLabelComponentPanel("Content type", obj.getContentType())); panels.add(buildLabelComponentPanel("Content length", FileUtils.humanReadableByteCount(obj.getContentLength(), true))); panels.add(buildLabelComponentPanel("E-tag", obj.getEtag())); panels.add(buildLabelComponentPanel("Last modified", obj.getLastModified())); //TODO: more info // ... JOptionPane.showMessageDialog(this, panels.toArray(), obj.getName() + " Info", JOptionPane.INFORMATION_MESSAGE); } protected void onCreateDirectory() { Container container = getSelectedContainer(); if (container == null) return ; List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; JTextField directoryName = new JTextField(); while (true) { if (JOptionPane.showConfirmDialog(this, new Object[] { getLocalizedString("Directory_Name"), directoryName}, getLocalizedString("Create_Directory"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { String name = directoryName.getText() ; if (name == null || name.isEmpty()) { JOptionPane.showMessageDialog(this, getLocalizedString("please_enter_non_empty_directory_name")); continue ; } else ops.createDirectory(container, parentObject, name, callback); } break ; } } private AbstractButton setOverwriteOption (JPanel optionPanel) { if (optionPanel == null) return null ; final JCheckBox overwriteCheck = new JCheckBox(getLocalizedString("Overwrite_existing_files")); overwriteCheck.addItemListener(new ItemListener (){ @Override public void itemStateChanged(ItemEvent e) { if (overwriteCheck.isSelected()) { overwriteCheck.setOpaque(true); overwriteCheck.setBackground(Color.RED); } else overwriteCheck.setOpaque(false); }}) ; optionPanel.add(overwriteCheck); return overwriteCheck ; } private JPanel getOptionPanel () { final JPanel optionPanel = new JPanel(); optionPanel.setBorder(BorderFactory.createTitledBorder(getLocalizedString("Options"))); return optionPanel ; } protected void onUploadDirectory() { List<StoredObject> sltObj = getSelectedStoredObjects() ; if (sltObj != null && sltObj.size() > 1) return ; // should never happen, because in such a case the menu is disable StoredObject parentObject = (sltObj == null || sltObj.isEmpty()) ? (null) : (sltObj.get(0)) ; final Container container = getSelectedContainer(); final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setCurrentDirectory(lastFolder); chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY); final JPanel optionPanel = getOptionPanel (); chooser.setAccessory(optionPanel); AbstractButton overwriteCheck = setOverwriteOption (optionPanel) ; if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { final File selectedDir = chooser.getSelectedFile(); try { boolean overwriteAll = overwriteCheck.isSelected() ; if (overwriteAll) { if (!confirm(getLocalizedString("confirm_overwrite_any_existing_files"))) return ; } ops.uploadDirectory(container, parentObject, selectedDir, overwriteAll, callback); // We open the progress window, for it is likely that this operation // will take a while onProgressButton () ; } catch (IOException e) { logger.error("Error occurred while uploading a directory.", e); } lastFolder = chooser.getCurrentDirectory(); } } public void bind() { containersList.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } else { int idx = containersList.getSelectedIndex(); if (idx >= 0) { refreshFiles((Container) containers.get(idx)); } } } }); // Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable ex) { if (ex instanceof CommandException) { showError((CommandException) ex); } else { ex.printStackTrace(); } } }); // containersList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); containersList.getActionMap().put("refresh", containerRefreshAction); // storedObjectsList.getInputMap().put(KeyStroke.getKeyStroke("F5"), "refresh"); storedObjectsList.getActionMap().put("refresh", containerRefreshAction); // } public void refreshContainers() { containers.clear(); storedObjects.clear(); ops.refreshContainers(callback); } public void refreshFiles(Container selected) { storedObjects.clear(); ops.refreshStoredObjects(selected, callback); } public void onProgressButton () { if (progressBar.isShowing()) return ; final int border = 15 ; Box box = Box.createVerticalBox() ; box.setBorder(BorderFactory.createEmptyBorder(border, border, border, border)); box.add (progressLabel) ; box.add (progressBar) ; JDialog dlg = new JDialog (owner) ; dlg.setContentPane(box); dlg.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE); dlg.setSize(200, 100) ; dlg.pack(); center (dlg) ; dlg.setVisible(true); } public void onSearch() { storedObjects.clear(); synchronized (allStoredObjects) { for (StoredObject storedObject : allStoredObjects) { if (isFilterIncluded(storedObject)) { storedObjects.addElement(storedObject); } } } //set the tablist if (allStoredObjects.size() != storedObjects.size()) objectViewTabbedPane.setSelectedIndex(listviewTabIndex); buildTree () ; } private boolean isFilterIncluded(StoredObject obj) { String filter = searchTextField.getText(); if (filter.isEmpty()) { return true; } else { return obj.getName().contains(filter); } } // // Callback // /** * {@inheritDoc}. */ @Override public void onStart() { if (busyCnt.getAndIncrement() == 0) { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); statusPanel.onStart(); progressButton.setEnabled(true); progressBar.setValue(0); progressLabel.setText("Processing"); progressBar.setIndeterminate(true) ; enableDisable(); } } /** * {@inheritDoc}. */ @Override public void onDone() { if (busyCnt.decrementAndGet() == 0) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); statusPanel.onEnd(); progressButton.setEnabled(false); progressBar.setValue(100); Window progressWindow = SwingUtilities.getWindowAncestor(progressBar); if (progressWindow != null) progressWindow.setVisible(false) ; } enableDisable(); } /** * {@inheritDoc}. */ @Override public void onError(final CommandException ex) { showError(ex); } /** * {@inheritDoc}. */ @Override public void onUpdateContainers(final Collection<Container> cs) { containers.clear(); for (Container container : cs) { containers.addElement(container); } statusPanel.onDeselectContainer(); } /** * {@inheritDoc}. */ @Override public void onStoredObjectDeleted(final Container container, final StoredObject storedObject) { if (isContainerSelected() && getSelectedContainer().equals(container)) { int idx = storedObjects.indexOf(storedObject); if (idx >= 0) { storedObjectsList.getSelectionModel().removeIndexInterval(idx, idx); } storedObjects.removeElement(storedObject); allStoredObjects.remove(storedObject); buildTree () ; } } /** * {@inheritDoc}. */ @Override public void onNewStoredObjects() { searchTextField.setText(""); storedObjects.clear(); allStoredObjects.clear(); statusPanel.onDeselectStoredObject(); buildTree () ; } /** * {@inheritDoc}. */ @Override public void onAppendStoredObjects(final Container container, int page, final Collection<StoredObject> sos) { if (isContainerSelected() && getSelectedContainer().equals(container)) { allStoredObjects.addAll(sos); for (StoredObject storedObject : sos) { if (isFilterIncluded(storedObject)) { storedObjects.addElement(storedObject); } } updateTree (sos) ; // TODO: seems to be necessary to avoid freezing for huge amount of objects // Must be checked // ... System.gc() ; } } /** * {@inheritDoc}. */ @Override public void onProgress(final double p, final String msg) { int currValue = (int) (p * 100) ; if (progressBar.isIndeterminate()) progressBar.setIndeterminate(false) ; progressBar.setValue(currValue); progressLabel.setText(msg); if (progressBar.getValue() == progressBar.getMaximum()) progressBar.setIndeterminate(true) ; } /** * {@inheritDoc}. */ @Override public void onContainerUpdate(final Container container) { statusPanel.onSelectContainer(container); } /** * {@inheritDoc}. */ @Override public void onStoredObjectUpdate(final StoredObject obj) { statusPanel.onSelectStoredObjects(Collections.singletonList(obj)); } // // // /** * @return true if the window can close. */ public boolean onClose() { return (loggedIn && confirm(getLocalizedString("confirm_quit_application"))) || (!loggedIn); } public boolean confirm(String message) { return JOptionPane.showConfirmDialog(this, message, getLocalizedString("Confirmation"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION; } public void info(String message) { JOptionPane.showMessageDialog(this, message) ; } protected void showError(CommandException ex) { JOptionPane.showMessageDialog(this, ex.toString(), getLocalizedString("Error"), JOptionPane.OK_OPTION); } }
Minor improvements
src/main/java/org/swiftexplorer/gui/MainPanel.java
Minor improvements
Java
apache-2.0
689417aa490e1a1a30b37d9c1cc996fb59b4c3a8
0
AllenZYoung/HeartBeat,maxiee/HeartBeat,maxiee/HeartBeat,AllenZYoung/HeartBeat
package com.maxiee.heartbeat.database.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.maxiee.heartbeat.database.tables.EventLabelRelationTable; import com.maxiee.heartbeat.database.tables.LabelsTable; import com.maxiee.heartbeat.model.Event; import com.maxiee.heartbeat.model.Label; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; /** * Created by maxiee on 15/11/10. */ public class LabelUtils { private static long queryId(Cursor cursor) { return DatabaseUtils.getLong(cursor, LabelsTable.ID); } private static String queryLabelStr(Cursor cursor) { return DatabaseUtils.getString(cursor, LabelsTable.LABEL); } private static Label queryLabel(Cursor cursor) { return new Label(queryId(cursor), queryLabelStr(cursor)); } private static long[] getRelativedIds(Context context, String idField, String getField, long id) { Cursor cursor = DatabaseUtils.query( context, EventLabelRelationTable.NAME, new String[]{EventLabelRelationTable.EVENT_ID, EventLabelRelationTable.LABEL_ID}, idField + "=?", new String[]{String.valueOf(id)}); if (cursor.getCount() < 1) { cursor.close(); return new long[] {}; } long[] ret = new long[cursor.getCount()]; while (cursor.moveToNext()) { ret[cursor.getPosition()] = DatabaseUtils.getLong(cursor, getField); } cursor.close(); return ret; } public static long[] getRelativedEventIds(Context context, Label label) { return getRelativedIds( context, EventLabelRelationTable.LABEL_ID, EventLabelRelationTable.EVENT_ID, label.getId()); } public static long[] getRelativedLabelIds(Context context, Event event) { return getRelativedIds( context, EventLabelRelationTable.EVENT_ID, EventLabelRelationTable.LABEL_ID, event.getId()); } public static void addRelation(Context context, long eventId, long labelId) { ContentValues values = new ContentValues(); values.put(EventLabelRelationTable.EVENT_ID, eventId); values.put(EventLabelRelationTable.LABEL_ID, labelId); DatabaseUtils.add(context, EventLabelRelationTable.NAME, values); } public static void deleteRelation(Context context, long eventId, long labelId) { DatabaseUtils.delete( context, EventLabelRelationTable.NAME, EventLabelRelationTable.EVENT_ID + "=? and " + EventLabelRelationTable.LABEL_ID + "=?", new String[]{String.valueOf(eventId), String.valueOf(labelId)}); deleteIfNoUse(context, new Label(labelId, "")); } public static void deleteRelation(Context context, Event event) { long[] ids = getRelativedLabelIds(context, event); for (long id : ids) deleteRelation(context, event.getId(), id); for (long id : ids) deleteIfNoUse(context, new Label(id, "")); } public static Label getLabelByLabelId(Context context, long labelId) { Cursor cursor = DatabaseUtils.query( context, LabelsTable.NAME, new String[]{LabelsTable.ID, LabelsTable.LABEL}, LabelsTable.ID + "=?", new String[]{String.valueOf(labelId)}); if (cursor.getCount() < 1) { cursor.close(); return null; } cursor.moveToFirst(); Label l = queryLabel(cursor); cursor.close(); return l; } public static ArrayList<Label> getLabelsByEvent(Context context, Event event) { long[] ids = getRelativedLabelIds(context, event); ArrayList<Label> labels = new ArrayList<>(); for (long id : ids) { Label l = getLabelByLabelId(context, id); if (l != null) labels.add(l); } return labels; } public static ArrayList<Label> getAll(Context context) { Cursor cursor = DatabaseUtils.queryAll( context, LabelsTable.NAME, new String[]{LabelsTable.ID, LabelsTable.LABEL}); ArrayList<Label> ret = new ArrayList<>(); if (cursor.getCount() < 1) { cursor.close(); return ret; } while (cursor.moveToNext()) { ret.add(queryLabel(cursor)); } cursor.close(); return ret; } public static Label addLabel(Context context, String label) { ContentValues values = new ContentValues(); values.put(LabelsTable.LABEL, label); return new Label(DatabaseUtils.add(context, LabelsTable.NAME, values), label); } public static Label addLabel(Context context, long eventId, String label) { Label ret = addLabel(context, label); addRelation(context, eventId, ret.getId()); return ret; } public static ArrayList<Label> addLabels(Context context, ArrayList<String> labels) { ArrayList<Label> ret = new ArrayList<>(); for (String l : labels) { long id = hasLabel(context, l); if (id == NOT_FOUND) { ret.add(addLabel(context, l)); } else { ret.add(getLabelByLabelId(context, id)); } } return ret; } public static ArrayList<Label> addLabels(Context context, long eventId, ArrayList<String> labels) { ArrayList<Label> ret = addLabels(context, labels); for (Label l: ret) { addRelation(context, eventId, l.getId()); } return ret; } public static void deleteIfNoUse(Context context, Label label) { ArrayList<Event> events = EventUtils.getEvents(context, label); if (!events.isEmpty()) return; DatabaseUtils.delete( context, LabelsTable.NAME, LabelsTable.ID + "=?", new String[] {String.valueOf(label.getId())}); } public static Map<Long, Integer> getFreq(Context context) { ArrayList<Label> labels = LabelUtils.getAll(context); Map<Long, Integer> ret = new TreeMap<>(); for (Label label : labels) { Cursor cursor = DatabaseUtils.query( context, EventLabelRelationTable.NAME, new String[]{EventLabelRelationTable.LABEL_ID}, EventLabelRelationTable.LABEL_ID + "=?", new String[]{String.valueOf(label.getId())}); ret.put(label.getId() ,cursor.getCount()); cursor.close(); } return ret; } public final static int NOT_FOUND = -1; // TODO return Label public static long hasLabel(Context context, String label) { Cursor cursor = DatabaseUtils.query( context, LabelsTable.NAME, new String[] {LabelsTable.ID, LabelsTable.LABEL}, LabelsTable.LABEL + "=?", new String[] {label}); if (cursor.getCount() < 1) { cursor.close(); return -1; } else { cursor.moveToFirst(); long ret = queryId(cursor); cursor.close(); return ret; } } }
app/src/main/java/com/maxiee/heartbeat/database/utils/LabelUtils.java
package com.maxiee.heartbeat.database.utils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.maxiee.heartbeat.database.tables.EventLabelRelationTable; import com.maxiee.heartbeat.database.tables.LabelsTable; import com.maxiee.heartbeat.model.Event; import com.maxiee.heartbeat.model.Label; import java.util.ArrayList; import java.util.Map; import java.util.TreeMap; /** * Created by maxiee on 15/11/10. */ public class LabelUtils { private static long queryId(Cursor cursor) { return DatabaseUtils.getLong(cursor, LabelsTable.ID); } private static String queryLabelStr(Cursor cursor) { return DatabaseUtils.getString(cursor, LabelsTable.LABEL); } private static Label queryLabel(Cursor cursor) { return new Label(queryId(cursor), queryLabelStr(cursor)); } private static long[] getRelativedIds(Context context, String idField, String getField, long id) { Cursor cursor = DatabaseUtils.query( context, EventLabelRelationTable.NAME, new String[]{EventLabelRelationTable.EVENT_ID, EventLabelRelationTable.LABEL_ID}, idField + "=?", new String[]{String.valueOf(id)}); if (cursor.getCount() < 1) { cursor.close(); return new long[] {}; } long[] ret = new long[cursor.getCount()]; while (cursor.moveToNext()) { ret[cursor.getPosition()] = DatabaseUtils.getLong(cursor, getField); } cursor.close(); return ret; } public static long[] getRelativedEventIds(Context context, Label label) { return getRelativedIds( context, EventLabelRelationTable.LABEL_ID, EventLabelRelationTable.EVENT_ID, label.getId()); } public static long[] getRelativedLabelIds(Context context, Event event) { return getRelativedIds( context, EventLabelRelationTable.EVENT_ID, EventLabelRelationTable.LABEL_ID, event.getId()); } public static void addRelation(Context context, long eventId, long labelId) { ContentValues values = new ContentValues(); values.put(EventLabelRelationTable.EVENT_ID, eventId); values.put(EventLabelRelationTable.LABEL_ID, labelId); DatabaseUtils.add(context, EventLabelRelationTable.NAME, values); } public static void deleteRelation(Context context, long eventId, long labelId) { DatabaseUtils.delete( context, EventLabelRelationTable.NAME, EventLabelRelationTable.EVENT_ID + "=? and " + EventLabelRelationTable.LABEL_ID + "=?", new String[]{String.valueOf(eventId), String.valueOf(labelId)}); deleteIfNoUse(context, new Label(labelId, "")); } public static void deleteRelation(Context context, Event event) { long[] ids = getRelativedLabelIds(context, event); for (long id : ids) deleteRelation(context, event.getId(), id); for (long id : ids) deleteIfNoUse(context, new Label(id, "")); } public static Label getLabelByLabelId(Context context, long labelId) { Cursor cursor = DatabaseUtils.query( context, LabelsTable.NAME, new String[]{LabelsTable.ID, LabelsTable.LABEL}, LabelsTable.ID + "=?", new String[]{String.valueOf(labelId)}); if (cursor.getCount() < 1) { cursor.close(); return null; } cursor.moveToFirst(); Label l = queryLabel(cursor); cursor.close(); return l; } public static ArrayList<Label> getLabelsByEvent(Context context, Event event) { long[] ids = getRelativedLabelIds(context, event); ArrayList<Label> labels = new ArrayList<>(); for (long id : ids) { Label l = getLabelByLabelId(context, id); if (l != null) labels.add(l); } return labels; } public static ArrayList<Label> getAll(Context context) { Cursor cursor = DatabaseUtils.queryAll( context, LabelsTable.NAME, new String[]{LabelsTable.ID, LabelsTable.LABEL}); ArrayList<Label> ret = new ArrayList<>(); if (cursor.getCount() < 1) { cursor.close(); return ret; } while (cursor.moveToNext()) { ret.add(queryLabel(cursor)); } cursor.close(); return ret; } public static Label addLabel(Context context, String label) { ContentValues values = new ContentValues(); values.put(LabelsTable.LABEL, label); return new Label(DatabaseUtils.add(context, LabelsTable.NAME, values), label); } public static Label addLabel(Context context, long eventId, String label) { Label ret = addLabel(context, label); addRelation(context, eventId, ret.getId()); return ret; } public static ArrayList<Label> addLabels(Context context, ArrayList<String> labels) { ArrayList<Label> ret = new ArrayList<>(); for (String l : labels) { ret.add(addLabel(context, l)); } return ret; } public static ArrayList<Label> addLabels(Context context, long eventId, ArrayList<String> labels) { ArrayList<Label> ret = addLabels(context, labels); for (Label l: ret) { addRelation(context, eventId, l.getId()); } return ret; } public static void deleteIfNoUse(Context context, Label label) { ArrayList<Event> events = EventUtils.getEvents(context, label); if (!events.isEmpty()) return; DatabaseUtils.delete( context, LabelsTable.NAME, LabelsTable.ID + "=?", new String[] {String.valueOf(label.getId())}); } public static Map<Long, Integer> getFreq(Context context) { ArrayList<Label> labels = LabelUtils.getAll(context); Map<Long, Integer> ret = new TreeMap<>(); for (Label label : labels) { Cursor cursor = DatabaseUtils.query( context, EventLabelRelationTable.NAME, new String[]{EventLabelRelationTable.LABEL_ID}, EventLabelRelationTable.LABEL_ID + "=?", new String[]{String.valueOf(label.getId())}); ret.put(label.getId() ,cursor.getCount()); cursor.close(); } return ret; } public final static int NOT_FOUND = -1; // TODO return Label public static long hasLabel(Context context, String label) { Cursor cursor = DatabaseUtils.query( context, LabelsTable.NAME, new String[] {LabelsTable.ID, LabelsTable.LABEL}, LabelsTable.LABEL + "=?", new String[] {label}); if (cursor.getCount() < 1) { cursor.close(); return -1; } else { cursor.moveToFirst(); long ret = queryId(cursor); cursor.close(); return ret; } } }
LabelUtils.java: fix bug: add label duplicated.
app/src/main/java/com/maxiee/heartbeat/database/utils/LabelUtils.java
LabelUtils.java: fix bug: add label duplicated.
Java
apache-2.0
84d72380a666797587fb62a5b538c79aaa61a8b8
0
vatbub/hangman-solver,vatbub/hangman-solver
package algorithm; import languages.Language; /** * Represents a result of {@link HangmanSolver#solve} * * @author frede * */ public class Result { /** * The current state of the game (win, loose, still running) * * @see GameState */ public GameState gameState; /** * The next guess. */ public String result; public ResultType resultType; public char bestChar; public double bestCharScore; /** * The word in the dictionary that is the closest word to the current word * sequence. This is not necessarily the proposed next guess, but this is * most probably the word that the user is looking for. */ public String bestWord; /** * The correlation currentSequence - {@link #bestWord} computed with * {@link languages.TabFile#stringCorrelation} */ public double bestWordScore; /** * The language of the solution */ public Language lang; public void convertToLetterResult() { this.result = Character.toString(this.bestChar); this.resultType = ResultType.letter; } public void convertToWordResult() { this.result = this.bestWord; this.resultType = ResultType.word; } /** * Combines multiple results to a phrase * @param resultsToCombine The {@code Result}s to be combined * @return A {@link ResultType}{@code .phrase}-result. */ public static Result generatePhraseResult(ResultList resultsToCombine){ Result res = new Result(); res.bestWord = String.join(" ", resultsToCombine.getBestWords()); res.convertToWordResult(); res.resultType = ResultType.phrase; res.lang = resultsToCombine.get(0).lang; return res; } }
src/main/java/algorithm/Result.java
package algorithm; import java.util.ArrayList; import java.util.List; import languages.Language; /** * Represents a result of {@link HangmanSolver#solve} * * @author frede * */ public class Result { /** * The current state of the game (win, loose, still running) * * @see GameState */ public GameState gameState; /** * The next guess. */ public String result; public ResultType resultType; public char bestChar; public double bestCharScore; /** * The word in the dictionary that is the closest word to the current word * sequence. This is not necessarily the proposed next guess, but this is * most probably the word that the user is looking for. */ public String bestWord; /** * The correlation currentSequence - {@link #bestWord} computed with * {@link languages.TabFile#stringCorrelation} */ public double bestWordScore; /** * The language of the solution */ public Language lang; public void convertToLetterResult() { this.result = Character.toString(this.bestChar); this.resultType = ResultType.letter; } public void convertToWordResult() { this.result = this.bestWord; this.resultType = ResultType.word; } /** * Combines multiple results to a phrase * @param resultsToCombine The {@code Result}s to be combined * @return A {@link ResultType}{@code .phrase}-result. */ public static Result generatePhraseResult(ResultList resultsToCombine){ Result res = new Result(); res.bestWord = String.join(" ", resultsToCombine.getBestWords()); res.convertToWordResult(); res.resultType = ResultType.phrase; res.lang = resultsToCombine.get(0).lang; return res; } }
Removed unused imports
src/main/java/algorithm/Result.java
Removed unused imports
Java
apache-2.0
e8736d2d02f1f7f17a339b42c20a41881b450973
0
dtrott/trello4j,smozely/trello4j,ForNeVeR/trello4j,Pedramrn/trello4j,johanmynhardt/trello4j
package org.trello4j; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.trello4j.model.Action; import org.trello4j.model.Card; import org.trello4j.model.Checklist; import org.trello4j.model.Member; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * @author Johan Mynhardt */ public class CardServiceTest { // Note: this url was used to generate token with read, write permissions: // https://trello.com/1/authorize?key=23ec668887f03d4c71c7f74fb0ae30a4&name=My+Application&expiration=never&response_type=token&scope=read,write private static final String API_KEY = "23ec668887f03d4c71c7f74fb0ae30a4"; private static final String API_TOKEN = "cfb1df98cbde193b3181e02a8bca9871eaeb8aed0659391f887631055b0b774d"; @Test public void testCreateCard() { // GIVEN String listId = "4f82ed4f1903bae43e66f5fd"; String name = "Trello4J CardService: Add Card using POST"; String description = "Something awesome happened :)"; Map<String, Object> map = new HashMap<String, Object>(); map.put("desc", description); // WHEN Card card = new TrelloImpl(API_KEY, API_TOKEN).createCard(listId, name, map); // THEN assertNotNull(card); assertThat(card.getName(), equalTo(name)); assertThat(card.getDesc(), equalTo(description)); } @Test public void testCommentOnCard() { // GIVEN String idCard = "50429779e215b4e45d7aef24"; String commentText = "Comment text from JUnit test."; // WHEN Action action = new TrelloImpl(API_KEY, API_TOKEN).commentOnCard(idCard, commentText); //THEN assertNotNull(action); assertThat(action.getType(), equalTo(Action.TYPE.COMMENT_CARD)); assertThat(action.getData().getText(), equalTo(commentText)); assertThat(action.getData().getCard().getId(), equalTo(idCard)); } @Test public void testAttachFileToCard() throws IOException { // GIVEN String idCard = "50429779e215b4e45d7aef24"; String fileContents = "foo bar text in file\n"; File file = File.createTempFile("trello_attach_test",".junit"); if (!file.exists()) { try { FileWriter fileWriter = new FileWriter(file); fileWriter.write(fileContents); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { fail(e.toString()); } } long size = file.length(); String fileName = file.getName(); // WHEN List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, file, null, null, null); file.deleteOnExit(); //THEN assertNotNull(attachments); Card.Attachment attachment = attachments.get(attachments.size()-1); assertThat(attachment.getName(), equalTo(fileName)); assertThat(attachment.getBytes(), equalTo("" + size)); } @Test public void testAttachFileFromUrl() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; URL url = new URL("https://trello.com/images/reco/Taco_idle.png"); //WHEN List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, null, url, "Taco", null); //THEN assertNotNull(attachments); Card.Attachment attachment = attachments.get(attachments.size()-1); assertNotNull(attachment); assertThat(attachment.getName(), equalTo("Taco")); assertTrue(attachment.getUrl().startsWith("http")); assertTrue(attachment.getUrl().endsWith("Taco_idle.png")); } @Test public void testAddChecklistToCard() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; //WHEN Checklist checklist = new TrelloImpl(API_KEY, API_TOKEN).addChecklist(idCard, null, null, null); //THEN assertNotNull(checklist); assertThat(checklist.getName(), equalTo("Checklist")); assertThat(checklist.getCheckItems().size(), equalTo(0)); } @Test public void testAddLabelToCard() throws IOException { //TODO: prepare for test by removing all labels when the delete method becomes available. //GIVEN String idCard = "50429779e215b4e45d7aef24"; Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //WHEN trello.deleteLabelFromCard(idCard, "blue"); List<Card.Label> labels = trello.addLabel(idCard, "blue"); //THEN assertNotNull(labels); assertThat(labels.get(labels.size() - 1).getColor(), equalTo("blue")); } @Test public void testAddMemberToCard() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; Trello trello = new TrelloImpl(API_KEY, API_TOKEN); Member boardUser = trello.getMember("userj"); //PREPARE CARD List<Member> cardMembers = trello.getMembersByCard(idCard); if (!cardMembers.isEmpty()) { for (Member member : cardMembers){ trello.deleteMemberFromCard(idCard, member.getId()); } } //WHEN List<Member> membersAfterAdd = trello.addMember(idCard, boardUser.getId()); //THEN assertNotNull(membersAfterAdd); assertThat(membersAfterAdd.size(), equalTo(1)); Member resultMember = membersAfterAdd.get(0); assertThat(resultMember.getId(), equalTo(boardUser.getId())); } @Test public void addMemberVote() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member boardUser = trello.getMember("userj"); assertNotNull(boardUser); //CLEANUP List<Member> votedMembers = trello.getMemberVotesOnCard(idCard); if (votedMembers != null && !votedMembers.isEmpty()) { for (Member member : votedMembers) { trello.deleteVoteFromCard(idCard, member.getId()); } } //WHEN boolean voted = new TrelloImpl(API_KEY, API_TOKEN).voteOnCard(idCard, boardUser.getId()); //THEN assertTrue(voted); } @Test public void deleteCard() { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idList = "4f82ed4f1903bae43e66f5fd"; Card card = trello.createCard(idList, "jUnitCard", null); //WHEN boolean deletedCard = trello.deleteCard(card.getId()); //THEN assertTrue(deletedCard); } @Test public void deleteChecklistFromCard() { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Checklist checklist = trello.addChecklist(idCard, null, null, null); //WHEN boolean deletedChecklist = trello.deleteChecklistFromCard(idCard, checklist.getId()); //THEN assertTrue(deletedChecklist); } @Test public void deleteLabelFromCard() { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member member = trello.getMember("userj"); //PREPARATION trello.deleteLabelFromCard(idCard, "blue"); trello.addLabel(idCard, "blue"); //WHEN boolean deleted = trello.deleteLabelFromCard(idCard, "blue"); //THEN assertTrue(deleted); } @Test public void deleteMemberFromCard() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member member = trello.getMember("userj"); //PREPARATION List<Member> members = trello.getMembersByCard(idCard); boolean needToAddMember = true; for (Member cardMember : members) { if (cardMember.getId().equals(member.getId())) needToAddMember = false; } if (needToAddMember) trello.addMember(idCard, member.getId()); //WHEN boolean removedMemberFromCard = trello.deleteMemberFromCard(idCard, member.getId()); //THEN assertTrue(removedMemberFromCard); } @Test public void testDeleteMemberVoteFromCard() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member boardUser = trello.getMember("userj"); assertNotNull(boardUser); List<Member> membersVoted = trello.getMemberVotesOnCard(idCard); boolean needToAddVote = true; for (Member member : membersVoted) { if (member.getId().equals(boardUser.getId())) needToAddVote = false; } if (needToAddVote) { boolean addedVote = trello.voteOnCard(idCard, boardUser.getId()); assertTrue(addedVote); } //WHEN boolean removedFromCard = trello.deleteVoteFromCard(idCard, boardUser.getId()); //THEN assertTrue(removedFromCard); } }
src/test/java/org/trello4j/CardServiceTest.java
package org.trello4j; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.trello4j.model.Action; import org.trello4j.model.Card; import org.trello4j.model.Checklist; import org.trello4j.model.Member; import static junit.framework.Assert.assertTrue; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; /** * @author Johan Mynhardt */ public class CardServiceTest { // Note: this url was used to generate token with read, write permissions: // https://trello.com/1/authorize?key=23ec668887f03d4c71c7f74fb0ae30a4&name=My+Application&expiration=never&response_type=token&scope=read,write private static final String API_KEY = "23ec668887f03d4c71c7f74fb0ae30a4"; private static final String API_TOKEN = "cfb1df98cbde193b3181e02a8bca9871eaeb8aed0659391f887631055b0b774d"; @Test public void testCreateCard() { // GIVEN String listId = "4f82ed4f1903bae43e66f5fd"; String name = "Trello4J CardService: Add Card using POST"; String description = "Something awesome happened :)"; Map<String, Object> map = new HashMap<String, Object>(); map.put("desc", description); // WHEN Card card = new TrelloImpl(API_KEY, API_TOKEN).createCard(listId, name, map); // THEN assertNotNull(card); assertThat(card.getName(), equalTo(name)); assertThat(card.getDesc(), equalTo(description)); } @Test public void testCommentOnCard() { // GIVEN String idCard = "50429779e215b4e45d7aef24"; String commentText = "Comment text from JUnit test."; // WHEN Action action = new TrelloImpl(API_KEY, API_TOKEN).commentOnCard(idCard, commentText); //THEN assertNotNull(action); assertThat(action.getType(), equalTo(Action.TYPE.COMMENT_CARD)); assertThat(action.getData().getText(), equalTo(commentText)); assertThat(action.getData().getCard().getId(), equalTo(idCard)); } @Test public void testAttachFileToCard() throws IOException { // GIVEN String idCard = "50429779e215b4e45d7aef24"; String fileContents = "foo bar text in file\n"; File file = File.createTempFile("trello_attach_test",".junit"); if (!file.exists()) { try { FileWriter fileWriter = new FileWriter(file); fileWriter.write(fileContents); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { fail(e.toString()); } } long size = file.length(); String fileName = file.getName(); // WHEN List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, file, null, null, null); file.deleteOnExit(); //THEN assertNotNull(attachments); Card.Attachment attachment = attachments.get(attachments.size()-1); assertThat(attachment.getName(), equalTo(fileName)); assertThat(attachment.getBytes(), equalTo("" + size)); } @Test public void testAttachFileFromUrl() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; URL url = new URL("https://trello.com/images/reco/Taco_idle.png"); //WHEN List<Card.Attachment> attachments = new TrelloImpl(API_KEY, API_TOKEN).attachToCard(idCard, null, url, "Taco", null); //THEN assertNotNull(attachments); Card.Attachment attachment = attachments.get(attachments.size()-1); assertNotNull(attachment); assertThat(attachment.getName(), equalTo("Taco")); assertTrue(attachment.getUrl().startsWith("http")); assertTrue(attachment.getUrl().endsWith("Taco_idle.png")); } @Test public void testAddChecklistToCard() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; //WHEN Checklist checklist = new TrelloImpl(API_KEY, API_TOKEN).addChecklist(idCard, null, null, null); //THEN assertNotNull(checklist); assertThat(checklist.getName(), equalTo("Checklist")); assertThat(checklist.getCheckItems().size(), equalTo(0)); } @Test public void testAddLabelToCard() throws IOException { //TODO: prepare for test by removing all labels when the delete method becomes available. //GIVEN String idCard = "50429779e215b4e45d7aef24"; Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //WHEN trello.deleteLabelFromCard(idCard, "blue"); List<Card.Label> labels = trello.addLabel(idCard, "blue"); //THEN assertNotNull(labels); assertThat(labels.get(labels.size() - 1).getColor(), equalTo("blue")); } @Test public void testAddMemberToCard() throws IOException { //GIVEN String idCard = "50429779e215b4e45d7aef24"; Trello trello = new TrelloImpl(API_KEY, API_TOKEN); Member boardUser = trello.getMember("userj"); //PREPARE CARD List<Member> cardMembers = trello.getMembersByCard(idCard); if (!cardMembers.isEmpty()) { for (Member member : cardMembers){ trello.deleteMemberFromCard(idCard, member.getId()); } } //WHEN List<Member> membersAfterAdd = trello.addMember(idCard, boardUser.getId()); //THEN assertNotNull(membersAfterAdd); assertThat(membersAfterAdd.size(), equalTo(1)); Member resultMember = membersAfterAdd.get(0); assertThat(resultMember.getId(), equalTo(boardUser.getId())); } @Test public void addMemberVote() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member boardUser = trello.getMember("userj"); assertNotNull(boardUser); //CLEANUP List<Member> votedMembers = trello.getMemberVotesOnCard(idCard); if (votedMembers != null && !votedMembers.isEmpty()) { for (Member member : votedMembers) { trello.deleteVoteFromCard(idCard, member.getId()); } } //WHEN boolean voted = new TrelloImpl(API_KEY, API_TOKEN).voteOnCard(idCard, boardUser.getId()); //THEN assertTrue(voted); } @Test public void deleteChecklistFromCard() { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Checklist checklist = trello.addChecklist(idCard, null, null, null); //WHEN boolean deletedChecklist = trello.deleteChecklistFromCard(idCard, checklist.getId()); //THEN assertTrue(deletedChecklist); } @Test public void deleteLabelFromCard() { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member member = trello.getMember("userj"); //PREPARATION trello.deleteLabelFromCard(idCard, "blue"); trello.addLabel(idCard, "blue"); //WHEN boolean deleted = trello.deleteLabelFromCard(idCard, "blue"); //THEN assertTrue(deleted); } @Test public void deleteMemberFromCard() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member member = trello.getMember("userj"); //PREPARATION List<Member> members = trello.getMembersByCard(idCard); boolean needToAddMember = true; for (Member cardMember : members) { if (cardMember.getId().equals(member.getId())) needToAddMember = false; } if (needToAddMember) trello.addMember(idCard, member.getId()); //WHEN boolean removedMemberFromCard = trello.deleteMemberFromCard(idCard, member.getId()); //THEN assertTrue(removedMemberFromCard); } @Test public void testDeleteMemberVoteFromCard() throws IOException { Trello trello = new TrelloImpl(API_KEY, API_TOKEN); //GIVEN String idCard = "50429779e215b4e45d7aef24"; Member boardUser = trello.getMember("userj"); assertNotNull(boardUser); List<Member> membersVoted = trello.getMemberVotesOnCard(idCard); boolean needToAddVote = true; for (Member member : membersVoted) { if (member.getId().equals(boardUser.getId())) needToAddVote = false; } if (needToAddVote) { boolean addedVote = trello.voteOnCard(idCard, boardUser.getId()); assertTrue(addedVote); } //WHEN boolean removedFromCard = trello.deleteVoteFromCard(idCard, boardUser.getId()); //THEN assertTrue(removedFromCard); } }
Card DELETE /1/cards/{0} test.
src/test/java/org/trello4j/CardServiceTest.java
Card DELETE /1/cards/{0} test.
Java
apache-2.0
7fda3d543df169cad487fae1cbedce15f775d27c
0
fl4via/xnio,panossot/xnio,fl4via/xnio,dmlloyd/xnio,kabir/xnio,kabir/xnio,panossot/xnio,xnio/xnio,stuartwdouglas/xnio,xnio/xnio
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.xnio.nio; import java.io.IOException; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; import java.security.AccessController; import java.security.PrivilegedAction; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.jboss.logging.Logger; import org.xnio.IoUtils; import org.xnio.Version; import org.xnio.Xnio; import org.xnio.OptionMap; import org.xnio.XnioWorker; /** * An NIO-based XNIO provider for a standalone application. */ final class NioXnio extends Xnio { private static final Logger log = Logger.getLogger("org.xnio.nio"); interface SelectorCreator { Selector open() throws IOException; } final SelectorCreator tempSelectorCreator; final SelectorCreator mainSelectorCreator; static { log.info("XNIO NIO Implementation Version " + Version.VERSION); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { final String bugLevel = System.getProperty("sun.nio.ch.bugLevel"); if (bugLevel == null) System.setProperty("sun.nio.ch.bugLevel", ""); return null; } }); } /** * Construct a new NIO-based XNIO provider instance. Should only be invoked by the service loader. */ NioXnio() { super("nio"); final Object[] objects = AccessController.doPrivileged( new PrivilegedAction<Object[]>() { public Object[] run() { final SelectorProvider defaultProvider = SelectorProvider.provider(); final String chosenProvider = System.getProperty("xnio.nio.selector.provider"); SelectorProvider provider = null; if (chosenProvider != null) { try { provider = Class.forName(chosenProvider, true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Mac OS X and BSD provider = Class.forName("sun.nio.ch.KQueueSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Linux provider = Class.forName("sun.nio.ch.EPollSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Solaris provider = Class.forName("sun.nio.ch.DevPollSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // AIX provider = Class.forName("sun.nio.ch.PollsetSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { defaultProvider.openSelector().close(); provider = defaultProvider; } catch (Throwable e) { // not available } } if (provider == null) { try { // Nothing else works, not even the default provider = Class.forName("sun.nio.ch.PollSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { throw new RuntimeException("No functional selector provider is available"); } log.tracef("Starting up with selector provider %s", provider.getClass().getCanonicalName()); final boolean defaultIsPoll = "sun.nio.ch.PollSelectorProvider".equals(provider.getClass().getName()); final String chosenMainSelector = System.getProperty("xnio.nio.selector.main"); final String chosenTempSelector = System.getProperty("xnio.nio.selector.temp"); final SelectorCreator defaultSelectorCreator = new DefaultSelectorCreator(provider); final Object[] objects = new Object[3]; objects[0] = provider; if (chosenTempSelector != null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator(chosenTempSelector, provider); IoUtils.safeClose(creator.open()); objects[1] = creator; } catch (Exception e) { // not available } if (chosenMainSelector != null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator(chosenMainSelector, provider); IoUtils.safeClose(creator.open()); objects[2] = creator; } catch (Exception e) { // not available } if (! defaultIsPoll) { // default is fine for main selectors; we should try to get poll for temp though if (objects[1] == null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator("sun.nio.ch.PollSelectorImpl", provider); IoUtils.safeClose(creator.open()); objects[1] = creator; } catch (Exception e) { // not available } } if (objects[1] == null) { objects[1] = defaultSelectorCreator; } if (objects[2] == null) { objects[2] = defaultSelectorCreator; } return objects; } } ); tempSelectorCreator = (SelectorCreator) objects[1]; mainSelectorCreator = (SelectorCreator) objects[2]; log.tracef("Using %s for main selectors", mainSelectorCreator); log.tracef("Using %s for temp selectors", tempSelectorCreator); } public XnioWorker createWorker(final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) throws IOException, IllegalArgumentException { final NioXnioWorker worker = new NioXnioWorker(this, threadGroup, optionMap, terminationTask); worker.start(); return worker; } private final ThreadLocal<Selector> selectorThreadLocal = new ThreadLocal<Selector>() { public void remove() { // if no selector was created, none will be closed IoUtils.safeClose(get()); super.remove(); } }; Selector getSelector() throws IOException { final ThreadLocal<Selector> threadLocal = selectorThreadLocal; Selector selector = threadLocal.get(); if (selector == null) { selector = tempSelectorCreator.open(); threadLocal.set(selector); } return selector; } private static class DefaultSelectorCreator implements SelectorCreator { private final SelectorProvider provider; private DefaultSelectorCreator(final SelectorProvider provider) { this.provider = provider; } public Selector open() throws IOException { return provider.openSelector(); } public String toString() { return "Default system selector creator for provider " + provider.getClass(); } } private static class ConstructorSelectorCreator implements SelectorCreator { private final Constructor<? extends Selector> constructor; private final SelectorProvider provider; public ConstructorSelectorCreator(final String name, final SelectorProvider provider) throws ClassNotFoundException, NoSuchMethodException { this.provider = provider; final Class<? extends Selector> selectorImplClass = Class.forName(name, true, null).asSubclass(Selector.class); final Constructor<? extends Selector> constructor = selectorImplClass.getDeclaredConstructor(SelectorProvider.class); constructor.setAccessible(true); this.constructor = constructor; } public Selector open() throws IOException { try { return constructor.newInstance(provider); } catch (InstantiationException e) { return Selector.open(); } catch (IllegalAccessException e) { return Selector.open(); } catch (InvocationTargetException e) { try { throw e.getTargetException(); } catch (IOException e2) { throw e2; } catch (RuntimeException e2) { throw e2; } catch (Error e2) { throw e2; } catch (Throwable t) { throw new IllegalStateException("Unexpected invocation exception", t); } } } public String toString() { return String.format("Selector creator %s for provider %s", constructor.getDeclaringClass(), provider.getClass()); } } }
nio-impl/src/main/java/org/xnio/nio/NioXnio.java
/* * JBoss, Home of Professional Open Source. * Copyright 2012 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.xnio.nio; import java.io.IOException; import java.nio.channels.Selector; import java.nio.channels.spi.SelectorProvider; import java.security.AccessController; import java.security.PrivilegedAction; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.jboss.logging.Logger; import org.xnio.IoUtils; import org.xnio.Version; import org.xnio.Xnio; import org.xnio.OptionMap; import org.xnio.XnioWorker; /** * An NIO-based XNIO provider for a standalone application. */ final class NioXnio extends Xnio { private static final Logger log = Logger.getLogger("org.xnio.nio"); interface SelectorCreator { Selector open() throws IOException; } final SelectorCreator tempSelectorCreator; final SelectorCreator mainSelectorCreator; static { log.info("XNIO NIO Implementation Version " + Version.VERSION); AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { final String bugLevel = System.getProperty("sun.nio.ch.bugLevel"); if (bugLevel == null) System.setProperty("sun.nio.ch.bugLevel", ""); return null; } }); } /** * Construct a new NIO-based XNIO provider instance. Should only be invoked by the service loader. */ NioXnio() { super("nio"); final Object[] objects = AccessController.doPrivileged( new PrivilegedAction<Object[]>() { public Object[] run() { final SelectorProvider defaultProvider = SelectorProvider.provider(); final String chosenProvider = System.getProperty("xnio.nio.selector.provider"); SelectorProvider provider = null; if (chosenProvider != null) { try { provider = Class.forName(chosenProvider, true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Mac OS X and BSD provider = Class.forName("sun.nio.ch.KQueueSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Linux provider = Class.forName("sun.nio.ch.EPollSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // Solaris provider = Class.forName("sun.nio.ch.DevPollSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { try { // AIX provider = Class.forName("sun.nio.ch.PollsetSelectorProvider", true, NioXnio.class.getClassLoader()).asSubclass(SelectorProvider.class).getConstructor().newInstance(); provider.openSelector().close(); } catch (Throwable e) { // not available provider = null; } } if (provider == null) { provider = defaultProvider; } log.tracef("Starting up with selector provider %s", provider.getClass().getCanonicalName()); final boolean defaultIsPoll = "sun.nio.ch.PollSelectorProvider".equals(provider.getClass().getName()); final String chosenMainSelector = System.getProperty("xnio.nio.selector.main"); final String chosenTempSelector = System.getProperty("xnio.nio.selector.temp"); final SelectorCreator defaultSelectorCreator = new DefaultSelectorCreator(provider); final Object[] objects = new Object[3]; objects[0] = provider; if (chosenTempSelector != null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator(chosenTempSelector, provider); IoUtils.safeClose(creator.open()); objects[1] = creator; } catch (Exception e) { // not available } if (chosenMainSelector != null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator(chosenMainSelector, provider); IoUtils.safeClose(creator.open()); objects[2] = creator; } catch (Exception e) { // not available } if (! defaultIsPoll) { // default is fine for main selectors; we should try to get poll for temp though if (objects[1] == null) try { final ConstructorSelectorCreator creator = new ConstructorSelectorCreator("sun.nio.ch.PollSelectorImpl", provider); IoUtils.safeClose(creator.open()); objects[1] = creator; } catch (Exception e) { // not available } } if (objects[1] == null) { objects[1] = defaultSelectorCreator; } if (objects[2] == null) { objects[2] = defaultSelectorCreator; } return objects; } } ); tempSelectorCreator = (SelectorCreator) objects[1]; mainSelectorCreator = (SelectorCreator) objects[2]; log.tracef("Using %s for main selectors", mainSelectorCreator); log.tracef("Using %s for temp selectors", tempSelectorCreator); } public XnioWorker createWorker(final ThreadGroup threadGroup, final OptionMap optionMap, final Runnable terminationTask) throws IOException, IllegalArgumentException { final NioXnioWorker worker = new NioXnioWorker(this, threadGroup, optionMap, terminationTask); worker.start(); return worker; } private final ThreadLocal<Selector> selectorThreadLocal = new ThreadLocal<Selector>() { public void remove() { // if no selector was created, none will be closed IoUtils.safeClose(get()); super.remove(); } }; Selector getSelector() throws IOException { final ThreadLocal<Selector> threadLocal = selectorThreadLocal; Selector selector = threadLocal.get(); if (selector == null) { selector = tempSelectorCreator.open(); threadLocal.set(selector); } return selector; } private static class DefaultSelectorCreator implements SelectorCreator { private final SelectorProvider provider; private DefaultSelectorCreator(final SelectorProvider provider) { this.provider = provider; } public Selector open() throws IOException { return provider.openSelector(); } public String toString() { return "Default system selector creator for provider " + provider.getClass(); } } private static class ConstructorSelectorCreator implements SelectorCreator { private final Constructor<? extends Selector> constructor; private final SelectorProvider provider; public ConstructorSelectorCreator(final String name, final SelectorProvider provider) throws ClassNotFoundException, NoSuchMethodException { this.provider = provider; final Class<? extends Selector> selectorImplClass = Class.forName(name, true, null).asSubclass(Selector.class); final Constructor<? extends Selector> constructor = selectorImplClass.getDeclaredConstructor(SelectorProvider.class); constructor.setAccessible(true); this.constructor = constructor; } public Selector open() throws IOException { try { return constructor.newInstance(provider); } catch (InstantiationException e) { return Selector.open(); } catch (IllegalAccessException e) { return Selector.open(); } catch (InvocationTargetException e) { try { throw e.getTargetException(); } catch (IOException e2) { throw e2; } catch (RuntimeException e2) { throw e2; } catch (Error e2) { throw e2; } catch (Throwable t) { throw new IllegalStateException("Unexpected invocation exception", t); } } } public String toString() { return String.format("Selector creator %s for provider %s", constructor.getDeclaringClass(), provider.getClass()); } } }
Detect situations where the default selector provider does not work properly
nio-impl/src/main/java/org/xnio/nio/NioXnio.java
Detect situations where the default selector provider does not work properly
Java
apache-2.0
6a3e2a234750844202d850b5507f293ff94ae12d
0
ISSC/Bluebit
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.data.BLEDevice; import com.issc.impl.GattProxy; import com.issc.R; import com.issc.util.Log; import java.util.ArrayList; import java.util.Iterator; import java.util.UUID; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ToggleButton; import com.samsung.android.sdk.bt.gatt.BluetoothGatt; import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter; import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback; import com.samsung.android.sdk.bt.gatt.BluetoothGattCharacteristic; import com.samsung.android.sdk.bt.gatt.BluetoothGattService; public class ActivityAIO extends Activity { private BluetoothDevice mDevice; private BluetoothGatt mGatt; private GattProxy.Listener mListener; private ProgressDialog mConnectionDialog; protected ViewHandler mViewHandler; private List<BluetoothGattService> mServices; private final static int CONNECTION_DIALOG = 1; private final static int SHOW_CONNECTION_DIALOG = 0x1000; private final static int DISMISS_CONNECTION_DIALOG = 0x1001; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aio); BLEDevice device = getIntent().getParcelableExtra(Bluebit.CHOSEN_DEVICE); mDevice = device.getDevice(); mServices = new ArrayList<BluetoothGattService>(); mViewHandler = new ViewHandler(); mListener = new GattListener(); } @Override protected void onActivityResult(int request, int result, Intent data) { } @Override protected void onResume() { super.onResume(); GattProxy proxy = GattProxy.get(this); proxy.addListener(mListener); proxy.retrieveGatt(mListener); } @Override protected void onPause() { super.onPause(); GattProxy proxy = GattProxy.get(this); proxy.rmListener(mListener); } @Override protected Dialog onCreateDialog(int id, Bundle args) { /*FIXME: this function is deprecated. */ if (id == CONNECTION_DIALOG) { mConnectionDialog = new ProgressDialog(this); mConnectionDialog.setMessage(this.getString(R.string.connecting)); mConnectionDialog.setCancelable(true); return mConnectionDialog; } return null; } private final static UUID SERVICE_AUTOMATION_IO = UUID.fromString("00001815-0000-1000-8000-00805f9b34fb"); private final static UUID CHAR_DI = UUID.fromString("00002a56-0000-1000-8000-00805f9b34fb"); private final static UUID CHAR_DO = UUID.fromString("00002a57-0000-1000-8000-00805f9b34fb"); public void onToggleClicked(View v) { ToggleButton toggle = (ToggleButton)v; Log.d("is checked:" + toggle.isChecked()); BluetoothGattService srv = mGatt.getService(mDevice, SERVICE_AUTOMATION_IO); if (srv == null) { Log.d("Get Service failed"); } else { dumpService(srv); } } private void dumpService(BluetoothGattService srv) { BluetoothGattCharacteristic ch = srv.getCharacteristic(CHAR_DO); if (ch == null) { Log.d("get char failed"); } else { byte ctrl = (byte)(int)(Math.random() * 2); byte[] value = {(byte)0xfc, (byte)0xfe}; value[0] += ctrl; value[1] += ctrl; ch.setValue(value); boolean r = mGatt.writeCharacteristic(ch); Log.d(String.format("ctrl:%1x,%02x %02x, %b", ctrl, value[0], value[1], r)); } } public void updateView(int tag, Bundle info) { if (info == null) { info = new Bundle(); } mViewHandler.removeMessages(tag); Message msg = mViewHandler.obtainMessage(tag); msg.what = tag; msg.setData(info); mViewHandler.sendMessage(msg); } class ViewHandler extends Handler { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); if (bundle == null) { Log.d("ViewHandler handled a message without information"); return; } int tag = msg.what; if (tag == SHOW_CONNECTION_DIALOG) { showDialog(CONNECTION_DIALOG); } else if (tag == DISMISS_CONNECTION_DIALOG) { if (mConnectionDialog != null && mConnectionDialog.isShowing()) { dismissDialog(CONNECTION_DIALOG); } } } } private void onConnected() { List<BluetoothGattService> list = mGatt.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("no services, do discovery"); mGatt.discoverServices(mDevice); } else { onDiscovered(); } } private void onDiscovered() { updateView(DISMISS_CONNECTION_DIALOG, null); mServices.clear(); mServices.addAll(mGatt.getServices(mDevice)); Log.d("found services:" + mServices.size()); } class GattListener extends GattProxy.ListenerHelper { GattListener() { super("ActivityAIO"); } @Override public void onRetrievedGatt(BluetoothGatt gatt) { Log.d(String.format("onRetrievedGatt")); mGatt = gatt; int conn = mGatt.getConnectionState(mDevice); if (conn == BluetoothProfile.STATE_DISCONNECTED) { Log.d("disconnected, connecting to device"); updateView(SHOW_CONNECTION_DIALOG, null); mGatt.connect(mDevice, true); } else { Log.d("already connected"); onConnected(); } } @Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { onConnected(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { updateView(SHOW_CONNECTION_DIALOG, null); } } @Override public void onServicesDiscovered(BluetoothDevice device, int status) { onDiscovered(); } public void onCharacteristicRead(BluetoothGattCharacteristic charac, int status) { Log.d("read char, uuid=" + charac.getUuid().toString()); byte[] value = charac.getValue(); Log.d("get value, byte length:" + value.length); for (int i = 0; i < value.length; i++) { Log.d("[" + i + "]" + Byte.toString(value[i])); } } } }
src/com/issc/ui/ActivityAIO.java
// vim: et sw=4 sts=4 tabstop=4 package com.issc.ui; import com.issc.Bluebit; import com.issc.data.BLEDevice; import com.issc.impl.GattProxy; import com.issc.R; import com.issc.util.Log; import java.util.ArrayList; import java.util.Iterator; import java.util.UUID; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.ToggleButton; import com.samsung.android.sdk.bt.gatt.BluetoothGatt; import com.samsung.android.sdk.bt.gatt.BluetoothGattAdapter; import com.samsung.android.sdk.bt.gatt.BluetoothGattCallback; import com.samsung.android.sdk.bt.gatt.BluetoothGattCharacteristic; import com.samsung.android.sdk.bt.gatt.BluetoothGattService; public class ActivityAIO extends Activity { private BluetoothDevice mDevice; private BluetoothGatt mGatt; private GattProxy.Listener mListener; private ProgressDialog mConnectionDialog; protected ViewHandler mViewHandler; private List<BluetoothGattService> mServices; private final static int CONNECTION_DIALOG = 1; private final static int SHOW_CONNECTION_DIALOG = 0x1000; private final static int DISMISS_CONNECTION_DIALOG = 0x1001; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_aio); BLEDevice device = getIntent().getParcelableExtra(Bluebit.CHOSEN_DEVICE); mDevice = device.getDevice(); mServices = new ArrayList<BluetoothGattService>(); mViewHandler = new ViewHandler(); mListener = new GattListener(); } @Override protected void onActivityResult(int request, int result, Intent data) { } @Override protected void onResume() { super.onResume(); GattProxy proxy = GattProxy.get(this); proxy.addListener(mListener); proxy.retrieveGatt(mListener); } @Override protected void onPause() { super.onPause(); GattProxy proxy = GattProxy.get(this); proxy.rmListener(mListener); } @Override protected Dialog onCreateDialog(int id, Bundle args) { /*FIXME: this function is deprecated. */ if (id == CONNECTION_DIALOG) { mConnectionDialog = new ProgressDialog(this); mConnectionDialog.setMessage(this.getString(R.string.connecting)); mConnectionDialog.setCancelable(true); return mConnectionDialog; } return null; } private final static UUID SERVICE_AUTOMATION_IO = UUID.fromString("00001815-0000-1000-8000-00805f9b34fb"); private final static UUID CHAR_DI = UUID.fromString("00002a56-0000-1000-8000-00805f9b34fb"); private final static UUID CHAR_DO = UUID.fromString("00002a57-0000-1000-8000-00805f9b34fb"); public void onToggleClicked(View v) { ToggleButton toggle = (ToggleButton)v; Log.d("is checked:" + toggle.isChecked()); BluetoothGattService srv = mGatt.getService(mDevice, SERVICE_AUTOMATION_IO); if (srv == null) { Log.d("Get Service failed"); } else { dumpService(srv); } } private void dumpService(BluetoothGattService srv) { BluetoothGattCharacteristic ch = srv.getCharacteristic(CHAR_DO); if (ch == null) { Log.d("get char failed"); } else { byte ctrl = (byte)(int)(Math.random() * 2); byte[] value = {(byte)0xfc, (byte)0xfe}; value[0] += ctrl; value[1] += ctrl; ch.setValue(value); boolean r = mGatt.writeCharacteristic(ch); Log.d(String.format("ctrl:%1x,%02x %02x, %b", ctrl, value[0], value[1], r)); } } public void updateView(int tag, Bundle info) { if (info == null) { info = new Bundle(); } mViewHandler.removeMessages(tag); Message msg = mViewHandler.obtainMessage(tag); msg.what = tag; msg.setData(info); mViewHandler.sendMessage(msg); } class ViewHandler extends Handler { public void handleMessage(Message msg) { Bundle bundle = msg.getData(); if (bundle == null) { Log.d("ViewHandler handled a message without information"); return; } int tag = msg.what; if (tag == SHOW_CONNECTION_DIALOG) { showDialog(CONNECTION_DIALOG); } else if (tag == DISMISS_CONNECTION_DIALOG) { dismissDialog(CONNECTION_DIALOG); } } } private void onConnected() { List<BluetoothGattService> list = mGatt.getServices(mDevice); if ((list == null) || (list.size() == 0)) { Log.d("no services, do discovery"); mGatt.discoverServices(mDevice); } else { onDiscovered(); } } private void onDiscovered() { updateView(DISMISS_CONNECTION_DIALOG, null); mServices.clear(); mServices.addAll(mGatt.getServices(mDevice)); Log.d("found services:" + mServices.size()); } class GattListener extends GattProxy.ListenerHelper { GattListener() { super("ActivityAIO"); } @Override public void onRetrievedGatt(BluetoothGatt gatt) { Log.d(String.format("onRetrievedGatt")); mGatt = gatt; int conn = mGatt.getConnectionState(mDevice); if (conn == BluetoothProfile.STATE_DISCONNECTED) { Log.d("disconnected, connecting to device"); updateView(SHOW_CONNECTION_DIALOG, null); mGatt.connect(mDevice, true); } else { Log.d("already connected"); onConnected(); } } @Override public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { onConnected(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { updateView(SHOW_CONNECTION_DIALOG, null); } } @Override public void onServicesDiscovered(BluetoothDevice device, int status) { onDiscovered(); } public void onCharacteristicRead(BluetoothGattCharacteristic charac, int status) { Log.d("read char, uuid=" + charac.getUuid().toString()); byte[] value = charac.getValue(); Log.d("get value, byte length:" + value.length); for (int i = 0; i < value.length; i++) { Log.d("[" + i + "]" + Byte.toString(value[i])); } } } }
ui: Fix dialog issue if the connection is already exist, the dialog might not be initialized.
src/com/issc/ui/ActivityAIO.java
ui: Fix dialog issue
Java
apache-2.0
dd888c92269d16fd92177b4ae14394a0014bff5d
0
louishust/incubator-ignite,apacheignite/ignite,shroman/ignite,a1vanov/ignite,abhishek-ch/incubator-ignite,svladykin/ignite,andrey-kuznetsov/ignite,voipp/ignite,StalkXT/ignite,shroman/ignite,ptupitsyn/ignite,dream-x/ignite,ryanzz/ignite,agoncharuk/ignite,shroman/ignite,shurun19851206/ignite,SomeFire/ignite,ilantukh/ignite,DoudTechData/ignite,sk0x50/ignite,irudyak/ignite,ptupitsyn/ignite,vsuslov/incubator-ignite,vadopolski/ignite,psadusumilli/ignite,kromulan/ignite,adeelmahmood/ignite,gridgain/apache-ignite,agura/incubator-ignite,ascherbakoff/ignite,sk0x50/ignite,alexzaitzev/ignite,vsuslov/incubator-ignite,SharplEr/ignite,agoncharuk/ignite,svladykin/ignite,kromulan/ignite,xtern/ignite,murador/ignite,leveyj/ignite,SharplEr/ignite,gridgain/apache-ignite,mcherkasov/ignite,zzcclp/ignite,leveyj/ignite,agoncharuk/ignite,avinogradovgg/ignite,ptupitsyn/ignite,samaitra/ignite,leveyj/ignite,nizhikov/ignite,avinogradovgg/ignite,agura/incubator-ignite,afinka77/ignite,vadopolski/ignite,samaitra/ignite,samaitra/ignite,dlnufox/ignite,afinka77/ignite,dlnufox/ignite,apache/ignite,vsuslov/incubator-ignite,psadusumilli/ignite,vsisko/incubator-ignite,BiryukovVA/ignite,agoncharuk/ignite,vsuslov/incubator-ignite,abhishek-ch/incubator-ignite,shurun19851206/ignite,SomeFire/ignite,zzcclp/ignite,dream-x/ignite,sylentprayer/ignite,ascherbakoff/ignite,WilliamDo/ignite,louishust/incubator-ignite,voipp/ignite,amirakhmedov/ignite,amirakhmedov/ignite,ilantukh/ignite,SomeFire/ignite,amirakhmedov/ignite,NSAmelchev/ignite,wmz7year/ignite,nizhikov/ignite,StalkXT/ignite,pperalta/ignite,andrey-kuznetsov/ignite,tkpanther/ignite,psadusumilli/ignite,louishust/incubator-ignite,DoudTechData/ignite,dream-x/ignite,ashutakGG/incubator-ignite,dmagda/incubator-ignite,leveyj/ignite,StalkXT/ignite,vldpyatkov/ignite,wmz7year/ignite,afinka77/ignite,sk0x50/ignite,nivanov/ignite,NSAmelchev/ignite,kidaa/incubator-ignite,vldpyatkov/ignite,pperalta/ignite,psadusumilli/ignite,tkpanther/ignite,murador/ignite,zzcclp/ignite,pperalta/ignite,nivanov/ignite,nizhikov/ignite,WilliamDo/ignite,samaitra/ignite,StalkXT/ignite,nizhikov/ignite,daradurvs/ignite,f7753/ignite,vadopolski/ignite,ntikhonov/ignite,daradurvs/ignite,WilliamDo/ignite,svladykin/ignite,andrey-kuznetsov/ignite,zzcclp/ignite,rfqu/ignite,nizhikov/ignite,VladimirErshov/ignite,nivanov/ignite,afinka77/ignite,ascherbakoff/ignite,samaitra/ignite,andrey-kuznetsov/ignite,alexzaitzev/ignite,NSAmelchev/ignite,gargvish/ignite,iveselovskiy/ignite,StalkXT/ignite,wmz7year/ignite,kromulan/ignite,irudyak/ignite,psadusumilli/ignite,NSAmelchev/ignite,endian675/ignite,ryanzz/ignite,xtern/ignite,adeelmahmood/ignite,apache/ignite,alexzaitzev/ignite,rfqu/ignite,pperalta/ignite,gargvish/ignite,rfqu/ignite,chandresh-pancholi/ignite,amirakhmedov/ignite,apacheignite/ignite,thuTom/ignite,thuTom/ignite,kidaa/incubator-ignite,VladimirErshov/ignite,apache/ignite,vldpyatkov/ignite,leveyj/ignite,vladisav/ignite,iveselovskiy/ignite,amirakhmedov/ignite,WilliamDo/ignite,daradurvs/ignite,dlnufox/ignite,StalkXT/ignite,mcherkasov/ignite,pperalta/ignite,irudyak/ignite,murador/ignite,irudyak/ignite,dlnufox/ignite,f7753/ignite,arijitt/incubator-ignite,svladykin/ignite,vadopolski/ignite,kidaa/incubator-ignite,BiryukovVA/ignite,ptupitsyn/ignite,f7753/ignite,voipp/ignite,daradurvs/ignite,shroman/ignite,pperalta/ignite,arijitt/incubator-ignite,dlnufox/ignite,dmagda/incubator-ignite,shurun19851206/ignite,daradurvs/ignite,agoncharuk/ignite,alexzaitzev/ignite,avinogradovgg/ignite,a1vanov/ignite,irudyak/ignite,alexzaitzev/ignite,agura/incubator-ignite,shroman/ignite,thuTom/ignite,BiryukovVA/ignite,apache/ignite,dmagda/incubator-ignite,f7753/ignite,BiryukovVA/ignite,ashutakGG/incubator-ignite,nizhikov/ignite,adeelmahmood/ignite,vsuslov/incubator-ignite,chandresh-pancholi/ignite,samaitra/ignite,sk0x50/ignite,sylentprayer/ignite,vadopolski/ignite,shurun19851206/ignite,leveyj/ignite,sylentprayer/ignite,dream-x/ignite,voipp/ignite,pperalta/ignite,dmagda/incubator-ignite,xtern/ignite,SharplEr/ignite,voipp/ignite,iveselovskiy/ignite,vladisav/ignite,zzcclp/ignite,andrey-kuznetsov/ignite,vldpyatkov/ignite,avinogradovgg/ignite,louishust/incubator-ignite,mcherkasov/ignite,ilantukh/ignite,afinka77/ignite,vsisko/incubator-ignite,vsisko/incubator-ignite,irudyak/ignite,svladykin/ignite,rfqu/ignite,tkpanther/ignite,akuznetsov-gridgain/ignite,zzcclp/ignite,rfqu/ignite,shroman/ignite,SomeFire/ignite,svladykin/ignite,shroman/ignite,murador/ignite,DoudTechData/ignite,vsuslov/incubator-ignite,WilliamDo/ignite,chandresh-pancholi/ignite,andrey-kuznetsov/ignite,dlnufox/ignite,adeelmahmood/ignite,agura/incubator-ignite,ryanzz/ignite,NSAmelchev/ignite,dream-x/ignite,gargvish/ignite,vladisav/ignite,svladykin/ignite,thuTom/ignite,ntikhonov/ignite,f7753/ignite,agura/incubator-ignite,shurun19851206/ignite,shurun19851206/ignite,amirakhmedov/ignite,nivanov/ignite,ilantukh/ignite,daradurvs/ignite,murador/ignite,dream-x/ignite,arijitt/incubator-ignite,agoncharuk/ignite,VladimirErshov/ignite,gargvish/ignite,amirakhmedov/ignite,voipp/ignite,ntikhonov/ignite,tkpanther/ignite,ilantukh/ignite,avinogradovgg/ignite,apacheignite/ignite,thuTom/ignite,vadopolski/ignite,ascherbakoff/ignite,voipp/ignite,dmagda/incubator-ignite,samaitra/ignite,WilliamDo/ignite,agoncharuk/ignite,gridgain/apache-ignite,ryanzz/ignite,sk0x50/ignite,mcherkasov/ignite,vladisav/ignite,thuTom/ignite,sk0x50/ignite,ntikhonov/ignite,zzcclp/ignite,SharplEr/ignite,vldpyatkov/ignite,apacheignite/ignite,SharplEr/ignite,apache/ignite,voipp/ignite,leveyj/ignite,vldpyatkov/ignite,vldpyatkov/ignite,abhishek-ch/incubator-ignite,a1vanov/ignite,ptupitsyn/ignite,daradurvs/ignite,ptupitsyn/ignite,xtern/ignite,alexzaitzev/ignite,StalkXT/ignite,kidaa/incubator-ignite,louishust/incubator-ignite,akuznetsov-gridgain/ignite,ptupitsyn/ignite,louishust/incubator-ignite,vsisko/incubator-ignite,iveselovskiy/ignite,psadusumilli/ignite,SomeFire/ignite,ascherbakoff/ignite,VladimirErshov/ignite,kromulan/ignite,alexzaitzev/ignite,agura/incubator-ignite,sk0x50/ignite,ntikhonov/ignite,wmz7year/ignite,chandresh-pancholi/ignite,agoncharuk/ignite,SharplEr/ignite,nizhikov/ignite,sk0x50/ignite,nivanov/ignite,samaitra/ignite,kromulan/ignite,sk0x50/ignite,murador/ignite,chandresh-pancholi/ignite,ryanzz/ignite,samaitra/ignite,a1vanov/ignite,SomeFire/ignite,rfqu/ignite,ashutakGG/incubator-ignite,xtern/ignite,BiryukovVA/ignite,akuznetsov-gridgain/ignite,SomeFire/ignite,vsisko/incubator-ignite,DoudTechData/ignite,sylentprayer/ignite,gridgain/apache-ignite,endian675/ignite,tkpanther/ignite,NSAmelchev/ignite,alexzaitzev/ignite,afinka77/ignite,vsisko/incubator-ignite,amirakhmedov/ignite,endian675/ignite,xtern/ignite,vladisav/ignite,VladimirErshov/ignite,BiryukovVA/ignite,amirakhmedov/ignite,mcherkasov/ignite,apache/ignite,nizhikov/ignite,f7753/ignite,rfqu/ignite,chandresh-pancholi/ignite,abhishek-ch/incubator-ignite,VladimirErshov/ignite,gridgain/apache-ignite,zzcclp/ignite,ptupitsyn/ignite,mcherkasov/ignite,nivanov/ignite,DoudTechData/ignite,sylentprayer/ignite,afinka77/ignite,shurun19851206/ignite,nizhikov/ignite,ascherbakoff/ignite,sylentprayer/ignite,iveselovskiy/ignite,adeelmahmood/ignite,gargvish/ignite,SomeFire/ignite,DoudTechData/ignite,leveyj/ignite,ilantukh/ignite,vldpyatkov/ignite,abhishek-ch/incubator-ignite,daradurvs/ignite,ilantukh/ignite,daradurvs/ignite,apacheignite/ignite,ptupitsyn/ignite,SomeFire/ignite,VladimirErshov/ignite,arijitt/incubator-ignite,ashutakGG/incubator-ignite,a1vanov/ignite,apacheignite/ignite,xtern/ignite,ntikhonov/ignite,irudyak/ignite,ilantukh/ignite,andrey-kuznetsov/ignite,andrey-kuznetsov/ignite,NSAmelchev/ignite,ntikhonov/ignite,shroman/ignite,arijitt/incubator-ignite,voipp/ignite,akuznetsov-gridgain/ignite,endian675/ignite,andrey-kuznetsov/ignite,adeelmahmood/ignite,ryanzz/ignite,BiryukovVA/ignite,dream-x/ignite,StalkXT/ignite,dlnufox/ignite,thuTom/ignite,WilliamDo/ignite,SharplEr/ignite,DoudTechData/ignite,endian675/ignite,BiryukovVA/ignite,alexzaitzev/ignite,shroman/ignite,dmagda/incubator-ignite,adeelmahmood/ignite,agura/incubator-ignite,mcherkasov/ignite,vadopolski/ignite,f7753/ignite,gargvish/ignite,samaitra/ignite,apache/ignite,chandresh-pancholi/ignite,pperalta/ignite,NSAmelchev/ignite,ptupitsyn/ignite,chandresh-pancholi/ignite,vsisko/incubator-ignite,SomeFire/ignite,agura/incubator-ignite,rfqu/ignite,ashutakGG/incubator-ignite,apacheignite/ignite,a1vanov/ignite,ascherbakoff/ignite,sylentprayer/ignite,kromulan/ignite,dream-x/ignite,nivanov/ignite,wmz7year/ignite,apache/ignite,irudyak/ignite,arijitt/incubator-ignite,irudyak/ignite,ilantukh/ignite,BiryukovVA/ignite,ryanzz/ignite,gridgain/apache-ignite,StalkXT/ignite,NSAmelchev/ignite,akuznetsov-gridgain/ignite,a1vanov/ignite,vladisav/ignite,wmz7year/ignite,xtern/ignite,BiryukovVA/ignite,kromulan/ignite,dmagda/incubator-ignite,kromulan/ignite,ryanzz/ignite,andrey-kuznetsov/ignite,endian675/ignite,tkpanther/ignite,vsisko/incubator-ignite,vladisav/ignite,SharplEr/ignite,ascherbakoff/ignite,xtern/ignite,psadusumilli/ignite,murador/ignite,ilantukh/ignite,ascherbakoff/ignite,shurun19851206/ignite,gargvish/ignite,ashutakGG/incubator-ignite,wmz7year/ignite,vladisav/ignite,daradurvs/ignite,SharplEr/ignite,endian675/ignite,apache/ignite,vadopolski/ignite,kidaa/incubator-ignite,iveselovskiy/ignite,WilliamDo/ignite,gargvish/ignite,sylentprayer/ignite,endian675/ignite,kidaa/incubator-ignite,thuTom/ignite,ntikhonov/ignite,wmz7year/ignite,tkpanther/ignite,f7753/ignite,mcherkasov/ignite,apacheignite/ignite,a1vanov/ignite,dlnufox/ignite,abhishek-ch/incubator-ignite,akuznetsov-gridgain/ignite,VladimirErshov/ignite,psadusumilli/ignite,gridgain/apache-ignite,shroman/ignite,dmagda/incubator-ignite,avinogradovgg/ignite,avinogradovgg/ignite,tkpanther/ignite,afinka77/ignite,adeelmahmood/ignite,murador/ignite,DoudTechData/ignite,nivanov/ignite,chandresh-pancholi/ignite
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.service; import org.gridgain.grid.*; import org.gridgain.grid.resources.*; import org.jetbrains.annotations.*; import java.io.*; import java.util.*; /** * Defines functionality necessary to deploy distributed services services on the grid. Instance of * {@code GridServices} is obtained from grid projection as follows: * <pre name="code" class="java"> * GridServices svcs = GridGain.grid().services(); * </pre> * With distributed services you can do the following: * <ul> * <li>Automatically deploy any number of service instances on the grid.</li> * <li> * Automatically deploy singletons, including <b>cluster-singleton</b>, * <b>node-singleton</b>, or <b>key-affinity-singleton</b>. * </li> * <li>Automatically deploy services on node start-up by specifying them in grid configuration.</li> * <li>Undeploy any of the deployed services.</li> * <li>Get information about service deployment topology within the grid.</li> * </ul> * <h1 class="header">Deployment From Configuration</h1> * In addition to deploying managed services by calling any of the provided {@code deploy(...)} methods, * you can also automatically deploy services on startup by specifying them in {@link GridConfiguration} * like so: * <pre name="code" class="java"> * GridConfiguration gridCfg = new GridConfiguration(); * * GridServiceConfiguration svcCfg1 = new GridServiceConfiguration(); * * // Cluster-wide singleton configuration. * svcCfg1.setName("myClusterSingletonService"); * svcCfg1.setMaxPerNodeCount(1); * svcCfg1.setTotalCount(1); * svcCfg1.setService(new MyClusterSingletonService()); * * GridServiceConfiguration svcCfg2 = new GridServiceConfiguration(); * * // Per-node singleton configuration. * svcCfg2.setName("myNodeSingletonService"); * svcCfg2.setMaxPerNodeCount(1); * svcCfg2.setService(new MyNodeSingletonService()); * * gridCfg.setServiceConfiguration(svcCfg1, svcCfg2); * ... * GridGain.start(gridCfg); * </pre> * <h1 class="header">Load Balancing</h1> * In all cases, other than singleton service deployment, GridGain will automatically make sure that * an about equal number of services are deployed on each node within the grid. Whenever cluster topology * changes, GridGain will re-evaluate service deployments and may re-deploy an already deployed service * on another node for better load balancing. * <h1 class="header">Fault Tolerance</h1> * GridGain guarantees that services are deployed according to specified configuration regardless * of any topology changes, including node crashes. * <h1 class="header">Resource Injection</h1> * All distributed services can be injected with * grid resources. Both, field and method based injections are supported. The following grid * resources can be injected: * <ul> * <li>{@link GridInstanceResource}</li> * <li>{@link GridLoggerResource}</li> * <li>{@link GridHomeResource}</li> * <li>{@link GridExecutorServiceResource}</li> * <li>{@link GridLocalNodeIdResource}</li> * <li>{@link GridMBeanServerResource}</li> * <li>{@link GridMarshallerResource}</li> * <li>{@link GridSpringApplicationContextResource}</li> * <li>{@link GridSpringResource}</li> * </ul> * Refer to corresponding resource documentation for more information. * <h1 class="header">Service Example</h1> * Here is an example of how an distributed service may be implemented and deployed: * <pre name="code" class="java"> * // Simple service implementation. * public class MyGridService implements GridService { * ... * // Example of grid resource injection. All resources are optional. * // You should inject resources only as needed. * &#64;GridInstanceResource * private Grid grid; * ... * &#64;Override public void cancel(GridServiceContext ctx) { * // No-op. * } * * &#64;Override public void execute(GridServiceContext ctx) { * // Loop until service is cancelled. * while (!ctx.isCancelled()) { * // Do something. * ... * } * } * } * ... * GridServices svcs = grid.services(); * * GridFuture&lt;?&gt; fut = svcs.deployClusterSingleton("mySingleton", new MyGridService()); * * // Wait for deployment to complete. * fut.get(); * </pre> */ public interface GridServices extends Serializable { /** * Gets grid projection to which this {@code GridCompute} instance belongs. * * @return Grid projection to which this {@code GridCompute} instance belongs. */ public GridProjection projection(); /** * Deploys a cluster-wide singleton service. GridGain will guarantee that there is always * one instance of the service in the cluster. In case if grid node on which the service * was deployed crashes or stops, GridGain will automatically redeploy it on another node. * However, if the node on which the service is deployed remains in topology, then the * service will always be deployed on that node only, regardless of topology changes. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a singleton service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to calling * {@link #deployMultiple(String, GridService, int, int) deployMultiple(name, svc, 1, 1)} method. * * @param name Service name. * @param svc Service instance. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployClusterSingleton(String name, GridService svc); /** * Deploys a per-node singleton service. GridGain will guarantee that there is always * one instance of the service running on each node. Whenever new nodes are started * within this grid projection, GridGain will automatically deploy one instance of * the service on every new node. * <p> * This method is analogous to calling * {@link #deployMultiple(String, GridService, int, int) deployMultiple(name, svc, 0, 1)} method. * * @param name Service name. * @param svc Service instance. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployNodeSingleton(String name, GridService svc); /** * Deploys one instance of this service on the primary node for a given affinity key. * Whenever topology changes and primary node assignment changes, GridGain will always * make sure that the service is undeployed on the previous primary node and deployed * on the new primary node. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to the invocation of {@link #deploy(GridServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setCacheName(cacheName); * cfg.setAffinityKey(affKey); * cfg.setTotalCount(1); * cfg.setMaxPerNodeCount(1); * * grid.services().deploy(cfg); * </pre> * * @param name Service name. * @param svc Service instance. * @param cacheName Name of the cache on which affinity for key should be calculated, {@code null} for * default cache. * @param affKey Affinity cache key. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployKeyAffinitySingleton(String name, GridService svc, @Nullable String cacheName, Object affKey); /** * Deploys multiple instances of the service on the grid. GridGain will deploy a * maximum amount of services equal to {@code 'totalCnt'} parameter making sure that * there are no more than {@code 'maxPerNodeCnt'} service instances running * on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * This method is analogous to the invocation of {@link #deploy(GridServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(totalCnt); * cfg.setMaxPerNodeCount(maxPerNodeCnt); * * grid.services().deploy(cfg); * </pre> * * @param name Service name. * @param svc Service instance. * @param totalCnt Maximum number of deployed services in the grid, {@code 0} for unlimited. * @param maxPerNodeCnt Maximum number of deployed services on each node, {@code 0} for unlimited. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployMultiple(String name, GridService svc, int totalCnt, int maxPerNodeCnt); /** * Deploys multiple instances of the service on the grid according to provided * configuration. GridGain will deploy a maximum amount of services equal to * {@link GridServiceConfiguration#getTotalCount() cfg.getTotalCount()} parameter * making sure that there are no more than {@link GridServiceConfiguration#getMaxPerNodeCount() cfg.getMaxPerNodeCount()} * service instances running on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * If {@link GridServiceConfiguration#getAffinityKey() cfg.getAffinityKey()} is not {@code null}, then GridGain * will deploy the service on the primary node for given affinity key. The affinity will be calculated * on the cache with {@link GridServiceConfiguration#getCacheName() cfg.getCacheName()} name. * <p> * If {@link GridServiceConfiguration#getNodeFilter() cfg.getNodeFilter()} is not {@code null}, then * GridGain will deploy service on all grid nodes for which the provided filter evaluates to {@code true}. * The node filter will be checked in addition to the underlying grid projection filter, or the * whole grid, if the underlying grid projection includes all grid nodes. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * Here is an example of creating service deployment configuration: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(0); // Unlimited. * cfg.setMaxPerNodeCount(2); // Deploy 2 instances of service on each node. * * grid.services().deploy(cfg); * </pre> * * @param cfg Service configuration. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deploy(GridServiceConfiguration cfg); /** * Cancels service deployment. If a service with specified name was deployed on the grid, * then {@link GridService#cancel(GridServiceContext)} method will be called on it. * <p> * Note that GridGain cannot guarantee that the service exits from {@link GridService#execute(GridServiceContext)} * method whenever {@link GridService#cancel(GridServiceContext)} is called. It is up to the user to * make sure that the service code properly reacts to cancellations. * * @param name Name of service to cancel. * @return Future which completes whenever service is cancelled. Note that depending on user logic, * it may still take extra time for the service to finish execution, even after it was cancelled. */ public GridFuture<?> cancel(String name); /** * Cancels all deployed services. * * @return Future which completes whenever all deployed services are cancelled. Note that depending on user logic, * it may still take extra time for a service to finish execution, even after it was cancelled. */ public GridFuture<?> cancelAll(); /** * Gets metadata about all deployed services. * * @return Metadata about all deployed services. */ public Collection<GridServiceDescriptor> deployedServices(); }
modules/core/src/main/java/org/gridgain/grid/service/GridServices.java
/* @java.file.header */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ package org.gridgain.grid.service; import org.gridgain.grid.*; import org.gridgain.grid.resources.*; import org.jetbrains.annotations.*; import java.util.*; /** * Defines functionality necessary to deploy distributed services services on the grid. Instance of * {@code GridServices} is obtained from grid projection as follows: * <pre name="code" class="java"> * GridServices svcs = GridGain.grid().services(); * </pre> * With distributed services you can do the following: * <ul> * <li>Automatically deploy any number of service instances on the grid.</li> * <li> * Automatically deploy singletons, including <b>cluster-singleton</b>, * <b>node-singleton</b>, or <b>key-affinity-singleton</b>. * </li> * <li>Automatically deploy services on node start-up by specifying them in grid configuration.</li> * <li>Undeploy any of the deployed services.</li> * <li>Get information about service deployment topology within the grid.</li> * </ul> * <h1 class="header">Deployment From Configuration</h1> * In addition to deploying managed services by calling any of the provided {@code deploy(...)} methods, * you can also automatically deploy services on startup by specifying them in {@link GridConfiguration} * like so: * <pre name="code" class="java"> * GridConfiguration gridCfg = new GridConfiguration(); * * GridServiceConfiguration svcCfg1 = new GridServiceConfiguration(); * * // Cluster-wide singleton configuration. * svcCfg1.setName("myClusterSingletonService"); * svcCfg1.setMaxPerNodeCount(1); * svcCfg1.setTotalCount(1); * svcCfg1.setService(new MyClusterSingletonService()); * * GridServiceConfiguration svcCfg2 = new GridServiceConfiguration(); * * // Per-node singleton configuration. * svcCfg2.setName("myNodeSingletonService"); * svcCfg2.setMaxPerNodeCount(1); * svcCfg2.setService(new MyNodeSingletonService()); * * gridCfg.setServiceConfiguration(svcCfg1, svcCfg2); * ... * GridGain.start(gridCfg); * </pre> * <h1 class="header">Load Balancing</h1> * In all cases, other than singleton service deployment, GridGain will automatically make sure that * an about equal number of services are deployed on each node within the grid. Whenever cluster topology * changes, GridGain will re-evaluate service deployments and may re-deploy an already deployed service * on another node for better load balancing. * <h1 class="header">Fault Tolerance</h1> * GridGain guarantees that services are deployed according to specified configuration regardless * of any topology changes, including node crashes. * <h1 class="header">Resource Injection</h1> * All distributed services can be injected with * grid resources. Both, field and method based injections are supported. The following grid * resources can be injected: * <ul> * <li>{@link GridInstanceResource}</li> * <li>{@link GridLoggerResource}</li> * <li>{@link GridHomeResource}</li> * <li>{@link GridExecutorServiceResource}</li> * <li>{@link GridLocalNodeIdResource}</li> * <li>{@link GridMBeanServerResource}</li> * <li>{@link GridMarshallerResource}</li> * <li>{@link GridSpringApplicationContextResource}</li> * <li>{@link GridSpringResource}</li> * </ul> * Refer to corresponding resource documentation for more information. * <h1 class="header">Service Example</h1> * Here is an example of how an distributed service may be implemented and deployed: * <pre name="code" class="java"> * // Simple service implementation. * public class MyGridService implements GridService { * ... * // Example of grid resource injection. All resources are optional. * // You should inject resources only as needed. * &#64;GridInstanceResource * private Grid grid; * ... * &#64;Override public void cancel(GridServiceContext ctx) { * // No-op. * } * * &#64;Override public void execute(GridServiceContext ctx) { * // Loop until service is cancelled. * while (!ctx.isCancelled()) { * // Do something. * ... * } * } * } * ... * GridServices svcs = grid.services(); * * GridFuture&lt;?&gt; fut = svcs.deployClusterSingleton("mySingleton", new MyGridService()); * * // Wait for deployment to complete. * fut.get(); * </pre> */ public interface GridServices { /** * Gets grid projection to which this {@code GridCompute} instance belongs. * * @return Grid projection to which this {@code GridCompute} instance belongs. */ public GridProjection projection(); /** * Deploys a cluster-wide singleton service. GridGain will guarantee that there is always * one instance of the service in the cluster. In case if grid node on which the service * was deployed crashes or stops, GridGain will automatically redeploy it on another node. * However, if the node on which the service is deployed remains in topology, then the * service will always be deployed on that node only, regardless of topology changes. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a singleton service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to calling * {@link #deployMultiple(String, GridService, int, int) deployMultiple(name, svc, 1, 1)} method. * * @param name Service name. * @param svc Service instance. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployClusterSingleton(String name, GridService svc); /** * Deploys a per-node singleton service. GridGain will guarantee that there is always * one instance of the service running on each node. Whenever new nodes are started * within this grid projection, GridGain will automatically deploy one instance of * the service on every new node. * <p> * This method is analogous to calling * {@link #deployMultiple(String, GridService, int, int) deployMultiple(name, svc, 0, 1)} method. * * @param name Service name. * @param svc Service instance. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployNodeSingleton(String name, GridService svc); /** * Deploys one instance of this service on the primary node for a given affinity key. * Whenever topology changes and primary node assignment changes, GridGain will always * make sure that the service is undeployed on the previous primary node and deployed * on the new primary node. * <p> * Note that in case of topology changes, due to network delays, there may be a temporary situation * when a service instance will be active on more than one node (e.g. crash detection delay). * <p> * This method is analogous to the invocation of {@link #deploy(GridServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setCacheName(cacheName); * cfg.setAffinityKey(affKey); * cfg.setTotalCount(1); * cfg.setMaxPerNodeCount(1); * * grid.services().deploy(cfg); * </pre> * * @param name Service name. * @param svc Service instance. * @param cacheName Name of the cache on which affinity for key should be calculated, {@code null} for * default cache. * @param affKey Affinity cache key. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployKeyAffinitySingleton(String name, GridService svc, @Nullable String cacheName, Object affKey); /** * Deploys multiple instances of the service on the grid. GridGain will deploy a * maximum amount of services equal to {@code 'totalCnt'} parameter making sure that * there are no more than {@code 'maxPerNodeCnt'} service instances running * on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * This method is analogous to the invocation of {@link #deploy(GridServiceConfiguration)} method * as follows: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(totalCnt); * cfg.setMaxPerNodeCount(maxPerNodeCnt); * * grid.services().deploy(cfg); * </pre> * * @param name Service name. * @param svc Service instance. * @param totalCnt Maximum number of deployed services in the grid, {@code 0} for unlimited. * @param maxPerNodeCnt Maximum number of deployed services on each node, {@code 0} for unlimited. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deployMultiple(String name, GridService svc, int totalCnt, int maxPerNodeCnt); /** * Deploys multiple instances of the service on the grid according to provided * configuration. GridGain will deploy a maximum amount of services equal to * {@link GridServiceConfiguration#getTotalCount() cfg.getTotalCount()} parameter * making sure that there are no more than {@link GridServiceConfiguration#getMaxPerNodeCount() cfg.getMaxPerNodeCount()} * service instances running on each node. Whenever topology changes, GridGain will automatically rebalance * the deployed services within cluster to make sure that each node will end up with * about equal number of deployed instances whenever possible. * <p> * If {@link GridServiceConfiguration#getAffinityKey() cfg.getAffinityKey()} is not {@code null}, then GridGain * will deploy the service on the primary node for given affinity key. The affinity will be calculated * on the cache with {@link GridServiceConfiguration#getCacheName() cfg.getCacheName()} name. * <p> * If {@link GridServiceConfiguration#getNodeFilter() cfg.getNodeFilter()} is not {@code null}, then * GridGain will deploy service on all grid nodes for which the provided filter evaluates to {@code true}. * The node filter will be checked in addition to the underlying grid projection filter, or the * whole grid, if the underlying grid projection includes all grid nodes. * <p> * Note that at least one of {@code 'totalCnt'} or {@code 'maxPerNodeCnt'} parameters must have * value greater than {@code 0}. * <p> * Here is an example of creating service deployment configuration: * <pre name="code" class="java"> * GridServiceConfiguration cfg = new GridServiceConfiguration(); * * cfg.setName(name); * cfg.setService(svc); * cfg.setTotalCount(0); // Unlimited. * cfg.setMaxPerNodeCount(2); // Deploy 2 instances of service on each node. * * grid.services().deploy(cfg); * </pre> * * @param cfg Service configuration. * @return Future which completes upon completion of service deployment. */ public GridFuture<?> deploy(GridServiceConfiguration cfg); /** * Cancels service deployment. If a service with specified name was deployed on the grid, * then {@link GridService#cancel(GridServiceContext)} method will be called on it. * <p> * Note that GridGain cannot guarantee that the service exits from {@link GridService#execute(GridServiceContext)} * method whenever {@link GridService#cancel(GridServiceContext)} is called. It is up to the user to * make sure that the service code properly reacts to cancellations. * * @param name Name of service to cancel. * @return Future which completes whenever service is cancelled. Note that depending on user logic, * it may still take extra time for the service to finish execution, even after it was cancelled. */ public GridFuture<?> cancel(String name); /** * Cancels all deployed services. * * @return Future which completes whenever all deployed services are cancelled. Note that depending on user logic, * it may still take extra time for a service to finish execution, even after it was cancelled. */ public GridFuture<?> cancelAll(); /** * Gets metadata about all deployed services. * * @return Metadata about all deployed services. */ public Collection<GridServiceDescriptor> deployedServices(); }
GG-8687 - serializable is added to interfaces
modules/core/src/main/java/org/gridgain/grid/service/GridServices.java
GG-8687 - serializable is added to interfaces
Java
apache-2.0
71e1a184686dc4737ad7b9578010445bebae634f
0
dmourati/SimianArmy,dmourati/SimianArmy
// CHECKSTYLE IGNORE Javadoc /* * * Copyright 2012 Netflix, 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.netflix.simianarmy.chaos; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.TestMonkeyContext; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; public class TestChaosMonkeyContext extends TestMonkeyContext implements ChaosMonkey.Context { private static final Logger LOGGER = LoggerFactory.getLogger(TestChaosMonkeyContext.class); private final BasicConfiguration cfg; public TestChaosMonkeyContext() { super(ChaosMonkey.Type.CHAOS); cfg = new BasicConfiguration(new Properties()); } public TestChaosMonkeyContext(String propFile) { super(ChaosMonkey.Type.CHAOS); Properties props = new Properties(); try { InputStream is = TestChaosMonkeyContext.class.getResourceAsStream(propFile); try { props.load(is); } finally { is.close(); } } catch (Exception e) { LOGGER.error("Unable to load properties file " + propFile, e); } cfg = new BasicConfiguration(props); } @Override public MonkeyConfiguration configuration() { return cfg; } public static class TestInstanceGroup implements InstanceGroup { private final Enum type; private final String name; private final String region; private final List<String> instances = new ArrayList<String>(); public TestInstanceGroup(Enum type, String name, String region, String... instances) { this.type = type; this.name = name; this.region = region; for (String i : instances) { this.instances.add(i); } } @Override public Enum type() { return type; } @Override public String name() { return name; } @Override public String region() { return region; } @Override public List<String> instances() { return Collections.unmodifiableList(instances); } @Override public void addInstance(String ignored) { } public void deleteInstance(String id) { instances.remove(id); } @Override public InstanceGroup copyAs(String newName) { return new TestInstanceGroup(this.type, newName, this.region, instances().toString()); } } public enum CrawlerTypes { TYPE_A, TYPE_B, TYPE_C, TYPE_D }; @Override public ChaosCrawler chaosCrawler() { return new ChaosCrawler() { @Override public EnumSet<?> groupTypes() { return EnumSet.allOf(CrawlerTypes.class); } @Override public List<InstanceGroup> groups() { InstanceGroup gA0 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name0", "reg1", "0:i-123456780"); InstanceGroup gA1 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name1", "reg1", "1:i-123456781"); InstanceGroup gB2 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name2", "reg1", "2:i-123456782"); InstanceGroup gB3 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name3", "reg1", "3:i-123456783"); InstanceGroup gC1 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name4", "reg1", "3:i-123456784", "3:i-123456785"); InstanceGroup gC2 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name5", "reg1", "3:i-123456786", "3:i-123456787"); InstanceGroup gD0 = new TestInstanceGroup(CrawlerTypes.TYPE_D, "new-group-TestGroup1-XXXXXXXXX", "reg1", "3:i-123456786", "3:i-123456787"); return Arrays.asList(gA0, gA1, gB2, gB3, gC1, gC2, gD0); } @Override public List<InstanceGroup> groups(String... names) { Map<String, InstanceGroup> nameToGroup = new HashMap<String, InstanceGroup>(); for (InstanceGroup ig : groups()) { nameToGroup.put(ig.name(), ig); } List<InstanceGroup> list = new LinkedList<InstanceGroup>(); for (String name : names) { InstanceGroup ig = nameToGroup.get(name); if (ig == null) { continue; } for (String instanceId : terminated) { // Remove terminated instances from crawler list TestInstanceGroup testIg = (TestInstanceGroup) ig; testIg.deleteInstance(instanceId); } list.add(ig); } return list; } }; } private final List<InstanceGroup> selectedOn = new LinkedList<InstanceGroup>(); public List<InstanceGroup> selectedOn() { return selectedOn; } @Override public ChaosInstanceSelector chaosInstanceSelector() { return new BasicChaosInstanceSelector() { @Override public Collection<String> select(InstanceGroup group, double probability) { selectedOn.add(group); return super.select(group, probability); } }; } private final List<String> terminated = new LinkedList<String>(); public List<String> terminated() { return terminated; } private final List<String> stopped = new LinkedList<String>(); public List<String> stopped() { return stopped; } @Override public CloudClient cloudClient() { return new CloudClient() { @Override public void terminateInstance(String instanceId) { terminated.add(instanceId); } @Override public void stopInstance(String instanceId) { stopped.add(instanceId); } @Override public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) { } @Override public void deleteAutoScalingGroup(String asgName) { } @Override public void deleteVolume(String volumeId) { } @Override public void deleteSnapshot(String snapshotId) { } @Override public void deleteImage(String imageId) { } @Override public void deleteLaunchConfiguration(String launchConfigName) { } }; } private int groupNotified = 0; private int globallyNotified = 0; @Override public ChaosEmailNotifier chaosEmailNotifier() { return new ChaosEmailNotifier(null) { @Override public String getSourceAddress(String to) { return "[email protected]"; } @Override public String[] getCcAddresses(String to) { return new String[] {}; } @Override public String buildEmailSubject(String to) { return String.format("Testing Chaos termination notification for %s", to); } @Override public void sendTerminationNotification(InstanceGroup group, String instance) { groupNotified++; } @Override public void sendTerminationGlobalNotification(InstanceGroup group, String instance) { globallyNotified++; } }; } public int getNotified() { return groupNotified; } public int getGloballyNotified() { return globallyNotified; } }
src/test/java/com/netflix/simianarmy/chaos/TestChaosMonkeyContext.java
// CHECKSTYLE IGNORE Javadoc /* * * Copyright 2012 Netflix, 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.netflix.simianarmy.chaos; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.simianarmy.CloudClient; import com.netflix.simianarmy.MonkeyConfiguration; import com.netflix.simianarmy.TestMonkeyContext; import com.netflix.simianarmy.basic.BasicConfiguration; import com.netflix.simianarmy.basic.chaos.BasicChaosInstanceSelector; import com.netflix.simianarmy.chaos.ChaosCrawler.InstanceGroup; public class TestChaosMonkeyContext extends TestMonkeyContext implements ChaosMonkey.Context { private static final Logger LOGGER = LoggerFactory.getLogger(TestChaosMonkeyContext.class); private final BasicConfiguration cfg; public TestChaosMonkeyContext() { super(ChaosMonkey.Type.CHAOS); cfg = new BasicConfiguration(new Properties()); } public TestChaosMonkeyContext(String propFile) { super(ChaosMonkey.Type.CHAOS); Properties props = new Properties(); try { InputStream is = TestChaosMonkeyContext.class.getResourceAsStream(propFile); try { props.load(is); } finally { is.close(); } } catch (Exception e) { LOGGER.error("Unable to load properties file " + propFile, e); } cfg = new BasicConfiguration(props); } @Override public MonkeyConfiguration configuration() { return cfg; } public static class TestInstanceGroup implements InstanceGroup { private final Enum type; private final String name; private final String region; private final List<String> instances = new ArrayList<String>(); public TestInstanceGroup(Enum type, String name, String region, String... instances) { this.type = type; this.name = name; this.region = region; for (String i : instances) { this.instances.add(i); } } @Override public Enum type() { return type; } @Override public String name() { return name; } @Override public String region() { return region; } @Override public List<String> instances() { return Collections.unmodifiableList(instances); } @Override public void addInstance(String ignored) { } public void deleteInstance(String id) { instances.remove(id); } @Override public InstanceGroup copyAs(String newName) { return new TestInstanceGroup(this.type, newName, this.region, instances().toString()); } } public enum CrawlerTypes { TYPE_A, TYPE_B, TYPE_C, TYPE_D }; @Override public ChaosCrawler chaosCrawler() { return new ChaosCrawler() { @Override public EnumSet<?> groupTypes() { return EnumSet.allOf(CrawlerTypes.class); } @Override public List<InstanceGroup> groups() { InstanceGroup gA0 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name0", "reg1", "0:i-123456780"); InstanceGroup gA1 = new TestInstanceGroup(CrawlerTypes.TYPE_A, "name1", "reg1", "1:i-123456781"); InstanceGroup gB2 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name2", "reg1", "2:i-123456782"); InstanceGroup gB3 = new TestInstanceGroup(CrawlerTypes.TYPE_B, "name3", "reg1", "3:i-123456783"); InstanceGroup gC1 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name4", "reg1", "3:i-123456784", "3:i-123456785"); InstanceGroup gC2 = new TestInstanceGroup(CrawlerTypes.TYPE_C, "name5", "reg1", "3:i-123456786", "3:i-123456787"); InstanceGroup gD0 = new TestInstanceGroup(CrawlerTypes.TYPE_D, "new-group-TestGroup1-XXXXXXXXX", "reg1", "3:i-123456786", "3:i-123456787"); return Arrays.asList(gA0, gA1, gB2, gB3, gC1, gC2, gD0); } @Override public List<InstanceGroup> groups(String... names) { Map<String, InstanceGroup> nameToGroup = new HashMap<String, InstanceGroup>(); for (InstanceGroup ig : groups()) { nameToGroup.put(ig.name(), ig); } List<InstanceGroup> list = new LinkedList<InstanceGroup>(); for (String name : names) { InstanceGroup ig = nameToGroup.get(name); if (ig == null) { continue; } for (String instanceId : terminated) { // Remove terminated instances from crawler list TestInstanceGroup testIg = (TestInstanceGroup) ig; testIg.deleteInstance(instanceId); } list.add(ig); } return list; } }; } private final List<InstanceGroup> selectedOn = new LinkedList<InstanceGroup>(); public List<InstanceGroup> selectedOn() { return selectedOn; } @Override public ChaosInstanceSelector chaosInstanceSelector() { return new BasicChaosInstanceSelector() { @Override public Collection<String> select(InstanceGroup group, double probability) { selectedOn.add(group); return super.select(group, probability); } }; } private final List<String> terminated = new LinkedList<String>(); public List<String> terminated() { return terminated; } @Override public CloudClient cloudClient() { return new CloudClient() { @Override public void terminateInstance(String instanceId) { terminated.add(instanceId); } @Override public void createTagsForResources(Map<String, String> keyValueMap, String... resourceIds) { } @Override public void deleteAutoScalingGroup(String asgName) { } @Override public void deleteVolume(String volumeId) { } @Override public void deleteSnapshot(String snapshotId) { } @Override public void deleteImage(String imageId) { } @Override public void deleteLaunchConfiguration(String launchConfigName) { } }; } private int groupNotified = 0; private int globallyNotified = 0; @Override public ChaosEmailNotifier chaosEmailNotifier() { return new ChaosEmailNotifier(null) { @Override public String getSourceAddress(String to) { return "[email protected]"; } @Override public String[] getCcAddresses(String to) { return new String[] {}; } @Override public String buildEmailSubject(String to) { return String.format("Testing Chaos termination notification for %s", to); } @Override public void sendTerminationNotification(InstanceGroup group, String instance) { groupNotified++; } @Override public void sendTerminationGlobalNotification(InstanceGroup group, String instance) { globallyNotified++; } }; } public int getNotified() { return groupNotified; } public int getGloballyNotified() { return globallyNotified; } }
add stop test cases
src/test/java/com/netflix/simianarmy/chaos/TestChaosMonkeyContext.java
add stop test cases