answer
stringlengths
17
10.2M
package com.yahoo.vespa.hosted.provision.maintenance; import com.google.inject.Inject; import com.yahoo.component.AbstractComponent; import com.yahoo.concurrent.maintenance.Maintainer; import com.yahoo.config.provision.Deployer; import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.HostLivenessTracker; import com.yahoo.config.provision.InfraDeployer; import com.yahoo.config.provision.Zone; import com.yahoo.jdisc.Metric; import com.yahoo.vespa.flags.FlagSource; import com.yahoo.vespa.hosted.provision.NodeRepository; import com.yahoo.vespa.hosted.provision.autoscale.MetricsFetcher; import com.yahoo.vespa.hosted.provision.autoscale.MetricsDb; import com.yahoo.vespa.hosted.provision.provisioning.ProvisionServiceProvider; import com.yahoo.vespa.orchestrator.Orchestrator; import com.yahoo.vespa.service.monitor.ServiceMonitor; import java.time.Duration; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * A component which sets up all the node repo maintenance jobs. * * @author bratseth */ public class NodeRepositoryMaintenance extends AbstractComponent { private final List<Maintainer> maintainers = new CopyOnWriteArrayList<>(); @SuppressWarnings("unused") @Inject public NodeRepositoryMaintenance(NodeRepository nodeRepository, Deployer deployer, InfraDeployer infraDeployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, Zone zone, Orchestrator orchestrator, Metric metric, ProvisionServiceProvider provisionServiceProvider, FlagSource flagSource, MetricsFetcher metricsFetcher, MetricsDb metricsDb) { DefaultTimes defaults = new DefaultTimes(zone, deployer); PeriodicApplicationMaintainer periodicApplicationMaintainer = new PeriodicApplicationMaintainer(deployer, metric, nodeRepository, defaults.redeployMaintainerInterval, defaults.periodicRedeployInterval, flagSource); InfrastructureProvisioner infrastructureProvisioner = new InfrastructureProvisioner(nodeRepository, infraDeployer, defaults.infrastructureProvisionInterval, metric); maintainers.add(periodicApplicationMaintainer); maintainers.add(infrastructureProvisioner); maintainers.add(new NodeFailer(deployer, nodeRepository, defaults.failGrace, defaults.nodeFailerInterval, orchestrator, defaults.throttlePolicy, metric)); maintainers.add(new NodeHealthTracker(hostLivenessTracker, serviceMonitor, nodeRepository, defaults.nodeFailureStatusUpdateInterval, metric)); maintainers.add(new OperatorChangeApplicationMaintainer(deployer, metric, nodeRepository, defaults.operatorChangeRedeployInterval)); maintainers.add(new ReservationExpirer(nodeRepository, defaults.reservationExpiry, metric)); maintainers.add(new RetiredExpirer(nodeRepository, orchestrator, deployer, metric, defaults.retiredInterval, defaults.retiredExpiry)); maintainers.add(new InactiveExpirer(nodeRepository, defaults.inactiveExpiry, metric)); maintainers.add(new FailedExpirer(nodeRepository, zone, defaults.failedExpirerInterval, metric)); maintainers.add(new DirtyExpirer(nodeRepository, defaults.dirtyExpiry, metric)); maintainers.add(new ProvisionedExpirer(nodeRepository, defaults.provisionedExpiry, metric)); maintainers.add(new NodeRebooter(nodeRepository, flagSource, metric)); maintainers.add(new MetricsReporter(nodeRepository, metric, orchestrator, serviceMonitor, periodicApplicationMaintainer::pendingDeployments, defaults.metricsInterval)); maintainers.add(new SpareCapacityMaintainer(deployer, nodeRepository, metric, defaults.spareCapacityMaintenanceInterval)); maintainers.add(new OsUpgradeActivator(nodeRepository, defaults.osUpgradeActivatorInterval, metric)); maintainers.add(new Rebalancer(deployer, nodeRepository, metric, defaults.rebalancerInterval)); maintainers.add(new NodeMetricsDbMaintainer(nodeRepository, metricsFetcher, metricsDb, defaults.nodeMetricsCollectionInterval, metric)); maintainers.add(new AutoscalingMaintainer(nodeRepository, metricsDb, deployer, metric, defaults.autoscalingInterval)); maintainers.add(new ScalingSuggestionsMaintainer(nodeRepository, metricsDb, defaults.scalingSuggestionsInterval, metric)); maintainers.add(new SwitchRebalancer(nodeRepository, defaults.switchRebalancerInterval, metric, deployer)); provisionServiceProvider.getLoadBalancerService(nodeRepository) .map(lbService -> new LoadBalancerExpirer(nodeRepository, defaults.loadBalancerExpirerInterval, lbService, metric)) .ifPresent(maintainers::add); provisionServiceProvider.getHostProvisioner() .map(hostProvisioner -> new DynamicProvisioningMaintainer(nodeRepository, defaults.dynamicProvisionerInterval, hostProvisioner, flagSource, metric)) .ifPresent(maintainers::add); // The DuperModel is filled with infrastructure applications by the infrastructure provisioner, so explicitly run that now infrastructureProvisioner.maintainButThrowOnException(); } @Override public void deconstruct() { maintainers.forEach(Maintainer::shutdown); maintainers.forEach(Maintainer::awaitShutdown); } private static class DefaultTimes { /** Minimum time to wait between deployments by periodic application maintainer*/ private final Duration periodicRedeployInterval; /** Time between each run of maintainer that does periodic redeployment */ private final Duration redeployMaintainerInterval; /** Applications are redeployed after manual operator changes within this time period */ private final Duration operatorChangeRedeployInterval; /** The time a node must be continuously unresponsive before it is failed */ private final Duration failGrace; private final Duration reservationExpiry; private final Duration inactiveExpiry; private final Duration retiredExpiry; private final Duration failedExpirerInterval; private final Duration dirtyExpiry; private final Duration provisionedExpiry; private final Duration spareCapacityMaintenanceInterval; private final Duration metricsInterval; private final Duration nodeFailerInterval; private final Duration nodeFailureStatusUpdateInterval; private final Duration retiredInterval; private final Duration infrastructureProvisionInterval; private final Duration loadBalancerExpirerInterval; private final Duration dynamicProvisionerInterval; private final Duration osUpgradeActivatorInterval; private final Duration rebalancerInterval; private final Duration nodeMetricsCollectionInterval; private final Duration autoscalingInterval; private final Duration scalingSuggestionsInterval; private final Duration switchRebalancerInterval; private final NodeFailer.ThrottlePolicy throttlePolicy; DefaultTimes(Zone zone, Deployer deployer) { autoscalingInterval = Duration.ofMinutes(15); dynamicProvisionerInterval = Duration.ofMinutes(5); failedExpirerInterval = Duration.ofMinutes(10); failGrace = Duration.ofMinutes(30); infrastructureProvisionInterval = Duration.ofMinutes(1); loadBalancerExpirerInterval = Duration.ofMinutes(5); metricsInterval = Duration.ofMinutes(1); nodeFailerInterval = Duration.ofMinutes(15); nodeFailureStatusUpdateInterval = Duration.ofMinutes(2); nodeMetricsCollectionInterval = Duration.ofMinutes(1); operatorChangeRedeployInterval = Duration.ofMinutes(3); // Vespa upgrade frequency is higher in CD so (de)activate OS upgrades more frequently as well osUpgradeActivatorInterval = zone.system().isCd() ? Duration.ofSeconds(30) : Duration.ofMinutes(5); periodicRedeployInterval = Duration.ofMinutes(60); provisionedExpiry = Duration.ofHours(4); rebalancerInterval = Duration.ofMinutes(120); redeployMaintainerInterval = Duration.ofMinutes(1); // Need to be long enough for deployment to be finished for all config model versions reservationExpiry = deployer.serverDeployTimeout(); scalingSuggestionsInterval = Duration.ofMinutes(31); spareCapacityMaintenanceInterval = Duration.ofMinutes(30); switchRebalancerInterval = Duration.ofHours(1); throttlePolicy = NodeFailer.ThrottlePolicy.hosted; retiredExpiry = Duration.ofDays(4); // give up migrating data after 4 days if (zone.environment() == Environment.prod && ! zone.system().isCd()) { inactiveExpiry = Duration.ofHours(4); // enough time for the application owner to discover and redeploy retiredInterval = Duration.ofMinutes(30); dirtyExpiry = Duration.ofHours(2); // enough time to clean the node } else { inactiveExpiry = Duration.ofSeconds(2); // support interactive wipe start over retiredInterval = Duration.ofMinutes(1); dirtyExpiry = Duration.ofMinutes(30); } } } }
package org.eclipse.mylyn.internal.jira.core.service.web; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.swing.text.html.HTML.Tag; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethodBase; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.FilePartSource; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.PartBase; import org.apache.commons.httpclient.methods.multipart.PartSource; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.eclipse.mylyn.internal.jira.core.model.Attachment; import org.eclipse.mylyn.internal.jira.core.model.Component; import org.eclipse.mylyn.internal.jira.core.model.CustomField; import org.eclipse.mylyn.internal.jira.core.model.Issue; import org.eclipse.mylyn.internal.jira.core.model.Version; import org.eclipse.mylyn.internal.jira.core.model.WebServerInfo; import org.eclipse.mylyn.internal.jira.core.service.JiraClient; import org.eclipse.mylyn.internal.jira.core.service.JiraException; import org.eclipse.mylyn.internal.jira.core.service.JiraRemoteException; import org.eclipse.mylyn.internal.jira.core.service.JiraRemoteMessageException; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.web.core.HtmlStreamTokenizer; import org.eclipse.mylyn.web.core.HtmlTag; import org.eclipse.mylyn.web.core.HtmlStreamTokenizer.Token; /** * TODO look at creation Operation classes to perform each of these actions TODO extract field names into constants * * @author Brock Janiczak * @author Steffen Pingel * @author Eugene Kuleshov */ public class JiraWebIssueService { public static final String DATE_FORMAT = "dd-MMM-yyyy"; //$NON-NLS-1$ public static final String DUE_DATE_FORMAT = "dd/MMM/yy"; //$NON-NLS-1$ private final JiraClient server; public JiraWebIssueService(JiraClient server) { this.server = server; } public void addCommentToIssue(final Issue issue, final String comment) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer rssUrlBuffer = new StringBuffer(baseUrl); rssUrlBuffer.append("/secure/AddComment.jspa"); PostMethod post = new PostMethod(rssUrlBuffer.toString()); post.setRequestHeader("Content-Type", s.getContentType()); post.addParameter("comment", comment); post.addParameter("commentLevel", ""); post.addParameter("id", issue.getId()); try { client.executeMethod(post); if (!s.expectRedirect(post, issue)) { handleErrorMessage(post); } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); } // TODO refactor common parameter configuration with advanceIssueWorkflow() method public void updateIssue(final Issue issue, final String comment) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer rssUrlBuffer = new StringBuffer(baseUrl); rssUrlBuffer.append("/secure/EditIssue.jspa"); PostMethod post = new PostMethod(rssUrlBuffer.toString()); post.setRequestHeader("Content-Type", s.getContentType()); post.addParameter("summary", issue.getSummary()); post.addParameter("issuetype", issue.getType().getId()); if (issue.getPriority() != null) { post.addParameter("priority", issue.getPriority().getId()); } if (issue.getDue() != null) { post.addParameter("duedate", new SimpleDateFormat(DUE_DATE_FORMAT, Locale.US).format(issue.getDue())); } else { post.addParameter("duedate", ""); } post.addParameter("timetracking", Long.toString(issue.getInitialEstimate() / 60) + "m"); Component[] components = issue.getComponents(); if (components != null) { if (components.length == 0) { post.addParameter("components", "-1"); } else { for (int i = 0; i < components.length; i++) { post.addParameter("components", components[i].getId()); } } } Version[] versions = issue.getReportedVersions(); if (versions != null) { if (versions.length == 0) { post.addParameter("versions", "-1"); } else { for (int i = 0; i < versions.length; i++) { post.addParameter("versions", versions[i].getId()); } } } Version[] fixVersions = issue.getFixVersions(); if (fixVersions != null) { if (fixVersions.length == 0) { post.addParameter("fixVersions", "-1"); } else { for (int i = 0; i < fixVersions.length; i++) { post.addParameter("fixVersions", fixVersions[i].getId()); } } } // TODO need to be able to choose unassigned and automatic if (issue.getAssignee() != null) { post.addParameter("assignee", issue.getAssignee()); } else { post.addParameter("assignee", "-1"); } post.addParameter("reporter", issue.getReporter()); post.addParameter("environment", issue.getEnvironment()); post.addParameter("description", issue.getDescription()); if (comment != null) { post.addParameter("comment", comment); } post.addParameter("commentLevel", ""); post.addParameter("id", issue.getId()); if (issue.getSecurityLevel() != null) { post.addParameter("security", issue.getSecurityLevel().getId()); } // custom fields for (CustomField customField : issue.getCustomFields()) { for (String value : customField.getValues()) { String key = customField.getKey(); if (key == null || (!key.startsWith("com.atlassian.jira.toolkit") && !key.startsWith("com.atlassian.jira.ext.charting"))) { post.addParameter(customField.getId(), value == null ? "" : value); } } } try { client.executeMethod(post); if (!s.expectRedirect(post, issue)) { handleErrorMessage(post); } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); } public void assignIssueTo(final Issue issue, final int assigneeType, final String user, final String comment) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer rssUrlBuffer = new StringBuffer(baseUrl); rssUrlBuffer.append("/secure/AssignIssue.jspa"); PostMethod post = new PostMethod(rssUrlBuffer.toString()); post.setRequestHeader("Content-Type", s.getContentType()); post.addParameter("assignee", getAssigneeParam(server, issue, assigneeType, user)); if (comment != null) { post.addParameter("comment", comment); } post.addParameter("commentLevel", ""); post.addParameter("id", issue.getId()); try { client.executeMethod(post); if (!s.expectRedirect(post, issue)) { handleErrorMessage(post); } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); } // public void advanceIssueWorkflow(final Issue issue, final String action, final Resolution resolution, // final Version[] fixVersions, final String comment, final int assigneeType, final String user) // throws JiraException { // JiraWebSession s = new JiraWebSession(server); // s.doInSession(new JiraWebSessionCallback() { // public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { // PostMethod post = new PostMethod(baseUrl + "/secure/CommentAssignIssue.jspa"); // post.setRequestHeader("Content-Type", s.getContentType()); // if (resolution != null) { // post.addParameter("resolution", resolution.getId()); // if (fixVersions == null || fixVersions.length == 0) { // post.addParameter("fixVersions", "-1"); // } else { // for (int i = 0; i < fixVersions.length; i++) { // post.addParameter("fixVersions", fixVersions[i].getId()); // post.addParameter("assignee", getAssigneeParam(server, issue, assigneeType, user)); // if (comment != null) { // post.addParameter("comment", comment); // post.addParameter("commentLevel", ""); // post.addParameter("action", action); // post.addParameter("id", issue.getId()); // try { // int result = client.executeMethod(post); // if (result != HttpStatus.SC_MOVED_TEMPORARILY) { // handleErrorMessage(post, result); // } catch (IOException e) { // throw new JiraException(e); // } finally { // post.releaseConnection(); public void advanceIssueWorkflow(final Issue issue, final String actionKey, final String comment, final String[] fields) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { PostMethod post = new PostMethod(baseUrl + "/secure/CommentAssignIssue.jspa"); post.setRequestHeader("Content-Type", s.getContentType()); post.addParameter("id", issue.getId()); post.addParameter("action", actionKey); // method.addParameter("assignee", issue.getAssignee()); if (comment != null) { post.addParameter("comment", comment); } post.addParameter("commentLevel", ""); for (String field : fields) { String[] values = issue.getFieldValues(field); if (values == null) { // method.addParameter(field, ""); } else { for (String value : values) { post.addParameter(field, value); } } } try { client.executeMethod(post); if (!s.expectRedirect(post, issue)) { handleErrorMessage(post); } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); } public void attachFile(final Issue issue, final String comment, final PartSource partSource, final String contentType) throws JiraException { attachFile(issue, comment, new FilePart("filename.1", partSource), contentType); } public void attachFile(final Issue issue, final String comment, final String filename, final byte[] contents, final String contentType) throws JiraException { attachFile(issue, comment, new FilePart("filename.1", new ByteArrayPartSource(filename, contents)), contentType); } public void attachFile(final Issue issue, final String comment, final String filename, final File file, final String contentType) throws JiraException { try { FilePartSource partSource = new FilePartSource(filename, file); attachFile(issue, comment, new FilePart("filename.1", partSource), contentType); } catch (FileNotFoundException e) { throw new JiraException(e); } } public void attachFile(final Issue issue, final String comment, final FilePart filePart, final String contentType) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer attachFileURLBuffer = new StringBuffer(baseUrl); attachFileURLBuffer.append("/secure/AttachFile.jspa"); PostMethod post = new PostMethod(attachFileURLBuffer.toString()); List<PartBase> parts = new ArrayList<PartBase>(); StringPart idPart = new StringPart("id", issue.getId()); StringPart commentLevelPart = new StringPart("commentLevel", ""); // The transfer encodings have to be removed for some reason // There is no need to send the content types for the strings, // as they should be in the correct format idPart.setTransferEncoding(null); idPart.setContentType(null); if (comment != null) { StringPart commentPart = new StringPart("comment", comment); commentPart.setTransferEncoding(null); commentPart.setContentType(null); parts.add(commentPart); } commentLevelPart.setTransferEncoding(null); commentLevelPart.setContentType(null); filePart.setTransferEncoding(null); if (contentType != null) { filePart.setContentType(contentType); } parts.add(filePart); parts.add(idPart); parts.add(commentLevelPart); post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); try { client.executeMethod(post); if (!s.expectRedirect(post, "/secure/ManageAttachments.jspa?id=" + issue.getId())) { handleErrorMessage(post); } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); } public void retrieveFile(final Issue issue, final Attachment attachment, final byte[] attachmentData) throws JiraException { JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer rssUrlBuffer = new StringBuffer(baseUrl); rssUrlBuffer.append("/secure/attachment/"); rssUrlBuffer.append(attachment.getId()); rssUrlBuffer.append("/"); try { rssUrlBuffer.append(URLEncoder.encode(attachment.getName(), server.getCharacterEncoding())); } catch (UnsupportedEncodingException e) { throw new JiraException(e); } GetMethod get = new GetMethod(rssUrlBuffer.toString()); try { int result = client.executeMethod(get); if (result != HttpStatus.SC_OK) { handleErrorMessage(get); } else { byte[] data = get.getResponseBody(); if (data.length != attachmentData.length) { throw new IOException("Unexpected attachment size (got " + data.length + ", expected " + attachmentData.length + ")"); } System.arraycopy(data, 0, attachmentData, 0, attachmentData.length); } } catch (IOException e) { throw new JiraException(e); } finally { get.releaseConnection(); } } }); } public void retrieveFile(final Issue issue, final Attachment attachment, final OutputStream out) throws JiraException { JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer rssUrlBuffer = new StringBuffer(baseUrl); rssUrlBuffer.append("/secure/attachment/"); rssUrlBuffer.append(attachment.getId()); rssUrlBuffer.append("/"); try { rssUrlBuffer.append(URLEncoder.encode(attachment.getName(), server.getCharacterEncoding())); } catch (UnsupportedEncodingException e) { throw new JiraException(e); } GetMethod get = new GetMethod(rssUrlBuffer.toString()); try { int result = client.executeMethod(get); if (result != HttpStatus.SC_OK) { handleErrorMessage(get); } else { out.write(get.getResponseBody()); } } catch (IOException e) { throw new JiraException(e); } finally { get.releaseConnection(); } } }); } public String createIssue(final Issue issue) throws JiraException { return createIssue("/secure/CreateIssueDetails.jspa", issue); } public String createSubTask(final Issue issue) throws JiraException { return createIssue("/secure/CreateSubTaskIssueDetails.jspa", issue); } // TODO refactor common parameter configuration with advanceIssueWorkflow() method private String createIssue(final String url, final Issue issue) throws JiraException { final String[] issueKey = new String[1]; final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer attachFileURLBuffer = new StringBuffer(baseUrl); attachFileURLBuffer.append(url); PostMethod post = new PostMethod(attachFileURLBuffer.toString()); post.setRequestHeader("Content-Type", s.getContentType()); post.addParameter("pid", issue.getProject().getId()); post.addParameter("issuetype", issue.getType().getId()); post.addParameter("summary", issue.getSummary()); if (issue.getPriority() != null) { post.addParameter("priority", issue.getPriority().getId()); } if (issue.getDue() != null) { post.addParameter("duedate", new SimpleDateFormat(DUE_DATE_FORMAT, Locale.US).format(issue.getDue())); } if (issue.getComponents() != null) { for (int i = 0; i < issue.getComponents().length; i++) { post.addParameter("components", issue.getComponents()[i].getId()); } } else { post.addParameter("components", "-1"); } if (issue.getReportedVersions() != null) { for (int i = 0; i < issue.getReportedVersions().length; i++) { post.addParameter("versions", issue.getReportedVersions()[i].getId()); } } else { post.addParameter("versions", "-1"); } if (issue.getFixVersions() != null) { for (int i = 0; i < issue.getFixVersions().length; i++) { post.addParameter("fixVersions", issue.getFixVersions()[i].getId()); } } else { post.addParameter("fixVersions", "-1"); } if (issue.getAssignee() == null) { post.addParameter("assignee", "-1"); // Default assignee } else if (issue.getAssignee().length() == 0) { post.addParameter("assignee", ""); // nobody } else { post.addParameter("assignee", issue.getAssignee()); } post.addParameter("reporter", server.getUserName()); post.addParameter("environment", issue.getEnvironment() != null ? issue.getEnvironment() : ""); post.addParameter("description", issue.getDescription() != null ? issue.getDescription() : ""); if (issue.getParentId() != null) { post.addParameter("parentIssueId", issue.getParentId()); } try { client.executeMethod(post); if (!s.expectRedirect(post, "/browse/")) { handleErrorMessage(post); } else { final Header locationHeader = post.getResponseHeader("location"); // parse issue key from issue URL String location = locationHeader.getValue(); int i = location.lastIndexOf("/"); if (i != -1) { issueKey[0] = location.substring(i); } else { throw new JiraException( "The server redirected to an unexpected location while creating an issue: " + location); } } } catch (IOException e) { throw new JiraException(e); } finally { post.releaseConnection(); } } }); assert issueKey[0] != null; return issueKey[0]; } public void watchIssue(final Issue issue) throws JiraException { watchUnwatchIssue(issue, true); } public void unwatchIssue(final Issue issue) throws JiraException { watchUnwatchIssue(issue, false); } private void watchUnwatchIssue(final Issue issue, final boolean watch) throws JiraException { JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer urlBuffer = new StringBuffer(baseUrl); urlBuffer.append("/browse/").append(issue.getKey()); urlBuffer.append("?watch=").append(Boolean.toString(watch)); HeadMethod head = new HeadMethod(urlBuffer.toString()); try { int result = client.executeMethod(head); if (result != HttpStatus.SC_OK) { throw new JiraException("Changing watch status failed. Return code: " + result); } } catch (IOException e) { throw new JiraException(e); } finally { head.releaseConnection(); } } }); } public void voteIssue(final Issue issue) throws JiraException { voteUnvoteIssue(issue, true); } public void unvoteIssue(final Issue issue) throws JiraException { voteUnvoteIssue(issue, false); } private void voteUnvoteIssue(final Issue issue, final boolean vote) throws JiraException { if (!issue.canUserVote(this.server.getUserName())) { return; } JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer urlBuffer = new StringBuffer(baseUrl); urlBuffer.append("/browse/").append(issue.getKey()); urlBuffer.append("?vote=").append(vote ? "vote" : "unvote"); HeadMethod head = new HeadMethod(urlBuffer.toString()); try { int result = client.executeMethod(head); if (result != HttpStatus.SC_OK) { throw new JiraException("Changing vote failed. Return code: " + result); } } catch (IOException e) { throw new JiraException(e); } finally { head.releaseConnection(); } } }); } public void deleteIssue(final Issue issue) throws JiraException { final JiraWebSession s = new JiraWebSession(server); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { StringBuffer urlBuffer = new StringBuffer(baseUrl); urlBuffer.append("/secure/DeleteIssue.jspa"); urlBuffer.append("?id=").append(issue.getId()); urlBuffer.append("&confirm=true"); HeadMethod head = new HeadMethod(urlBuffer.toString()); try { int result = client.executeMethod(head); if (result != HttpStatus.SC_OK) { throw new JiraException("Deleting issue failed. Return code: " + result); } } catch (IOException e) { throw new JiraException(e); } finally { head.releaseConnection(); } } }); } public WebServerInfo getWebServerInfo() throws JiraException { final WebServerInfo webServerInfo = new WebServerInfo(); final JiraWebSession s = new JiraWebSession(server); s.setLogEnabled(true); s.doInSession(new JiraWebSessionCallback() { public void execute(HttpClient client, JiraClient server, String baseUrl) throws JiraException { webServerInfo.setCharacterEncoding(s.getBaseURL()); webServerInfo.setCharacterEncoding(s.getCharacterEncoding()); webServerInfo.setInsecureRedirect(s.isInsecureRedirect()); } }); return webServerInfo; } private String getAssigneeParam(JiraClient server, Issue issue, int assigneeType, String user) { switch (assigneeType) { case JiraClient.ASSIGNEE_CURRENT: return issue.getAssignee(); case JiraClient.ASSIGNEE_DEFAULT: return "-1"; //$NON-NLS-1$ case JiraClient.ASSIGNEE_NONE: return ""; //$NON-NLS-1$ case JiraClient.ASSIGNEE_SELF: return server.getUserName(); case JiraClient.ASSIGNEE_USER: return user; default: return user; } } protected void handleErrorMessage(HttpMethodBase method) throws IOException, JiraException { String response = method.getResponseBodyAsString(); StatusHandler.log("JIRA error\n" + response, null); if (method.getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) { throw new JiraRemoteException("JIRA system error", null); } if (response == null) { throw new JiraRemoteMessageException("Error making JIRA request: " + method.getStatusCode(), ""); } StringReader reader = new StringReader(response); try { StringBuilder msg = new StringBuilder(); HtmlStreamTokenizer tokenizer = new HtmlStreamTokenizer(reader, null); for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); String classValue = tag.getAttribute("class"); if (classValue != null) { if (tag.getTagType() == HtmlTag.Type.DIV) { if (classValue.startsWith("infoBox")) { throw new JiraRemoteMessageException(getContent(tokenizer, HtmlTag.Type.DIV)); } else if (classValue.startsWith("errorArea")) { throw new JiraRemoteMessageException(getContent(tokenizer, HtmlTag.Type.DIV)); } } else if (tag.getTagType() == HtmlTag.Type.SPAN) { if (classValue.startsWith("errMsg")) { msg.append(getContent(tokenizer, HtmlTag.Type.SPAN)); } } } } } if (msg.length() == 0) { throw new JiraRemoteMessageException(response); } else { throw new JiraRemoteMessageException(msg.toString()); } } catch (ParseException e) { throw new JiraRemoteMessageException("Error parsing JIRA response: " + method.getStatusCode(), ""); } finally { reader.close(); } } private String getContent(HtmlStreamTokenizer tokenizer, Tag closingTag) throws IOException, ParseException { StringBuffer sb = new StringBuffer(); int count = 0; for (Token token = tokenizer.nextToken(); token.getType() != Token.EOF; token = tokenizer.nextToken()) { if (token.getType() == Token.TAG) { HtmlTag tag = (HtmlTag) token.getValue(); if (tag.getTagType() == closingTag) { if (tag.isEndTag()) { if (count == 0) { break; } else { count } } else { count++; } } } sb.append(token.toString()); } return sb.toString(); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-04-09"); this.setApiVersion("18.2.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package org.hisp.dhis.schema; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import com.google.common.base.MoreObjects; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.hisp.dhis.common.DxfNamespaces; import org.hisp.dhis.common.EmbeddedObject; import org.hisp.dhis.common.IdentifiableObject; import org.hisp.dhis.common.MetadataObject; import org.hisp.dhis.common.NameableObject; import org.hisp.dhis.security.Authority; import org.hisp.dhis.security.AuthorityType; import org.springframework.core.Ordered; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; /** * @author Morten Olav Hansen <mortenoh@gmail.com> */ @JacksonXmlRootElement( localName = "schema", namespace = DxfNamespaces.DXF_2_0 ) public class Schema implements Ordered, Klass { /** * Class that is described in this schema. */ private final Class<?> klass; /** * Is this class a sub-class of IdentifiableObject * * @see org.hisp.dhis.common.IdentifiableObject */ private final boolean identifiableObject; /** * Is this class a sub-class of NameableObject * * @see org.hisp.dhis.common.NameableObject */ private final boolean nameableObject; /** * Does this class implement {@link EmbeddedObject} ? */ private final boolean embeddedObject; /** * Singular name. */ private final String singular; /** * Plural name. */ private final String plural; /** * Is this class considered metadata, this is mainly used for our metadata importer/exporter. */ private final boolean metadata; /** * Namespace URI to be used for this class. */ private String namespace; /** * This will normally be set to equal singular, but in certain cases it might be useful to have another name * for when this class is used as an item inside a collection. */ private String name; /** * A beautified (and possibly translated) name that can be used in UI. */ private String displayName; /** * This will normally be set to equal plural, and is normally used as a wrapper for a collection of * instances of this klass type. */ private String collectionName; /** * Is sharing supported for instances of this class. */ private Boolean shareable; /** * Is data sharing supported for instances of this class. */ private boolean dataShareable; /** * Points to relative Web-API endpoint (if exposed). */ private String relativeApiEndpoint; /** * Used by LinkService to link to the API endpoint containing this type. */ private String apiEndpoint; /** * Used by LinkService to link to the Schema describing this type (if reference). */ private String href; /** * Are any properties on this class being persisted, if false, this file does not have any hbm file attached to it. */ private boolean persisted; /** * Should new instances always be default private, even if the user can create public instances. */ private boolean defaultPrivate; /** * If this is true, do not require private authority for create/update of instances of this type. */ private boolean implicitPrivateAuthority; /** * List of authorities required for doing operations on this class. */ private List<Authority> authorities = Lists.newArrayList(); /** * Map of all exposed properties on this class, where key is property * name, and value is instance of Property class. * * @see org.hisp.dhis.schema.Property */ private Map<String, Property> propertyMap = Maps.newHashMap(); /** * Map of all readable properties, cached on first request. */ private Map<String, Property> readableProperties = new HashMap<>(); /** * Map of all persisted properties, cached on first request. */ private Map<String, Property> persistedProperties = new HashMap<>(); /** * Map of all persisted properties, cached on first request. */ private Map<String, Property> nonPersistedProperties = new HashMap<>(); /** * Map of all link object properties, cached on first request. */ private Map<String, Property> embeddedObjectProperties; /** * Used for sorting of schema list when doing metadata import/export. */ private int order = Ordered.LOWEST_PRECEDENCE; public Schema( Class<?> klass, String singular, String plural ) { this.klass = klass; this.embeddedObject = EmbeddedObject.class.isAssignableFrom( klass ); this.identifiableObject = IdentifiableObject.class.isAssignableFrom( klass ); this.nameableObject = NameableObject.class.isAssignableFrom( klass ); this.singular = singular; this.plural = plural; this.metadata = MetadataObject.class.isAssignableFrom( klass ); } @Override @JsonProperty @JacksonXmlProperty( isAttribute = true ) public Class<?> getKlass() { return klass; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isIdentifiableObject() { return identifiableObject; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isNameableObject() { return nameableObject; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isEmbeddedObject() { return embeddedObject; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getSingular() { return singular; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getPlural() { return plural; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isMetadata() { return metadata; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getNamespace() { return namespace; } public void setNamespace( String namespace ) { this.namespace = namespace; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getCollectionName() { return collectionName == null ? plural : collectionName; } public void setCollectionName( String collectionName ) { this.collectionName = collectionName; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getName() { return name == null ? singular : name; } public void setName( String name ) { this.name = name; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getDisplayName() { return displayName != null ? displayName : getName(); } public void setDisplayName( String displayName ) { this.displayName = displayName; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isShareable() { return shareable != null ? shareable : (havePersistedProperty( "user" ) && havePersistedProperty( "userGroupAccesses" ) && havePersistedProperty( "publicAccess" )); } public void setShareable( boolean shareable ) { this.shareable = shareable; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isDataShareable() { return dataShareable; } public void setDataShareable( boolean dataShareable ) { this.dataShareable = dataShareable; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getRelativeApiEndpoint() { return relativeApiEndpoint; } public void setRelativeApiEndpoint( String relativeApiEndpoint ) { this.relativeApiEndpoint = relativeApiEndpoint; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getApiEndpoint() { return apiEndpoint; } public void setApiEndpoint( String apiEndpoint ) { this.apiEndpoint = apiEndpoint; } public boolean haveApiEndpoint() { return getRelativeApiEndpoint() != null || getApiEndpoint() != null; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public String getHref() { return href; } public void setHref( String href ) { this.href = href; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isPersisted() { return persisted; } public void setPersisted( boolean persisted ) { this.persisted = persisted; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isTranslatable() { return isIdentifiableObject() && havePersistedProperty( "translations" ); } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isFavoritable() { return isIdentifiableObject() && havePersistedProperty( "favorites" ); } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isDefaultPrivate() { return defaultPrivate; } public void setDefaultPrivate( boolean defaultPrivate ) { this.defaultPrivate = defaultPrivate; } @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public boolean isImplicitPrivateAuthority() { return implicitPrivateAuthority; } public void setImplicitPrivateAuthority( boolean implicitPrivateAuthority ) { this.implicitPrivateAuthority = implicitPrivateAuthority; } @JsonProperty @JacksonXmlElementWrapper( localName = "authorities", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "authority", namespace = DxfNamespaces.DXF_2_0 ) public List<Authority> getAuthorities() { return authorities; } public void setAuthorities( List<Authority> authorities ) { this.authorities = authorities; } @JsonProperty @JacksonXmlElementWrapper( localName = "properties", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "property", namespace = DxfNamespaces.DXF_2_0 ) public List<Property> getProperties() { return Lists.newArrayList( propertyMap.values() ); } public boolean haveProperty( String propertyName ) { return getPropertyMap().containsKey( propertyName ); } public boolean havePersistedProperty( String propertyName ) { return haveProperty( propertyName ) && getProperty( propertyName ).isPersisted(); } public Property propertyByRole( String role ) { if ( !StringUtils.isEmpty( role ) ) { for ( Property property : propertyMap.values() ) { if ( property.isCollection() && property.isManyToMany() && (role.equals( property.getOwningRole() ) || role.equals( property.getInverseRole() )) ) { return property; } } } return null; } @JsonIgnore public Map<String, Property> getPropertyMap() { return propertyMap; } public void setPropertyMap( Map<String, Property> propertyMap ) { this.propertyMap = propertyMap; } @SuppressWarnings( "rawtypes" ) private Set<Class> references; @JsonProperty @JacksonXmlElementWrapper( localName = "references", namespace = DxfNamespaces.DXF_2_0 ) @JacksonXmlProperty( localName = "reference", namespace = DxfNamespaces.DXF_2_0 ) @SuppressWarnings( "rawtypes" ) public Set<Class> getReferences() { if ( references == null ) { references = getProperties().stream() .filter( p -> p.isCollection() ? PropertyType.REFERENCE == p.getItemPropertyType() : PropertyType.REFERENCE == p.getPropertyType() ) .map( p -> p.isCollection() ? p.getItemKlass() : p.getKlass() ).collect( Collectors.toSet() ); } return references; } public Map<String, Property> getReadableProperties() { if ( readableProperties.isEmpty() ) { getPropertyMap().entrySet().stream() .filter( entry -> entry.getValue().isReadable() ) .forEach( entry -> readableProperties.put( entry.getKey(), entry.getValue() ) ); } return readableProperties; } public Map<String, Property> getPersistedProperties() { if ( persistedProperties.isEmpty() ) { getPropertyMap().entrySet().stream() .filter( entry -> entry.getValue().isPersisted() ) .forEach( entry -> persistedProperties.put( entry.getKey(), entry.getValue() ) ); } return persistedProperties; } public Map<String, Property> getNonPersistedProperties() { if ( nonPersistedProperties.isEmpty() ) { getPropertyMap().entrySet().stream() .filter( entry -> !entry.getValue().isPersisted() ) .forEach( entry -> nonPersistedProperties.put( entry.getKey(), entry.getValue() ) ); } return nonPersistedProperties; } public Map<String, Property> getEmbeddedObjectProperties() { if ( embeddedObjectProperties == null ) { embeddedObjectProperties = new HashMap<>(); getPropertyMap().entrySet().stream() .filter( entry -> entry.getValue().isEmbeddedObject() ) .forEach( entry -> embeddedObjectProperties.put( entry.getKey(), entry.getValue() ) ); } return embeddedObjectProperties; } public void addProperty( Property property ) { if ( property == null || property.getName() == null || propertyMap.containsKey( property.getName() ) ) { return; } propertyMap.put( property.getName(), property ); } @JsonIgnore public Property getProperty( String name ) { if ( propertyMap.containsKey( name ) ) { return propertyMap.get( name ); } return null; } @JsonIgnore public Property getPersistedProperty( String name ) { Property property = getProperty( name ); if ( property != null && property.isPersisted() ) { return property; } return null; } public List<String> getAuthorityByType( AuthorityType type ) { List<String> authorityList = Lists.newArrayList(); authorities.stream() .filter( authority -> type.equals( authority.getType() ) ) .forEach( authority -> authorityList.addAll( authority.getAuthorities() ) ); return authorityList; } @Override @JsonProperty @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 ) public int getOrder() { return order; } public void setOrder( int order ) { this.order = order; } @Override public int hashCode() { return Objects.hash( klass, identifiableObject, nameableObject, singular, plural, namespace, name, collectionName, shareable, relativeApiEndpoint, metadata, authorities, propertyMap, order ); } @Override public boolean equals( Object obj ) { if ( this == obj ) { return true; } if ( obj == null || getClass() != obj.getClass() ) { return false; } final Schema other = (Schema) obj; return java.util.Objects.equals( this.klass, other.klass ) && Objects.equals( this.identifiableObject, other.identifiableObject ) && Objects.equals( this.nameableObject, other.nameableObject ) && Objects.equals( this.singular, other.singular ) && Objects.equals( this.plural, other.plural ) && Objects.equals( this.namespace, other.namespace ) && Objects.equals( this.name, other.name ) && Objects.equals( this.collectionName, other.collectionName ) && Objects.equals( this.shareable, other.shareable ) && Objects.equals( this.relativeApiEndpoint, other.relativeApiEndpoint ) && Objects.equals( this.metadata, other.metadata ) && Objects.equals( this.authorities, other.authorities ) && Objects.equals( this.propertyMap, other.propertyMap ) && Objects.equals( this.order, other.order ); } @Override public String toString() { return MoreObjects.toStringHelper( this ) .add( "klass", klass ) .add( "identifiableObject", identifiableObject ) .add( "nameableObject", nameableObject ) .add( "singular", singular ) .add( "plural", plural ) .add( "namespace", namespace ) .add( "name", name ) .add( "collectionName", collectionName ) .add( "shareable", shareable ) .add( "relativeApiEndpoint", relativeApiEndpoint ) .add( "metadata", metadata ) .add( "authorities", authorities ) .add( "propertyMap", propertyMap ) .toString(); } }
package org.eclipse.mylar.internal.tasks.ui.views; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.mylar.internal.tasks.ui.TaskListImages; import org.eclipse.mylar.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylar.tasks.core.TaskRepository; import org.eclipse.mylar.tasks.ui.TasksUiPlugin; import org.eclipse.swt.graphics.Image; /** * @author Mik Kersten */ public class TaskRepositoryLabelProvider extends LabelProvider implements ITableLabelProvider { public String getColumnText(Object object, int index) { if (object instanceof TaskRepository) { TaskRepository repository = (TaskRepository) object; if (repository.getRepositoryLabel() != null && repository.getRepositoryLabel().length() > 0) { return repository.getRepositoryLabel(); } else { return repository.getUrl(); } } else if (object instanceof AbstractRepositoryConnector) { return ((AbstractRepositoryConnector) object).getLabel(); } else { return getText(object); } } public Image getColumnImage(Object obj, int index) { return getImage(obj); } public Image getImage(Object object) { String kind = null; if (object instanceof AbstractRepositoryConnector) { AbstractRepositoryConnector repositoryConnector = (AbstractRepositoryConnector) object; kind = repositoryConnector.getRepositoryType(); } else if (object instanceof TaskRepository) { TaskRepository repository = (TaskRepository) object; kind = repository.getKind(); } if (kind != null) { Image image = TasksUiPlugin.getDefault().getBrandingIcon(kind); if (image != null) { return image; } } return TaskListImages.getImage(TaskListImages.REPOSITORY); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-11-05"); this.setApiVersion("14.8.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package som.langserv.newspeak; import static som.langserv.som.PositionConversion.getEnd; import static som.langserv.som.PositionConversion.getStart; import static som.langserv.som.PositionConversion.toRange; import static som.vm.Symbols.symbolFor; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import org.eclipse.lsp4j.ParameterInformation; import org.eclipse.lsp4j.Position; import org.eclipse.lsp4j.Range; import org.eclipse.lsp4j.SignatureInformation; import org.eclipse.lsp4j.SymbolKind; import com.oracle.truffle.api.instrumentation.Tag; import com.oracle.truffle.api.source.Source; import com.oracle.truffle.api.source.SourceSection; import bd.basic.ProgramDefinitionError; import som.compiler.AccessModifier; import som.compiler.MethodBuilder; import som.compiler.MixinBuilder; import som.compiler.Parser; import som.compiler.Variable.Argument; import som.compiler.Variable.Local; import som.interpreter.SomLanguage; import som.interpreter.nodes.ArgumentReadNode.LocalArgumentReadNode; import som.interpreter.nodes.ArgumentReadNode.NonLocalArgumentReadNode; import som.interpreter.nodes.ExpressionNode; import som.interpreter.nodes.LocalVariableNode.LocalVariableReadNode; import som.interpreter.nodes.NonLocalVariableNode.NonLocalVariableReadNode; import som.interpreter.nodes.literals.LiteralNode; import som.langserv.som.BlockId; import som.langserv.structure.DocumentStructures; import som.langserv.structure.LanguageElement; import som.langserv.structure.LanguageElementId; import som.langserv.structure.SemanticTokenModifier; import som.langserv.structure.SemanticTokenType; import som.vmobjects.SSymbol; import tools.debugger.Tags.ArgumentTag; import tools.debugger.Tags.CommentTag; import tools.debugger.Tags.KeywordTag; import tools.debugger.Tags.LiteralTag; import tools.debugger.Tags.LocalVariableTag; /** * Extension of the SOMns parser to record additional structural information * that is useful for tooling. */ public class NewspeakParser extends Parser { private final DocumentStructures symbols; private final ArrayDeque<LanguageElement> currentClass; private LanguageElement currentMethod; private final ArrayList<Integer> keywordStart; private final ArrayList<String> keywordParts; public NewspeakParser(final String content, final Source source, final NewspeakStructures structuralProbe, final SomLanguage lang) throws ParseError { super(content, source, structuralProbe, lang); this.symbols = structuralProbe.getSymbols(); currentClass = new ArrayDeque<>(); keywordStart = new ArrayList<>(); keywordParts = new ArrayList<>(); } @Override protected String className() throws ParseError { int coord = getStartIndex(); var name = super.className(); recordTokenSemantics(coord, name, SemanticTokenType.CLASS); LanguageElement clazz = startSymbol(name, SymbolKind.Class, coord, new SymbolId(symbolFor(name))); currentClass.push(clazz); clazz.setDetail(name); return name; } @Override protected void mixinApplication(final MixinBuilder mxnBuilder, final int mixinId) throws ProgramDefinitionError { // in this case, classBody() isn't called, // so, we need to complete the possible primary factory method completePrimaryFactoryMethod(mxnBuilder); super.mixinApplication(mxnBuilder, mixinId); } @Override protected void classBody(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { int coord = getStartIndex(); try { super.classBody(mxnBuilder); } finally { LanguageElement clazz = currentClass.pop(); Range range = toRange(getSource(coord)); symbols.completeSymbol(clazz, new Range(clazz.getSelectionRange().getStart(), range.getEnd())); } } @Override protected void classHeader(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { try { super.classHeader(mxnBuilder); } finally { completePrimaryFactoryMethod(mxnBuilder); } } private void completePrimaryFactoryMethod(final MixinBuilder mxnBuilder) { if (currentMethod != null) { SourceSection ss = mxnBuilder.getInitializerSource(); if (ss == null) { ss = getSource(getStartIndex()); } Range selection = currentMethod.getSelectionRange(); Range init = toRange(ss); symbols.completeSymbol(currentMethod, new Range(selection.getStart(), init.getEnd())); currentMethod = null; } } @Override protected void classSideDecl(final MixinBuilder mxnBuilder) throws ProgramDefinitionError { int coord = getStartIndex(); LanguageElement clazz = symbols.startSymbol(SymbolKind.Class, true); clazz.setName("class"); currentClass.push(clazz); try { super.classSideDecl(mxnBuilder); } finally { currentClass.pop(); clazz.setId(new SymbolId(symbolFor("class"))); clazz.setDetail(mxnBuilder.getName() + " class"); symbols.completeSymbol(clazz, toRange(getSource(coord))); } } @Override protected boolean acceptIdentifier(final String identifier, final Class<? extends Tag> tag) { int coord = getStartIndex(); boolean result = super.acceptIdentifier(identifier, tag); if (result) { if (tag == KeywordTag.class) { switch (identifier) { case "private": case "public": case "protected": recordTokenSemantics(coord, identifier, SemanticTokenType.MODIFIER); break; default: recordTokenSemantics(coord, identifier, SemanticTokenType.KEYWORD); break; } } else if (tag == LiteralTag.class) { switch (identifier) { case "true": case "false": case "nil": case "objL": recordTokenSemantics(coord, identifier, SemanticTokenType.KEYWORD); } } } return result; } @Override protected ExpressionNode keywordMessage(final MethodBuilder builder, final ExpressionNode receiver, final boolean explicitRcvr, final boolean eventualSend, final SourceSection sendOperator) throws ProgramDefinitionError { int stackHeight = keywordParts.size(); ExpressionNode result = super.keywordMessage( builder, receiver, explicitRcvr, eventualSend, sendOperator); int numParts = keywordParts.size() - stackHeight; assert numParts >= 1; int[] starts = new int[numParts]; StringBuilder kw = new StringBuilder(); for (int i = numParts - 1; i >= 0; i kw.append(keywordParts.remove(keywordParts.size() - 1)); starts[i] = keywordStart.remove(keywordStart.size() - 1); } SSymbol msg = symbolFor(kw.toString()); SymbolId call = new SymbolId(msg); for (int i = 0; i < numParts; i += 1) { referenceSymbol(call, starts[i], msg.getString().length()); } return result; } @Override protected SSymbol unarySelector() throws ParseError { int coord = getStartIndex(); SSymbol result = super.unarySelector(); recordTokenSemantics(coord, result.getString(), SemanticTokenType.METHOD); return result; } @Override protected SSymbol unarySendSelector() throws ParseError { int coord = getStartIndex(); SSymbol result = super.unarySendSelector(); recordTokenSemantics(coord, result.getString(), SemanticTokenType.METHOD); referenceSymbol(new SymbolId(result), coord, result.getString().length()); return result; } @Override protected ExpressionNode implicitUnaryMessage(final MethodBuilder meth, final SSymbol selector, final SourceSection section) { ExpressionNode result = super.implicitUnaryMessage(meth, selector, section); if (result instanceof LocalArgumentReadNode || result instanceof NonLocalArgumentReadNode) { recordTokenSemantics(section, SemanticTokenType.PARAMETER); Argument arg; if (result instanceof LocalArgumentReadNode l) { arg = l.getArg(); } else { arg = ((NonLocalArgumentReadNode) result).getArg(); } referenceSymbol(new VariableId(arg), section); } else if (result instanceof LocalVariableReadNode || result instanceof NonLocalVariableReadNode) { recordTokenSemantics(section, SemanticTokenType.VARIABLE); Local local; if (result instanceof LocalVariableReadNode l) { local = l.getLocal(); } else { local = ((NonLocalVariableReadNode) result).getLocal(); } referenceSymbol(new VariableId(local), section); } else { recordTokenSemantics(section, SemanticTokenType.METHOD); referenceSymbol(new SymbolId(selector), section); } return result; } @Override protected SSymbol binarySelector() throws ParseError { int coord = getStartIndex(); SSymbol result = super.binarySelector(); recordTokenSemantics(coord, result.getString(), SemanticTokenType.METHOD); return result; } @Override protected SSymbol binarySendSelector() throws ParseError { int coord = getStartIndex(); SSymbol result = super.binarySendSelector(); recordTokenSemantics(coord, result.getString(), SemanticTokenType.METHOD); referenceSymbol(new SymbolId(result), coord, result.getString().length()); return result; } @Override protected String keyword() throws ParseError { int coord = getStartIndex(); String result = super.keyword(); recordTokenSemantics(coord, result, SemanticTokenType.METHOD); keywordParts.add(result); keywordStart.add(coord); return result; } @Override protected Argument argument(final MethodBuilder builder) throws ParseError { Argument arg = super.argument(builder); recordSymbolDefinition( arg.name.getString(), new VariableId(arg), SymbolKind.Variable, arg.source, false); return arg; } @Override protected void unaryPattern(final MethodBuilder builder) throws ParseError { assert currentMethod == null; int coord = getStartIndex(); currentMethod = symbols.startSymbol(SymbolKind.Method, true); super.unaryPattern(builder); currentMethod.setName(builder.getSignature().getString()); currentMethod.setId(new SymbolId(builder.getSignature())); currentMethod.setSelectionRange(getRange(coord, builder.getSignature().getString())); currentMethod.setDetail(builder.getSignature().getString()); } @Override protected void binaryPattern(final MethodBuilder builder) throws ParseError { assert currentMethod == null; int coord = getStartIndex(); currentMethod = symbols.startSymbol(SymbolKind.Method, true); super.binaryPattern(builder); String name = builder.getSignature().getString(); currentMethod.setName(name); currentMethod.setId(new SymbolId(builder.getSignature())); currentMethod.setSelectionRange(getRange(coord, name)); currentMethod.setDetail(name + " " + builder.getArgument(1).name.getString()); } @Override protected void keywordPattern(final MethodBuilder builder) throws ParseError { assert currentMethod == null; assert keywordParts.size() == 0 : "We are not in any method, so, this is expected to be zero"; assert keywordStart.size() == 0 : "We are not in any method, so, this is expected to be zero"; assert keywordStart.size() == keywordParts.size(); currentMethod = symbols.startSymbol(SymbolKind.Method, true); super.keywordPattern(builder); String name = builder.getSignature().getString(); currentMethod.setName(name); currentMethod.setId(new SymbolId(builder.getSignature())); Position start = getStart(source, keywordStart.get(0)); Position end = getEnd(source, keywordStart.get(keywordStart.size() - 1), keywordParts.get(keywordParts.size() - 1).length()); currentMethod.setSelectionRange(new Range(start, end)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < keywordParts.size(); i += 1) { sb.append(keywordParts.get(i)); sb.append(' '); sb.append(builder.getArgument(i + 1).name.getString()); if (i < keywordParts.size() - 1) { sb.append(' '); } } currentMethod.setDetail(sb.toString()); keywordParts.clear(); keywordStart.clear(); } @Override protected MethodBuilder methodDeclaration(final AccessModifier accessModifier, final int coord, final MixinBuilder mxnBuilder) throws ProgramDefinitionError { MethodBuilder builder = super.methodDeclaration(accessModifier, coord, mxnBuilder); symbols.completeSymbol(currentMethod, toRange(getSource(coord))); currentMethod.setSignature(createSignature(builder)); currentMethod = null; return builder; } private SignatureInformation createSignature(final MethodBuilder mbuilder) { SignatureInformation info = new SignatureInformation(); info.setLabel(mbuilder.getFullName()); List<ParameterInformation> params = new ArrayList<>(mbuilder.getNumberOfArguments() - 1); for (int i = 1; i < mbuilder.getNumberOfArguments(); i += 1) { ParameterInformation p = new ParameterInformation(); p.setLabel(mbuilder.getArgument(i).name.getString()); params.add(p); } info.setParameters(params); return info; } @Override protected String slotDecl() throws ParseError { int coord = getStartIndex(); var slotName = super.slotDecl(); recordTokenSemantics(coord, slotName, SemanticTokenType.PROPERTY); return slotName; } @Override protected LiteralNode literalNumber() throws ParseError { int coord = getStartIndex(); var result = super.literalNumber(); SourceSection source = getSource(coord); recordTokenSemantics(source, SemanticTokenType.NUMBER); return result; } @Override protected LiteralNode literalSymbol() throws ParseError { var result = super.literalSymbol(); recordTokenSemantics(result.getSourceSection(), SemanticTokenType.STRING); return result; } @Override protected LiteralNode literalString() throws ParseError { var result = super.literalString(); recordTokenSemantics(result.getSourceSection(), SemanticTokenType.STRING); return result; } @Override protected LiteralNode literalChar() throws ParseError { var result = super.literalChar(); recordTokenSemantics(result.getSourceSection(), SemanticTokenType.STRING); return result; } @Override protected ExpressionNode literalObject(final MethodBuilder builder) throws ProgramDefinitionError { LanguageElement currentM = currentMethod; currentMethod = null; int coord = getStartIndex(); LanguageElement clazz = startSymbol("objL", SymbolKind.Class, coord, new LiteralId("objL")); currentClass.push(clazz); clazz.setDetail("objL"); ExpressionNode node = super.literalObject(builder); currentMethod = currentM; return node; } @Override public ExpressionNode nestedBlock(final MethodBuilder mbuilder) throws ProgramDefinitionError { int coord = getStartIndex(); LanguageElement block = symbols.startSymbol(SymbolKind.Function, true); ExpressionNode result = super.nestedBlock(mbuilder); block.setName(mbuilder.getSignature().getString()); StringBuilder sb = new StringBuilder(); sb.append('['); for (int i = 1; i < mbuilder.getNumberOfArguments(); i += 1) { if (i > 1) { sb.append(' '); } var a = mbuilder.getArgument(i); sb.append(':'); sb.append(a.name.getString()); } sb.append(']'); block.setDetail(sb.toString()); block.setId(new BlockId(block.getName())); symbols.completeSymbol(block, toRange(getSource(coord))); block.setSelectionRange(block.getRange()); return result; } @Override protected void reportSyntaxElement(final Class<? extends Tag> type, final SourceSection source) { if (type == CommentTag.class) { recordTokenSemantics(source, SemanticTokenType.COMMENT); } else if (type == LocalVariableTag.class) { recordTokenSemantics(source, SemanticTokenType.VARIABLE); } else if (type == ArgumentTag.class) { recordTokenSemantics(source, SemanticTokenType.PARAMETER); } } protected void recordTokenSemantics(final int coords, final String length, final SemanticTokenType tokenType) { recordTokenSemantics(coords, length, tokenType, (SemanticTokenModifier[]) null); } protected void recordTokenSemantics(final int coords, final String length, final SemanticTokenType tokenType, final SemanticTokenModifier... modifiers) { symbols.getSemanticTokens().addSemanticToken(source.getLineNumber(coords) - 1, source.getColumnNumber(coords) - 1, length.length(), tokenType, modifiers); } protected void recordTokenSemantics(final SourceSection source, final SemanticTokenType tokenType) { symbols.getSemanticTokens().addSemanticToken(source.getStartLine() - 1, source.getStartColumn() - 1, source.getCharLength(), tokenType); } private LanguageElement startSymbol(final String name, final SymbolKind kind, final int startCoord, final LanguageElementId id) { return symbols.startSymbol( name, kind, id, toRange(source, startCoord, name.length()), true); } private void referenceSymbol(final LanguageElementId id, final int startCoord, final int length) { symbols.referenceSymbol(id, toRange(source, startCoord, length)); } private void referenceSymbol(final LanguageElementId id, final SourceSection ss) { symbols.referenceSymbol(id, toRange(ss)); } private Range getRange(final int startCoord, final String name) { return toRange(source, startCoord, name.length()); } private void recordSymbolDefinition(final String string, final LanguageElementId id, final SymbolKind kind, final SourceSection ss, final boolean listAsSymbol) { symbols.recordDefinition(string, id, kind, toRange(ss), false, listAsSymbol); } }
package org.lamport.tla.toolbox.tool.tlc.ui.wizard; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.lamport.tla.toolbox.tool.tlc.ui.util.FormHelper; /** * A page with a simple field for formula editing * @author Simon Zambrovski * @version $Id$ */ public class FormulaWizardPage extends WizardPage { private SourceViewer sourceViewer; private Document document; public FormulaWizardPage(String action, String description) { super("FormulaWizardPage"); setTitle(action); setDescription(description); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { Composite container = new Composite(parent, SWT.NULL); GridLayout layout = new GridLayout(1, false); container.setLayout(layout); sourceViewer = FormHelper.createSourceViewer(container, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL); // SWT.FILL causes the text field to expand and contract // with changes in size of the dialog window. GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); gd.heightHint = 200; gd.widthHint = 400; gd.grabExcessHorizontalSpace = true; gd.grabExcessVerticalSpace = true; StyledText control = sourceViewer.getTextWidget(); control.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getContainer().updateButtons(); } }); control.setEditable(true); control.setLayoutData(gd); if (this.document == null) { this.document = new Document(); } sourceViewer.setDocument(this.getDocument()); setControl(container); } public Document getDocument() { return this.document; } public void setDocument(Document document) { this.document = document; } }
package se.llbit.tinytemplate.test; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import org.junit.Test; import se.llbit.tinytemplate.TemplateParser.SyntaxError; import se.llbit.tinytemplate.TinyTemplate; @SuppressWarnings("javadoc") public class TestTinyTemplate { @Test public void testUndefinedTemplate() throws SyntaxError { TinyTemplate tt = new TinyTemplate(""); assertEquals("", tt.expand("test")); assertFalse("expand returns false if the template was not expanded", tt.expand("test", new PrintStream(new ByteArrayOutputStream()))); } @Test public void testSimple_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate("test [[hello]]"); assertEquals("hello", tt.expand("test")); assertTrue("expand returns true if the template was expanded", tt.expand("test", new PrintStream(new ByteArrayOutputStream()))); } @Test public void testSimple_2() throws SyntaxError { TinyTemplate tt = new TinyTemplate("foo [[]]"); assertEquals("", tt.expand("foo")); assertTrue("expand returns true if the template was expanded", tt.expand("foo", new PrintStream(new ByteArrayOutputStream()))); } /** * Multiple templates in one "file" * @throws SyntaxError */ @Test public void testSimple_3() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "foo [[ baa ]] bar [[ faa ]]"); assertEquals(" baa ", tt.expand("foo")); assertEquals(" faa ", tt.expand("bar")); } /** * Very many special characters can be used in template names * @throws SyntaxError */ @Test public void testSimple_4() throws SyntaxError { TinyTemplate tt = new TinyTemplate("$(%)!}@{ [[=)]]"); assertEquals("=)", tt.expand("$(%)!}@{")); } /** * Missing template name * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_1() throws SyntaxError { new TinyTemplate("[[]]"); } /** * Missing template name * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_2() throws SyntaxError { new TinyTemplate(" = [[]]"); } /** * Missing end of template body * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_3() throws SyntaxError { new TinyTemplate("x = [[ "); } /** * Missing end of template body * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_4() throws SyntaxError { new TinyTemplate("x = [[ ]"); } /** * Missing start of template body * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_5() throws SyntaxError { new TinyTemplate("x = ]]"); } /** * Missing start of template body * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_6() throws SyntaxError { new TinyTemplate("x = [ ]]"); } /** * Double brackets not allowed inside double brackets * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_7() throws SyntaxError { new TinyTemplate("x = [[ [[ ]]"); } /** * Double brackets not allowed inside double brackets * @throws SyntaxError */ @Test(expected=SyntaxError.class) public void testSyntaxError_8() throws SyntaxError { new TinyTemplate("x = [[ ]] ]]"); } /** * Tests a template variable * @throws SyntaxError */ @Test public void testVariable_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate("test = [[$hello]]"); tt.bind("hello", "hej"); assertEquals("hej", tt.expand("test")); } /** * Tests an unbound variable * @throws SyntaxError */ @Test public void testVariable_2() throws SyntaxError { TinyTemplate tt = new TinyTemplate("test = [[x $hello y]]"); assertEquals("x <unbound variable hello> y", tt.expand("test")); } /** * Double dollar signs escape to a single dollar sign * @throws SyntaxError */ @Test public void testVariable_3() throws SyntaxError { TinyTemplate tt = new TinyTemplate("test = [[ $$ not a variable ]]"); assertEquals(" $ not a variable ", tt.expand("test")); } /** * Special characters can be used in variable names if the name is * parenthesized. * @throws SyntaxError */ @Test public void testVariable_4() throws SyntaxError { TinyTemplate tt = new TinyTemplate("foo = [[$([what].wat)]]"); tt.bind("[what].wat", "batman"); assertEquals("batman", tt.expand("foo")); } /** * Multiple assign are allowed between template name and template body * @throws SyntaxError */ @Test public void testMultiAssign_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "test == \n" + "== ==== = ===== [[$hello]]"); tt.bind("hello", "hej"); assertEquals("hej", tt.expand("test")); } /** * Multiple template names are allowed for each template * @throws SyntaxError */ @Test public void testSynonyms_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "test == foo = = = bar [[$hello]]"); tt.bind("hello", "hej"); assertEquals("hej", tt.expand("test")); assertEquals("hej", tt.expand("foo")); assertEquals("hej", tt.expand("bar")); } /** * Multiple template names are allowed for each template * @throws SyntaxError */ @Test public void testSynonyms_2() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "test foo bar [[$hello]]"); tt.bind("hello", "hej"); assertEquals("hej", tt.expand("test")); assertEquals("hej", tt.expand("foo")); assertEquals("hej", tt.expand("bar")); } @Test public void testComment_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "# line comment\n" + "test = [[$hello]]"); tt.bind("hello", "hej"); assertEquals("hej", tt.expand("test")); } @Test public void testComment_2() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "foo=[[x]]# comment\n" + "# test = [[y]]"); assertEquals("", tt.expand("test")); assertEquals("x", tt.expand("foo")); } @Test public void testComment_3() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "foo=[[## not a comment]]"); assertEquals("hash signs inside a template body are not comments", "# not a comment", tt.expand("foo")); } @Test public void testPersistentVariables_1() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "foo [[ $boo ]]\n" + "bar [[ XY$boo.Z ]]"); tt.bind("boo", "123"); assertEquals(" 123 ", tt.expand("foo")); assertEquals(" XY123.Z ", tt.expand("bar")); } @Test public void testPersistentVariables_2() throws SyntaxError { TinyTemplate tt = new TinyTemplate( "foo [[ $boo ]]\n" + "bar [[ XY$boo.Z ]]"); tt.setPersistentVariables(false); tt.bind("boo", "123"); assertEquals(" 123 ", tt.expand("foo")); assertEquals(" XY<unbound variable boo>.Z ", tt.expand("bar")); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-11-11"); this.setApiVersion("17.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package org.metaborg.sunshine.services.pipelined.builders; import java.io.IOException; import java.io.OutputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSystemException; import org.metaborg.spoofax.core.SpoofaxException; import org.metaborg.spoofax.core.SpoofaxRuntimeException; import org.metaborg.spoofax.core.context.ContextIdentifier; import org.metaborg.spoofax.core.context.SpoofaxContext; import org.metaborg.spoofax.core.language.ILanguage; import org.metaborg.spoofax.core.language.ILanguageIdentifierService; import org.metaborg.spoofax.core.resource.ResourceService; import org.metaborg.spoofax.core.stratego.IStrategoRuntimeService; import org.metaborg.spoofax.core.stratego.StrategoRuntimeUtils; import org.metaborg.spoofax.core.transform.stratego.menu.Action; import org.metaborg.spoofax.core.transform.stratego.menu.MenusFacet; import org.metaborg.sunshine.environment.LaunchConfiguration; import org.metaborg.sunshine.environment.ServiceRegistry; import org.metaborg.sunshine.pipeline.ISinkOne; import org.metaborg.sunshine.pipeline.diff.Diff; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.terms.TermFactory; import org.strategoxt.HybridInterpreter; import org.strategoxt.lang.Context; import org.strategoxt.stratego_aterm.aterm_escape_strings_0_0; import org.strategoxt.stratego_aterm.pp_aterm_box_0_0; import org.strategoxt.stratego_gpp.box2text_string_0_1; public class BuilderSink implements ISinkOne<BuilderInputTerm> { private static final Logger logger = LoggerFactory.getLogger(BuilderSink.class.getName()); private final String builderName; private final LaunchConfiguration lauchConfig; private final ILanguageIdentifierService languageIdentifierService; public BuilderSink(String builderName, LaunchConfiguration launchConfig, ILanguageIdentifierService languageIdentifierService) { this.builderName = builderName; this.lauchConfig = launchConfig; this.languageIdentifierService = languageIdentifierService; logger.trace("Created new builder for {}", builderName); } /** * Call a builder on the file's source or analyzed AST. The builder is expected to have the following format: * * <code> * builder: * (node, position, ast, path, project-path) -> (filename, result) * </code> * * or * * <code> * builder: * (node, position, ast, path, project-path) -> None() * </code> * * In the latter option the assumption being that the builder code itself is taking care of writing files to disk if * necessary. * * NB: The current implementation calls the builder on the following input: * * <code> * (ast, [], ast, path, project-path) * </code> * * NB: The current implementation assumes that the result is a StrategoString and will not work with a term. * * @param product * The {@link BuilderInputTerm} to run this builder on. * * @throws SpoofaxRuntimeException */ @Override public void sink(Diff<BuilderInputTerm> product) { final FileObject file = product.getPayload().getFile(); final ILanguage language = languageIdentifierService.identify(file); final Action action = language.facet(MenusFacet.class).action(builderName); if(action == null) { logger.error("Builder {} could not be found", builderName); } logger.debug("Invoking builder {} on file {}", action.name, file); try { IStrategoTerm inputTuple = product.getPayload().toStratego(); assert inputTuple != null && inputTuple.getSubtermCount() == 5; invoke(action, inputTuple); } catch(FileSystemException e) { final String msg = "Cannot construct input tuple for builder"; logger.error(msg, e); throw new SpoofaxRuntimeException(msg, e); } } private IStrategoTerm invoke(Action action, IStrategoTerm input) { final ServiceRegistry services = ServiceRegistry.INSTANCE(); final IStrategoRuntimeService runtimeService = services.getService(IStrategoRuntimeService.class); final IStrategoTerm result; try { final HybridInterpreter interpreter = runtimeService.runtime(new SpoofaxContext(ServiceRegistry.INSTANCE().getService(ResourceService.class), new ContextIdentifier(lauchConfig.projectDir, action.inputLangauge))); result = StrategoRuntimeUtils.invoke(interpreter, input, action.strategy); } catch(SpoofaxException e) { final String msg = "Cannot get Stratego interpreter, or Stratego invocation failed"; logger.error(msg, e); throw new SpoofaxRuntimeException(msg, e); } processResult(action, result); return result; } private void processResult(Action action, IStrategoTerm result) { if(isWriteFile(result)) { try { final FileObject resultFile = lauchConfig.projectDir.resolveFile(((IStrategoString) result.getSubterm(0)).stringValue()); final IStrategoTerm resultTerm = result.getSubterm(1); final String resultContents; if(resultTerm.getTermType() == IStrategoTerm.STRING) { resultContents = ((IStrategoString) resultTerm).stringValue(); } else { final IStrategoString pp = prettyPrint(resultTerm); if (pp != null) { resultContents = pp.stringValue(); } else { resultContents = resultTerm.toString(); } } try(OutputStream stream = resultFile.getContent().getOutputStream()) { IOUtils.write(resultContents, stream); } } catch(IOException e) { throw new SpoofaxRuntimeException("Builder " + action.name + "failed to write result", e); } } } private boolean isWriteFile(final IStrategoTerm result) { if(result instanceof IStrategoAppl) { if(((IStrategoAppl) result).getName().equals("None")) { return false; } else { logger.error("Builder returned an unsupported result type {}", result); throw new SpoofaxRuntimeException("Unsupported return value from builder: " + result); } } else { if(result == null || result.getSubtermCount() != 2 || !(result.getSubterm(0) instanceof IStrategoString)) { logger.error("Builder returned an unsupported result type {}", result); throw new SpoofaxRuntimeException("Unsupported return value from builder: " + result); } else { return true; } } } private IStrategoString prettyPrint(IStrategoTerm term) { final ITermFactory termFactory = new TermFactory(); final Context context = new Context(termFactory); org.strategoxt.stratego_aterm.Main.init(context); term = aterm_escape_strings_0_0.instance.invoke(context, term); term = pp_aterm_box_0_0.instance.invoke(context, term); term = box2text_string_0_1.instance.invoke(context, term, termFactory.makeInt(120)); return (IStrategoString) term; } }
package org.strategoxt.imp.runtime.services.views.outline; import org.eclipse.imp.parser.IParseController; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.strategoxt.imp.runtime.EditorState; import org.strategoxt.imp.runtime.services.views.FilteringInfoPopup; import org.strategoxt.imp.runtime.services.views.StrategoLabelProvider; import org.strategoxt.imp.runtime.services.views.StrategoTreeContentProvider; public class SpoofaxOutlinePopup extends FilteringInfoPopup { private static int WIDTH = 400; private static int HEIGHT = 322; private final IParseController parseController; private final StrategoTreeContentProvider contentProvider; private final StrategoLabelProvider labelProvider; private final Composite editorComposite; public SpoofaxOutlinePopup(Shell parent, int shellStyle, int treeStyle, IParseController parseController, Composite editorComposite) { super(parent, shellStyle, treeStyle); this.parseController = parseController; this.editorComposite = editorComposite; contentProvider = new StrategoTreeContentProvider(); String pluginPath = EditorState.getEditorFor(parseController).getDescriptor().getBasePath().toOSString(); labelProvider = new StrategoLabelProvider(pluginPath); } @Override protected TreeViewer createTreeViewer(Composite parent, int style) { TreeViewer treeViewer = new TreeViewer(parent, style); treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS); treeViewer.setInput(SpoofaxOutlineUtil.getOutline(parseController)); return treeViewer; } @Override protected String getId() { return getClass().toString(); } @Override protected void handleElementSelected(Object selectedElement) { if (selectedElement != null) { SpoofaxOutlineUtil.selectCorrespondingText(selectedElement, parseController); setMatcherString("", false); } } @Override public void setInput(Object input) { getTreeViewer().setInput(input); } @Override protected Point getInitialSize() { return new Point(WIDTH, HEIGHT); } /** * See comments at {@link FilteringInfoPopup#setLocation(Point)}. */ @Override protected Point getInitialLocation(Point initialSize) { Point location = editorComposite.toDisplay(0, 0); Point editorSize = editorComposite.getSize(); return new Point(location.x + editorSize.x/2 - initialSize.x/2, location.y + editorSize.y/2 - initialSize.y/2); } }
package com.webp.util; public class BooleanUtil { public static String toFlag(String str) { return Boolean.valueOf(str) ? "1" : "0"; } public static String toFlag(boolean bool) { return bool ? "1" : "0"; } }
package ua.com.fielden.platform.security.user.impl; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.from; import static ua.com.fielden.platform.entity.query.fluent.EntityQueryUtils.select; import static ua.com.fielden.platform.error.Result.failure; import static ua.com.fielden.platform.error.Result.successful; import static ua.com.fielden.platform.utils.EntityUtils.equalsEx; import com.google.inject.Inject; import ua.com.fielden.platform.basic.config.IApplicationSettings; import ua.com.fielden.platform.basic.config.IApplicationSettings.AuthMode; import ua.com.fielden.platform.dao.QueryExecutionModel; import ua.com.fielden.platform.entity.query.fluent.EntityQueryProgressiveInterfaces.ICompoundCondition0; import ua.com.fielden.platform.entity.query.fluent.fetch; import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel; import ua.com.fielden.platform.error.Result; import ua.com.fielden.platform.security.user.IAuthenticationModel; import ua.com.fielden.platform.security.user.User; import ua.com.fielden.platform.security.user.UserSecret; import ua.com.fielden.platform.security.user.UserSecretCo; /** * An authentication model for explicit user logins. * It supports both RSO and SSO modes, whereby in the SSO mode users are checked if they are permitted to login with RSO. * * @author TG Team * */ public class DefaultAuthenticationModel implements IAuthenticationModel { private static final Result failedAuthResult = failure("The presented login credentials are not recognized."); private final UserSecretCo coUserSecret; private final String protectiveSalt; private final AuthMode authMode; @Inject public DefaultAuthenticationModel(final UserSecretCo coUserSecret, final IApplicationSettings settings) { this.authMode = settings.authMode(); this.coUserSecret = coUserSecret; this.protectiveSalt = coUserSecret.newSalt(); } @Override public Result authenticate(final String username, final String password) { try { // check attempts to login in with UNIT_TEST_USER and fail those if (User.system_users.UNIT_TEST_USER.matches(username)) { return failedAuthResult; } // in the SSO mode, users should only be able to login with RSO if they are permitted (i.e., their ssOnly property is false). final ICompoundCondition0<UserSecret> rsoCondition = select(UserSecret.class).where().lowerCase().prop("key.key").eq().lowerCase().val(username).and().prop("key.active").eq().val(true); final EntityResultQueryModel<UserSecret> query = (authMode == AuthMode.RSO ? rsoCondition : rsoCondition.and().prop("key.ssoOnly").eq().val(false)).model(); final fetch<UserSecret> fetch = coUserSecret.getFetchProvider().fetchModel(); final QueryExecutionModel<UserSecret, EntityResultQueryModel<UserSecret>> qem = from(query).with(fetch).model(); return coUserSecret.getEntityOptional(qem) .map(secret -> equalsEx(secret.getPassword(), coUserSecret.hashPasswd(password, secret.getSalt())) ? successful(secret.getKey()) : failedAuthResult) .orElseGet(() -> { // let's mimic password hashing for unrecognised users to protected from timing-based attacks that would allow enumerating valid user names coUserSecret.hashPasswd(password, protectiveSalt); // the original result needs to be returned. return failedAuthResult; }); } catch (final Exception ex) { return failure(ex); } } }
package org.geomajas.plugin.rasterizing.layer; import com.sun.media.jai.codec.ByteArraySeekableStream; import com.vividsolutions.jts.geom.Envelope; import java.awt.AlphaComposite; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.RenderedImage; import java.awt.image.WritableRaster; import java.awt.image.renderable.ParameterBlock; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import javax.media.jai.ImageLayout; import javax.media.jai.InterpolationNearest; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import javax.media.jai.RenderedOp; import javax.media.jai.operator.MosaicDescriptor; import javax.media.jai.operator.TranslateDescriptor; import org.geomajas.geometry.Bbox; import org.geomajas.layer.tile.RasterTile; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.DirectLayer; import org.geotools.map.MapContent; import org.geotools.map.MapViewport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Layer responsible for rendering raster layers. Most of the code is copied from the printing plugin. * * @author Jan De Moerloose */ public class RasterDirectLayer extends DirectLayer { protected static final int DOWNLOAD_MAX_ATTEMPTS = 2; protected static final int DOWNLOAD_MAX_THREADS = 5; protected static final long DOWNLOAD_TIMEOUT = 120000; // milliseconds protected static final long DOWNLOAD_TIMEOUT_ONE_TILE = 100; // milliseconds protected static final int RETRY_WAIT = 100; // milliseconds private static final String BUNDLE_NAME = "org/geomajas/plugin/rasterizing/rasterizing"; //$NON-NLS-1$ private static final String MISSING_TILE_IN_MOSAIC = "missing tile in mosaic "; private static final String OPACITY = "opacity:"; private static final int DEFAULT_IMAGE_BUFFER_SIZE = 1024; private static ExecutorService staticPool; private final List<RasterTile> tiles; private final ResourceBundle resourceBundle = ResourceBundle.getBundle(BUNDLE_NAME); private final Logger log = LoggerFactory.getLogger(RasterDirectLayer.class); private final int tileWidth; private final int tileHeight; private final String style; private double tileScale = -1; private UrlDownLoader urlDownLoader; private ExecutorService imageThreadPool; /** * Create a layer with a default static thread pool. * * @param urlDownLoader helper class for downloading images * @param tiles the tiles to be rendered * @param tileWidth the tile width * @param tileHeight the tile height * @param style the image style * @deprecated use * {@link RasterDirectLayer#RasterDirectLayer(ExecutorService, UrlDownLoader, List, int, int, String)} * */ @Deprecated public RasterDirectLayer(UrlDownLoader urlDownLoader, List<RasterTile> tiles, int tileWidth, int tileHeight, String style) { this(getStaticPool(), urlDownLoader, tiles, tileWidth, tileHeight, style); } /** * Create a layer with a default static thread pool. * * @param urlDownLoader helper class for downloading images * @param tiles the tiles to be rendered * @param tileWidth the tile width * @param tileHeight the tile height * @param tileScale the scale at which to render * @param style the image style * @deprecated use * {@link RasterDirectLayer#RasterDirectLayer(ExecutorService, UrlDownLoader, List, int, int, double, String)} * */ @Deprecated public RasterDirectLayer(UrlDownLoader urlDownLoader, List<RasterTile> tiles, int tileWidth, int tileHeight, double tileScale, String style) { this(getStaticPool(), urlDownLoader, tiles, tileWidth, tileHeight, tileScale, style); } /** * Create a layer with the specified thread pool. * * @param imageThreadPool thread pool * @param urlDownLoader helper class for downloading images * @param tiles the tiles to be rendered * @param tileWidth the tile width * @param tileHeight the tile height * @param style the image style * */ public RasterDirectLayer(ExecutorService imageThreadPool, UrlDownLoader urlDownLoader, List<RasterTile> tiles, int tileWidth, int tileHeight, String style) { this(imageThreadPool, urlDownLoader, tiles, tileWidth, tileHeight, -1.0, style); } /** * Create a layer with the specified thread pool. * * @param imageThreadPool thread pool * @param urlDownLoader helper class for downloading images * @param tiles the tiles to be rendered * @param tileWidth the tile width * @param tileHeight the tile height * @param tileScale the scale at which to render * @param style the image style * */ public RasterDirectLayer(ExecutorService imageThreadPool, UrlDownLoader urlDownLoader, List<RasterTile> tiles, int tileWidth, int tileHeight, double tileScale, String style) { this.imageThreadPool = imageThreadPool; this.urlDownLoader = urlDownLoader; this.tileScale = tileScale; this.tiles = tiles; if (tileWidth < 1) { tileWidth = 1; } this.tileWidth = tileWidth; if (tileHeight < 1) { tileHeight = 1; } this.tileHeight = tileHeight; this.style = style; } @Override public void draw(Graphics2D graphics, MapContent map, MapViewport viewport) { try { if (tiles.size() > 0) { Collection<Callable<ImageResult>> callables = new ArrayList<Callable<ImageResult>>(tiles.size()); // Build the image downloading threads for (RasterTile tile : tiles) { RasterImageDownloadCallable downloadThread = new RasterImageDownloadCallable(DOWNLOAD_MAX_ATTEMPTS, tile); callables.add(downloadThread); } // Loop until all images are downloaded or timeout is reached long totalTimeout = DOWNLOAD_TIMEOUT + DOWNLOAD_TIMEOUT_ONE_TILE * tiles.size(); log.debug("=== total timeout (millis): {}", totalTimeout); List<Future<ImageResult>> futures = imageThreadPool.invokeAll(callables, totalTimeout, TimeUnit.MILLISECONDS); log.debug("service.invokeAll() returned for " + tiles.size() + " tiles with tile #0 with URL: " + (tiles.isEmpty() ? "" : tiles.get(0).getUrl())); // determine the pixel bounds of the mosaic Bbox pixelBounds = getPixelBounds(tiles); // create the images for the mosaic List<RenderedImage> images = new ArrayList<RenderedImage>(); for (Future<ImageResult> future : futures) { ImageResult result = null; if (future.isDone()) { try { result = future.get(); // create a rendered image if (result.getImage() != null && result.getImage().length > 0) { RenderedImage image = JAI.create("stream", new ByteArraySeekableStream(result.getImage())); // convert to common direct color model (some images have their own indexed color model) RenderedImage colored = toDirectColorModel(image); // translate to the correct position in the tile grid double xOffset = result.getRasterImage().getCode().getX() * tileWidth - pixelBounds.getX(); double yOffset; // TODO: in some cases, the y-index is up (e.g. WMS), should be down for // all layers !!!! if (isYIndexUp(tiles)) { yOffset = result.getRasterImage().getCode().getY() * tileHeight - pixelBounds.getY(); } else { yOffset = (pixelBounds.getMaxY() - (result.getRasterImage().getCode().getY() + 1) * tileHeight); } log.debug("adding to(" + xOffset + "," + yOffset + "), url = " + result.getRasterImage().getUrl()); RenderedImage translated = TranslateDescriptor.create(colored, (float) xOffset, (float) yOffset, new InterpolationNearest(), null); images.add(translated); } } catch (ExecutionException e) { addLoadError(graphics, (ImageException) (e.getCause()), viewport); log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage()); } catch (Exception e) { log.warn("Missing tile " + result.getRasterImage().getUrl()); log.warn(MISSING_TILE_IN_MOSAIC + e.getMessage()); } } } if (images.size() > 0) { ImageLayout imageLayout = new ImageLayout(0, 0, (int) pixelBounds.getWidth(), (int) pixelBounds.getHeight()); imageLayout.setTileWidth(tileWidth); imageLayout.setTileHeight(tileHeight); // create the mosaic image ParameterBlock pbMosaic = new ParameterBlock(); pbMosaic.add(MosaicDescriptor.MOSAIC_TYPE_OVERLAY); for (RenderedImage renderedImage : images) { pbMosaic.addSource(renderedImage); } RenderedOp mosaic = JAI.create("mosaic", pbMosaic, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, imageLayout)); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); log.debug("rendering to buffer..."); ImageIO.write(mosaic, "png", baos); log.debug("rendering done, size = " + baos.toByteArray().length); RasterTile mosaicTile = new RasterTile(); mosaicTile.setBounds(getWorldBounds(tiles)); log.info("application bounds = " + mosaicTile.getBounds()); ImageResult mosaicResult = new ImageResult(mosaicTile); mosaicResult.setImage(baos.toByteArray()); addImage(graphics, mosaicResult, viewport); } catch (IOException e) { log.warn("could not write mosaic image " + e.getMessage()); } } } } catch (InterruptedException e) { log.warn("rendering {} to {} failed : ", getTitle(), viewport.getBounds()); } } protected void addImage(Graphics2D graphics, ImageResult imageResult, MapViewport viewport) throws IOException { Rectangle screenArea = viewport.getScreenArea(); ReferencedEnvelope worldBounds = viewport.getBounds(); // convert map bounds to application bounds double printScale = screenArea.getWidth() / worldBounds.getWidth(); if (tileScale < 0) { tileScale = printScale; } Envelope applicationBounds = new Envelope((worldBounds.getMinX()) * printScale, (worldBounds.getMaxX()) * printScale, -(worldBounds.getMinY()) * printScale, -(worldBounds.getMaxY()) * printScale); Bbox imageBounds = imageResult.getRasterImage().getBounds(); // find transform between image bounds and application bounds double tx = (imageBounds.getX() * printScale / tileScale - applicationBounds.getMinX()); double ty = (imageBounds.getY() * printScale / tileScale - applicationBounds.getMinY()); BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageResult.getImage())); double scaleX = imageBounds.getWidth() / image.getWidth() * printScale / tileScale; double scaleY = imageBounds.getHeight() / image.getHeight() * printScale / tileScale; AffineTransform transform = new AffineTransform(); transform.translate(tx, ty); transform.scale(scaleX, scaleY); if (log.isDebugEnabled()) { log.debug("adding image, width=" + image.getWidth() + ",height=" + image.getHeight() + ",x=" + tx + ",y=" + ty); } // opacity log.debug("before drawImage"); // create a copy to apply transform Graphics2D g = (Graphics2D) graphics.create(); // apply opacity to image off-graphics to avoid interference with whatever opacity model is used by graphics BufferedImage opaqueCopy = makeOpaque(image); g.drawImage(opaqueCopy, transform, null); log.debug("after drawImage"); } private BufferedImage makeOpaque(BufferedImage image) { if (image.getType() == BufferedImage.TYPE_CUSTOM) { log.warn("makeOpaque {} Unknown Image Type 0: ", getTitle()); return image; } BufferedImage opaqueCopy = new BufferedImage(image.getWidth(), image.getHeight(), image.getType()); Graphics2D g1 = opaqueCopy.createGraphics(); g1.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, getOpacity())); g1.drawImage(image, null, 0, 0); g1.dispose(); return opaqueCopy; } private float getOpacity() { String match = style; // could be 'opacity:0.5;' or '0.5' if (style.contains(OPACITY)) { match = style.substring(style.indexOf(OPACITY) + OPACITY.length()); } int semiColonPosition = match.indexOf(';'); if (semiColonPosition >= 0) { match = match.substring(0, semiColonPosition); } try { return Float.valueOf(match); } catch (NumberFormatException nfe) { log.warn("Could not parse opacity " + style + "of raster layer " + getTitle()); return 1f; } } protected void addLoadError(Graphics2D graphics, ImageException imageResult, MapViewport viewport) { Bbox imageBounds = imageResult.getRasterImage().getBounds(); ReferencedEnvelope viewBounds = viewport.getBounds(); double rasterScale = viewport.getScreenArea().getWidth() / viewport.getBounds().getWidth(); double width = imageBounds.getWidth(); double height = imageBounds.getHeight(); // subtract screen position of lower-left corner double x = imageBounds.getX() - rasterScale * viewBounds.getMinX(); // shift y to lower left corner, flip y to user space and subtract // screen position of lower-left // corner double y = -imageBounds.getY() - imageBounds.getHeight() - rasterScale * viewBounds.getMinY(); if (log.isDebugEnabled()) { log.debug("adding image, width=" + width + ",height=" + height + ",x=" + x + ",y=" + y); } // opacity log.debug("before drawImage"); graphics.drawString(getNlsString("loaderror.line1"), (int) x, (int) y); } @Override public ReferencedEnvelope getBounds() { return null; } private boolean isYIndexUp(List<RasterTile> tiles) { RasterTile first = tiles.iterator().next(); for (RasterTile tile : tiles) { if (tile.getCode().getY() > first.getCode().getY()) { return tile.getBounds().getY() > first.getBounds().getY(); } else if (tile.getCode().getY() < first.getCode().getY()) { return tile.getBounds().getY() < first.getBounds().getY(); } } return false; } private Bbox getPixelBounds(List<RasterTile> tiles) { Bbox bounds = null; for (RasterTile tile : tiles) { Bbox tileBounds = new Bbox(tile.getCode().getX() * tileWidth, tile.getCode().getY() * tileHeight, tileWidth, tileHeight); if (bounds == null) { bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight()); } else { double minx = Math.min(tileBounds.getX(), bounds.getX()); double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX()); double miny = Math.min(tileBounds.getY(), bounds.getY()); double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY()); bounds = new Bbox(minx, miny, maxx - minx, maxy - miny); } } return bounds; } private Bbox getWorldBounds(List<RasterTile> tiles) { Bbox bounds = null; for (RasterTile tile : tiles) { Bbox tileBounds = new Bbox(tile.getBounds().getX(), tile.getBounds().getY(), tile.getBounds().getWidth(), tile.getBounds().getHeight()); if (bounds == null) { bounds = new Bbox(tileBounds.getX(), tileBounds.getY(), tileBounds.getWidth(), tileBounds.getHeight()); } else { double minx = Math.min(tileBounds.getX(), bounds.getX()); double maxx = Math.max(tileBounds.getMaxX(), bounds.getMaxX()); double miny = Math.min(tileBounds.getY(), bounds.getY()); double maxy = Math.max(tileBounds.getMaxY(), bounds.getMaxY()); bounds = new Bbox(minx, miny, maxx - minx, maxy - miny); } } return bounds; } public String getNlsString(String key) { try { return resourceBundle.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } /** * Converts an image to a RGBA direct color model using a workaround via buffered image directly calling the * ColorConvert operation fails for unknown reasons ?! * * @param img image to convert * @return converted image */ public PlanarImage toDirectColorModel(RenderedImage img) { BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_4BYTE_ABGR); BufferedImage source = new BufferedImage(img.getColorModel(), (WritableRaster) img.getData(), img .getColorModel().isAlphaPremultiplied(), null); ColorConvertOp op = new ColorConvertOp(null); op.filter(source, dest); return PlanarImage.wrapRenderedImage(dest); } /** * Image result. * * @author Jan De Moerloose */ private static class ImageResult { private byte[] image; private final RasterTile rasterImage; public ImageResult(RasterTile rasterImage) { this.rasterImage = rasterImage; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } public RasterTile getRasterImage() { return rasterImage; } } /** * Image Exception * * @author Jan De Moerloose */ private static class ImageException extends Exception { private static final long serialVersionUID = 100L; private final RasterTile rasterImage; public ImageException(RasterTile rasterImage, Throwable cause) { super(cause); this.rasterImage = rasterImage; } public RasterTile getRasterImage() { return rasterImage; } } /** * Transforms a URL into an inputstream. * * @author Jan De Moerloose */ public interface UrlDownLoader { InputStream getStream(String url) throws IOException; } private static ExecutorService getStaticPool() { if (staticPool == null) { int cpus = Runtime.getRuntime().availableProcessors(); staticPool = Executors.newFixedThreadPool(cpus * 30); } return staticPool; } /** * Download image with a couple of retries. * * @author Jan De Moerloose */ private class RasterImageDownloadCallable implements Callable<ImageResult> { private final ImageResult result; private final int retries; public RasterImageDownloadCallable(int retries, RasterTile rasterImage) { this.result = new ImageResult(rasterImage); this.retries = retries; } public ImageResult call() throws ImageException { log.debug("Fetching image: {}", result.getRasterImage().getUrl()); int triesLeft = retries; while (true) { InputStream inputStream = null; try { inputStream = urlDownLoader.getStream(result.getRasterImage().getUrl()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(DEFAULT_IMAGE_BUFFER_SIZE); byte[] bytes = new byte[1024]; int readBytes; while ((readBytes = inputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, readBytes); } outputStream.flush(); result.setImage(outputStream.toByteArray()); return result; } catch (Exception e) { // NOSONAR if (log.isDebugEnabled()) { log.error("Fetching image: error loading " + result.getRasterImage().getUrl(), e); } triesLeft if (triesLeft == 0) { throw new ImageException(result.getRasterImage(), e); } else { log.debug("Fetching image: retrying ", result.getRasterImage().getUrl()); try { Thread.sleep(RETRY_WAIT); // give server some time to recover } catch (InterruptedException ie) { // NOSONAR just ignore } } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } } }
package dk.cs.aau.huppaal; import dk.cs.aau.huppaal.abstractions.Component; import dk.cs.aau.huppaal.abstractions.Project; import dk.cs.aau.huppaal.abstractions.Query; import dk.cs.aau.huppaal.backend.UPPAALDriverManager; import dk.cs.aau.huppaal.code_analysis.CodeAnalysis; import dk.cs.aau.huppaal.controllers.CanvasController; import dk.cs.aau.huppaal.controllers.HUPPAALController; import dk.cs.aau.huppaal.presentations.BackgroundThreadPresentation; import dk.cs.aau.huppaal.presentations.HUPPAALPresentation; import dk.cs.aau.huppaal.presentations.UndoRedoHistoryPresentation; import dk.cs.aau.huppaal.utility.keyboard.Keybind; import dk.cs.aau.huppaal.utility.keyboard.KeyboardTracker; import com.google.common.io.Files; import com.google.gson.*; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.ListChangeListener; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.text.Font; import javafx.stage.Screen; import javafx.stage.Stage; import jiconfont.icons.GoogleMaterialDesignIcons; import jiconfont.javafx.IconFontFX; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.security.CodeSource; import java.util.*; import java.util.prefs.Preferences; public class HUPPAAL extends Application { public static Preferences preferences; public static String serverDirectory; public static String debugDirectory; public static String temporaryProjectDirectory; public static boolean serializationDone = false; private static Project project; private static HUPPAALPresentation presentation; public static SimpleStringProperty projectDirectory = new SimpleStringProperty(); private Stage debugStage; { try { preferences = Preferences.userRoot().node("HUPPAAL"); final CodeSource codeSource = HUPPAAL.class.getProtectionDomain().getCodeSource(); final File jarFile = new File(codeSource.getLocation().toURI().getPath()); final String rootDirectory = jarFile.getParentFile().getPath() + File.separator; projectDirectory.set(preferences.get("latestProject", rootDirectory + "projects" + File.separator + "project")); projectDirectory.addListener((observable, oldValue, newValue) -> {preferences.put("latestProject", newValue);}); temporaryProjectDirectory = rootDirectory + "projects" + File.separator + "temp"; serverDirectory = rootDirectory + "servers"; debugDirectory = rootDirectory + "uppaal-debug"; forceCreateFolder(projectDirectory.getValue()); forceCreateFolder(serverDirectory); forceCreateFolder(debugDirectory); } catch (final URISyntaxException e) { System.out.println("Could not create project directory!"); System.exit(1); } catch (final IOException e) { System.out.println("Could not create project directory!"); System.exit(2); } } public static void main(final String[] args) { launch(HUPPAAL.class, args); } public static Project getProject() { return project; } public static void save() { // Clear the project folder try { final File directory = new File(projectDirectory.getValue()); FileUtils.forceMkdir(directory); FileUtils.cleanDirectory(directory); } catch (final IOException e) { showToast("Save failed: " + e.getMessage()); e.printStackTrace(); } HUPPAAL.getProject().getComponents().forEach(component -> { try { final Writer writer = new FileWriter(String.format(projectDirectory.getValue() + File.separator + "%s.json", component.getName())); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(component.serialize(), writer); writer.close(); } catch (final IOException e) { showToast("Could not save project: " + e.getMessage()); e.printStackTrace(); } }); final JsonArray queries = new JsonArray(); HUPPAAL.getProject().getQueries().forEach(query -> { queries.add(query.serialize()); }); final Writer writer; try { writer = new FileWriter(projectDirectory.getValue() + File.separator + "Queries.json"); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(queries, writer); writer.close(); showToast("Project saved!"); } catch (final IOException e) { showToast("Could not save project: " + e.getMessage()); e.printStackTrace(); } } public static void showToast(final String message) { presentation.showSnackbarMessage(message); } public static void showHelp() { presentation.showHelp(); } public static BooleanProperty toggleFilePane() { return presentation.toggleFilePane(); } public static BooleanProperty toggleQueryPane() { return presentation.toggleQueryPane(); } private void forceCreateFolder(final String directoryPath) throws IOException { final File directory = new File(directoryPath); FileUtils.forceMkdir(directory); } @Override public void start(final Stage stage) throws Exception { // Load or create new project project = new Project(); // Set the title and icon for the application stage.setTitle("H-UPPAAL"); stage.getIcons().add(new Image("uppaal.ico")); // Load the fonts required for the project IconFontFX.register(GoogleMaterialDesignIcons.getIconFont()); loadFonts(); // Remove the classic decoration //stage.initStyle(StageStyle.UNIFIED); // Make the view used for the application final HUPPAALPresentation huppaal = new HUPPAALPresentation(); presentation = huppaal; // Make the scene that we will use, and set its size to 80% of the primary screen final Screen screen = Screen.getPrimary(); final Scene scene = new Scene(huppaal, screen.getVisualBounds().getWidth() * 0.8, screen.getVisualBounds().getHeight() * 0.8); stage.setScene(scene); // Load all .css files used todo: these should be loaded in the view classes (?) scene.getStylesheets().add("main.css"); scene.getStylesheets().add("colors.css"); scene.getStylesheets().add("model_canvas.css"); // Handle a mouse click as a deselection of all elements scene.setOnMousePressed(event -> { if (scene.getFocusOwner() == null || scene.getFocusOwner().getParent() == null) return; scene.getFocusOwner().getParent().requestFocus(); }); // Let our keyboard tracker handle all key presses scene.setOnKeyPressed(KeyboardTracker.handleKeyPress); // Set the icon for the application stage.getIcons().addAll( new Image(getClass().getResource("ic_launcher/mipmap-hdpi/ic_launcher.png").toExternalForm()), new Image(getClass().getResource("ic_launcher/mipmap-mdpi/ic_launcher.png").toExternalForm()), new Image(getClass().getResource("ic_launcher/mipmap-xhdpi/ic_launcher.png").toExternalForm()), new Image(getClass().getResource("ic_launcher/mipmap-xxhdpi/ic_launcher.png").toExternalForm()), new Image(getClass().getResource("ic_launcher/mipmap-xxxhdpi/ic_launcher.png").toExternalForm()) ); initializeProjectFolder(); // We're now ready! Let the curtains fall! stage.show(); HUPPAALController.reachabilityServiceEnabled = true; // Register a key-bind for showing debug-information KeyboardTracker.registerKeybind("DEBUG", new Keybind(new KeyCodeCombination(KeyCode.F12), () -> { // Toggle the debug mode for the debug class (will update misc. debug variables which presentations bind to) Debug.debugModeEnabled.set(!Debug.debugModeEnabled.get()); if (debugStage != null) { debugStage.close(); debugStage = null; return; } try { final UndoRedoHistoryPresentation undoRedoHistoryPresentation = new UndoRedoHistoryPresentation(); undoRedoHistoryPresentation.setMinWidth(100); final BackgroundThreadPresentation backgroundThreadPresentation = new BackgroundThreadPresentation(); backgroundThreadPresentation.setMinWidth(100); final HBox root = new HBox(undoRedoHistoryPresentation, backgroundThreadPresentation); root.setStyle("-fx-background-color: brown;"); HBox.setHgrow(undoRedoHistoryPresentation, Priority.ALWAYS); HBox.setHgrow(backgroundThreadPresentation, Priority.ALWAYS); debugStage = new Stage(); debugStage.setScene(new Scene(root)); debugStage.getScene().getStylesheets().add("main.css"); debugStage.getScene().getStylesheets().add("colors.css"); debugStage.setWidth(screen.getVisualBounds().getWidth() * 0.2); debugStage.setHeight(screen.getVisualBounds().getWidth() * 0.3); debugStage.show(); //stage.requestFocus(); } catch (final Exception e) { e.printStackTrace(); } })); stage.setOnCloseRequest(event -> { UPPAALDriverManager.getInstance().stopEngines(); Platform.exit(); System.exit(0); }); } public static void initializeProjectFolder() throws IOException { try { // Make sure that the project directory exists final File directory = new File(projectDirectory.get()); FileUtils.forceMkdir(directory); CodeAnalysis.getErrors().addListener(new ListChangeListener<CodeAnalysis.Message>() { @Override public void onChanged(Change<? extends CodeAnalysis.Message> c) { CodeAnalysis.getErrors().forEach(message -> { System.out.println(message.getMessage()); }); } }); CodeAnalysis.getBackendErrors().removeIf(message -> true); CodeAnalysis.getErrors().removeIf(message -> true); CodeAnalysis.getWarnings().removeIf(message -> true); CodeAnalysis.disable(); HUPPAAL.getProject().getQueries().removeIf(query -> true); HUPPAAL.getProject().getComponents().removeIf(component -> true); HUPPAAL.getProject().setMainComponent(null); // Deserialize the project deserializeProject(directory); CodeAnalysis.enable(); // Generate all component presentations by making them the active component in the view one by one Component initialShownComponent = null; for (final Component component : HUPPAAL.getProject().getComponents()) { // The first component should be shown if there is no main if (initialShownComponent == null) { initialShownComponent = component; } // If the component is the main show that one if (component.isIsMain()) { initialShownComponent = component; } CanvasController.setActiveComponent(component); } // If we found a component (preferably main) set that as active if (initialShownComponent != null) { CanvasController.setActiveComponent(initialShownComponent); } serializationDone = true; }catch (Exception e) { e.printStackTrace(); } } public static void uppaalDriverUpdated(){ //The UPPAALDriver has been updated, notify the presentation presentation.uppaalDriverUpdated(); } private static void deserializeProject(final File projectFolder) throws IOException { // If there are no files do not try to deserialize final File[] projectFiles = projectFolder.listFiles(); if (projectFiles == null || projectFiles.length == 0) return; // Create maps for deserialization final Map<String, JsonObject> componentJsonMap = new HashMap<>(); final Map<JsonObject, Integer> componentMaxDepthMap = new HashMap<>(); JsonObject mainJsonComponent = null; for (final File file : projectFiles) { final String fileContent = Files.toString(file, Charset.defaultCharset()); // If the file represents the queries if (file.getName().equals("Queries.json")) { new JsonParser().parse(fileContent).getAsJsonArray().forEach(jsonElement -> { final Query newQuery = new Query((JsonObject) jsonElement); getProject().getQueries().add(newQuery); }); // Do not parse Queries.json as a component continue; } // Parse the file to an json object final JsonObject jsonObject = new JsonParser().parse(fileContent).getAsJsonObject(); // Fetch the name of the component final String componentName = jsonObject.get("name").getAsString(); // Add the name and the json object to the map componentJsonMap.put(componentName, jsonObject); // Initialize the max depth map componentMaxDepthMap.put(jsonObject, 0); // Find the main name of the main component if (jsonObject.get("main").getAsBoolean()) { mainJsonComponent = jsonObject; } } if (mainJsonComponent != null) { updateDepthMap(mainJsonComponent, 0, componentJsonMap, componentMaxDepthMap); } final List<Map.Entry<JsonObject, Integer>> list = new LinkedList<>(componentMaxDepthMap.entrySet()); // Defined Custom Comparator here Collections.sort(list, (o1, o2) -> o1.getValue().compareTo(o2.getValue())); final List<JsonObject> orderedJsonComponents = new ArrayList<>(); for (final Map.Entry<JsonObject, Integer> mapEntry : list) { orderedJsonComponents.add(mapEntry.getKey()); } // Reverse the list such that the greatest depth is first in the list Collections.reverse(orderedJsonComponents); // Add the components to the list orderedJsonComponents.forEach(jsonObject -> { // It is important that the components are added the list prior to deserialiation final Component newComponent = new Component(); getProject().getComponents().add(newComponent); newComponent.deserialize(jsonObject); }); } private static void updateDepthMap(final JsonObject jsonObject, final int depth, final Map<String, JsonObject> nameToJson, final Map<JsonObject, Integer> jsonToDpeth) { if (jsonToDpeth.get(jsonObject) < depth) { jsonToDpeth.put(jsonObject, depth); } final List<String> subComponentNames = new ArrayList<>(); jsonObject.get("sub_components").getAsJsonArray().forEach(jsonElement -> { subComponentNames.add(jsonElement.getAsJsonObject().get("component").getAsString()); }); for (final String subComponentName : subComponentNames) { updateDepthMap(nameToJson.get(subComponentName), depth + 1, nameToJson, jsonToDpeth); } } private void loadFonts() { Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Black.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-BlackItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Bold.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-BoldItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Bold.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-BoldItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Italic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Light.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-LightItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/RobotoCondensed-Regular.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Italic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Light.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-LightItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Medium.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-MediumItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Regular.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-Thin.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto/Roboto-ThinItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Bold.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-BoldItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Italic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Light.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-LightItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Medium.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-MediumItalic.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Regular.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-Thin.ttf"), 14); Font.loadFont(getClass().getResourceAsStream("fonts/roboto_mono/RobotoMono-ThinItalic.ttf"), 14); } }
package edu.chl.proton.model; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.List; public class File extends FileSystemEntity { private boolean isSaved; public File(String name) { this.setName(name); } public File(String name, Folder parentFolder) { this.setName(name); parentFolder.addFile(this); } protected void setIsSaved(boolean state) { isSaved = state; } protected boolean isSaved() { return isSaved; } protected void save(List<String> text) throws IOException { File file = new File(this.getPath()); BufferedWriter out = new BufferedWriter(new FileWriter(String.valueOf(file))); for(String line : text) { out.write(line); } out.close(); setIsSaved(true); } // TODO protected String lastEdited() { return ""; } // TODO protected void remove() { } }
package it.unibz.inf.ontop.reformulation.tests; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; import it.unibz.inf.ontop.model.*; import it.unibz.inf.ontop.model.impl.AtomPredicateImpl; import it.unibz.inf.ontop.model.impl.ImmutabilityTools; import it.unibz.inf.ontop.model.impl.OBDADataFactoryImpl; import it.unibz.inf.ontop.owlrefplatform.core.optimization.PullOutVariableOptimizer; import it.unibz.inf.ontop.pivotalrepr.*; import it.unibz.inf.ontop.pivotalrepr.equivalence.IQSyntacticEquivalenceChecker; import it.unibz.inf.ontop.pivotalrepr.impl.*; import it.unibz.inf.ontop.pivotalrepr.impl.tree.DefaultIntermediateQueryBuilder; import org.junit.Test; import java.util.Optional; import static it.unibz.inf.ontop.model.ExpressionOperation.EQ; import static junit.framework.TestCase.assertTrue; public class PullOutVariableOptimizerTest { private final static AtomPredicate TABLE1_PREDICATE = new AtomPredicateImpl("table1", 2); private final static AtomPredicate TABLE2_PREDICATE = new AtomPredicateImpl("table2", 2); private final static AtomPredicate TABLE3_PREDICATE = new AtomPredicateImpl("table3", 2); private final static AtomPredicate TABLE4_PREDICATE = new AtomPredicateImpl("table2", 3); private final static AtomPredicate TABLE5_PREDICATE = new AtomPredicateImpl("table3", 2); private final static AtomPredicate ANS1_PREDICATE1 = new AtomPredicateImpl("ans1", 4); private final static AtomPredicate ANS1_PREDICATE2 = new AtomPredicateImpl("ans1", 3); private final static AtomPredicate ANS1_PREDICATE3 = new AtomPredicateImpl("ans1", 2); private final static OBDADataFactory DATA_FACTORY = OBDADataFactoryImpl.getInstance(); private final static Variable X = DATA_FACTORY.getVariable("X"); private final static Variable X0 = DATA_FACTORY.getVariable("Xf0"); private final static Variable X1 = DATA_FACTORY.getVariable("Xf1"); private final static Variable X2 = DATA_FACTORY.getVariable("Xf2"); private final static Variable X3 = DATA_FACTORY.getVariable("Xf3"); private final static Variable X4 = DATA_FACTORY.getVariable("Xf0f3"); private final static Variable X5 = DATA_FACTORY.getVariable("Xf0f1"); private final static Variable Y = DATA_FACTORY.getVariable("Y"); private final static Variable Y1 = DATA_FACTORY.getVariable("Yf1"); private final static Variable Y2 = DATA_FACTORY.getVariable("Yf2"); private final static Variable Z = DATA_FACTORY.getVariable("Z"); private final static Variable W = DATA_FACTORY.getVariable("W"); private final static ImmutableExpression EXPRESSION1 = DATA_FACTORY.getImmutableExpression( EQ, X, X0); private final static ImmutableExpression EXPRESSION2 = DATA_FACTORY.getImmutableExpression( EQ, Y, Y1); private final static ImmutableExpression EXPRESSION3 = DATA_FACTORY.getImmutableExpression( EQ, X, X1); private final static ImmutableExpression EXPRESSION4 = DATA_FACTORY.getImmutableExpression( EQ, X, X2); private final static ImmutableExpression EXPRESSION5 = DATA_FACTORY.getImmutableExpression( EQ, X, X3); private final static ImmutableExpression EXPRESSION6 = DATA_FACTORY.getImmutableExpression( EQ, Y, Y2); private final static ImmutableExpression EXPRESSION7 = DATA_FACTORY.getImmutableExpression( EQ, X0, X4); private final static ImmutableExpression EXPRESSION8 = DATA_FACTORY.getImmutableExpression( EQ, X0, X5); private final MetadataForQueryOptimization metadata; public PullOutVariableOptimizerTest() { this.metadata = initMetadata(); } private static MetadataForQueryOptimization initMetadata() { ImmutableMultimap.Builder<AtomPredicate, ImmutableList<Integer>> uniqueKeyBuilder = ImmutableMultimap.builder(); return new MetadataForQueryOptimizationImpl(uniqueKeyBuilder.build(), new UriTemplateMatcher()); } @Test public void testJoiningConditionTest1() throws EmptyQueryException { IntermediateQueryBuilder queryBuilder1 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode = new ConstructionNodeImpl(projectionAtom.getVariables()); InnerJoinNode joinNode1 = new InnerJoinNodeImpl(Optional.empty()); ExtensionalDataNode dataNode1 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, Y)); ExtensionalDataNode dataNode2 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X, Z)); queryBuilder1.init(projectionAtom, constructionNode); queryBuilder1.addChild(constructionNode, joinNode1); queryBuilder1.addChild(joinNode1, dataNode1); queryBuilder1.addChild(joinNode1, dataNode2); IntermediateQuery query1 = queryBuilder1.build(); System.out.println("\nBefore optimization: \n" + query1); PullOutVariableOptimizer pullOutVariableOptimizer = new PullOutVariableOptimizer(); IntermediateQuery optimizedQuery = pullOutVariableOptimizer.optimize(query1); System.out.println("\nAfter optimization: \n" + optimizedQuery); IntermediateQueryBuilder queryBuilder2 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom2 = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode2 = new ConstructionNodeImpl(projectionAtom.getVariables()); InnerJoinNode joinNode2 = new InnerJoinNodeImpl(Optional.of(EXPRESSION1)); ExtensionalDataNode dataNode3 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X0, Z)); queryBuilder2.init(projectionAtom2, constructionNode2); queryBuilder2.addChild(constructionNode2, joinNode2); queryBuilder2.addChild(joinNode2, dataNode1); queryBuilder2.addChild(joinNode2, dataNode3); IntermediateQuery query2 = queryBuilder2.build(); System.out.println("\nExpected: \n" + query2); assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(optimizedQuery, query2)); } @Test public void testJoiningConditionTest2() throws EmptyQueryException { IntermediateQueryBuilder queryBuilder1 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode = new ConstructionNodeImpl(projectionAtom.getVariables()); LeftJoinNode leftJoinNode1 = new LeftJoinNodeImpl(Optional.empty()); ExtensionalDataNode dataNode1 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, Y)); ExtensionalDataNode dataNode2 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE4_PREDICATE, X, Y, Z)); queryBuilder1.init(projectionAtom, constructionNode); queryBuilder1.addChild(constructionNode, leftJoinNode1); queryBuilder1.addChild(leftJoinNode1, dataNode1, NonCommutativeOperatorNode.ArgumentPosition.LEFT); queryBuilder1.addChild(leftJoinNode1, dataNode2, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query1 = queryBuilder1.build(); System.out.println("\nBefore optimization: \n" + query1); PullOutVariableOptimizer pullOutVariableOptimizer = new PullOutVariableOptimizer(); IntermediateQuery optimizedQuery = pullOutVariableOptimizer.optimize(query1); System.out.println("\nAfter optimization: \n" + optimizedQuery); IntermediateQueryBuilder queryBuilder2 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom2 = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode2 = new ConstructionNodeImpl(projectionAtom.getVariables()); LeftJoinNode leftJoinNode2 = new LeftJoinNodeImpl(ImmutabilityTools.foldBooleanExpressions(EXPRESSION1, EXPRESSION2)); ExtensionalDataNode dataNode3 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE4_PREDICATE, X0, Y1, Z)); queryBuilder2.init(projectionAtom2, constructionNode2); queryBuilder2.addChild(constructionNode2, leftJoinNode2); queryBuilder2.addChild(leftJoinNode2, dataNode1, NonCommutativeOperatorNode.ArgumentPosition.LEFT); queryBuilder2.addChild(leftJoinNode2, dataNode3, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query2 = queryBuilder2.build(); System.out.println("\nExpected: \n" + query2); assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(optimizedQuery, query2)); } @Test public void testJoiningConditionTest3() throws EmptyQueryException { IntermediateQueryBuilder queryBuilder1 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom1 = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE3, X, Y); ConstructionNode constructionNode1 = new ConstructionNodeImpl(projectionAtom1.getVariables()); LeftJoinNode leftJoinNode1 = new LeftJoinNodeImpl(Optional.empty()); ExtensionalDataNode dataNode1 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, X, Y)); ExtensionalDataNode dataNode2 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE4_PREDICATE, X, Y, X)); queryBuilder1.init(projectionAtom1, constructionNode1); queryBuilder1.addChild(constructionNode1, leftJoinNode1); queryBuilder1.addChild(leftJoinNode1, dataNode1, NonCommutativeOperatorNode.ArgumentPosition.LEFT); queryBuilder1.addChild(leftJoinNode1, dataNode2, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query1 = queryBuilder1.build(); System.out.println("\nBefore optimization: \n" + query1); PullOutVariableOptimizer pullOutVariableOptimizer = new PullOutVariableOptimizer(); IntermediateQuery optimizedQuery = pullOutVariableOptimizer.optimize(query1); System.out.println("\nAfter optimization: \n" + optimizedQuery); IntermediateQueryBuilder expectedQuery = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom2 = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE3, X, Y); ConstructionNode constructionNode2 = new ConstructionNodeImpl(projectionAtom1.getVariables()); LeftJoinNode leftJoinNode2 = new LeftJoinNodeImpl(ImmutabilityTools.foldBooleanExpressions(EXPRESSION1, EXPRESSION2, EXPRESSION7)); FilterNode filterNode1 = new FilterNodeImpl(EXPRESSION4); ExtensionalDataNode dataNode3 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, X2, Y)); ExtensionalDataNode dataNode4 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE4_PREDICATE, X0, Y1, X4)); expectedQuery.init(projectionAtom2, constructionNode2); expectedQuery.addChild(constructionNode2, leftJoinNode2); expectedQuery.addChild(leftJoinNode2, filterNode1, NonCommutativeOperatorNode.ArgumentPosition.LEFT); expectedQuery.addChild(filterNode1, dataNode3); expectedQuery.addChild(leftJoinNode2, dataNode4, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query2 = expectedQuery.build(); System.out.println("\nExpected: \n" + query2); assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(optimizedQuery, query2)); } @Test public void testJoiningConditionTest4() throws EmptyQueryException { IntermediateQueryBuilder queryBuilder1 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE1, X, Y, Z, W); ConstructionNode constructionNode = new ConstructionNodeImpl(projectionAtom.getVariables()); InnerJoinNode joinNode1 = new InnerJoinNodeImpl(Optional.empty()); LeftJoinNode leftJoinNode1 = new LeftJoinNodeImpl(Optional.empty()); ExtensionalDataNode dataNode1 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, Y)); ExtensionalDataNode dataNode2 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X, Z)); ExtensionalDataNode dataNode3 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE3_PREDICATE, X, W)); queryBuilder1.init(projectionAtom, constructionNode); queryBuilder1.addChild(constructionNode, joinNode1); queryBuilder1.addChild(joinNode1, dataNode1); queryBuilder1.addChild(joinNode1, leftJoinNode1); queryBuilder1.addChild(leftJoinNode1, dataNode2, NonCommutativeOperatorNode.ArgumentPosition.LEFT); queryBuilder1.addChild(leftJoinNode1, dataNode3, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query1 = queryBuilder1.build(); System.out.println("\nBefore optimization: \n" + query1); PullOutVariableOptimizer pullOutVariableOptimizer = new PullOutVariableOptimizer(); IntermediateQuery optimizedQuery = pullOutVariableOptimizer.optimize(query1); System.out.println("\nAfter optimization: \n" + optimizedQuery); IntermediateQueryBuilder expectedQueryBuilder = new DefaultIntermediateQueryBuilder(metadata); InnerJoinNode joinNode2 = new InnerJoinNodeImpl(Optional.of(EXPRESSION1)); LeftJoinNode leftJoinNode2 = new LeftJoinNodeImpl(Optional.of(EXPRESSION8)); ExtensionalDataNode dataNode4 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, Y)); ExtensionalDataNode dataNode5 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X0, Z)); ExtensionalDataNode dataNode6 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE3_PREDICATE, X5, W)); expectedQueryBuilder.init(projectionAtom, constructionNode); expectedQueryBuilder.addChild(constructionNode, joinNode2); expectedQueryBuilder.addChild(joinNode2, dataNode4); expectedQueryBuilder.addChild(joinNode2, leftJoinNode2); expectedQueryBuilder.addChild(leftJoinNode2, dataNode5, NonCommutativeOperatorNode.ArgumentPosition.LEFT); expectedQueryBuilder.addChild(leftJoinNode2, dataNode6, NonCommutativeOperatorNode.ArgumentPosition.RIGHT); IntermediateQuery query2 = expectedQueryBuilder.build(); System.out.println("\nExpected: \n" + query2); assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(optimizedQuery, query2)); } @Test public void testJoiningConditionTest5() throws EmptyQueryException { IntermediateQueryBuilder queryBuilder1 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode = new ConstructionNodeImpl(projectionAtom.getVariables()); InnerJoinNode joinNode1 = new InnerJoinNodeImpl(Optional.empty()); ExtensionalDataNode dataNode1 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE1_PREDICATE, X, Y)); ExtensionalDataNode dataNode2 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X, Z, Y)); queryBuilder1.init(projectionAtom, constructionNode); queryBuilder1.addChild(constructionNode, joinNode1); queryBuilder1.addChild(joinNode1, dataNode1); queryBuilder1.addChild(joinNode1, dataNode2); IntermediateQuery query1 = queryBuilder1.build(); System.out.println("\nBefore optimization: \n" + query1); PullOutVariableOptimizer pullOutVariableOptimizer = new PullOutVariableOptimizer(); IntermediateQuery optimizedQuery = pullOutVariableOptimizer.optimize(query1); System.out.println("\nAfter optimization: \n" + optimizedQuery); IntermediateQueryBuilder queryBuilder2 = new DefaultIntermediateQueryBuilder(metadata); DistinctVariableOnlyDataAtom projectionAtom2 = DATA_FACTORY.getDistinctVariableOnlyDataAtom(ANS1_PREDICATE2, X, Y, Z); ConstructionNode constructionNode2 = new ConstructionNodeImpl(projectionAtom.getVariables()); InnerJoinNode joinNode2 = new InnerJoinNodeImpl(ImmutabilityTools.foldBooleanExpressions(EXPRESSION1, EXPRESSION2)); ExtensionalDataNode dataNode3 = new ExtensionalDataNodeImpl(DATA_FACTORY.getDataAtom(TABLE2_PREDICATE, X0, Z, Y1)); queryBuilder2.init(projectionAtom2, constructionNode2); queryBuilder2.addChild(constructionNode2, joinNode2); queryBuilder2.addChild(joinNode2, dataNode1); queryBuilder2.addChild(joinNode2, dataNode3); IntermediateQuery query2 = queryBuilder2.build(); System.out.println("\nExpected: \n" + query2); assertTrue(IQSyntacticEquivalenceChecker.areEquivalent(optimizedQuery, query2)); } }
package emufog.reader; import emufog.graph.Graph; import emufog.settings.Settings; import java.io.IOException; import java.nio.file.Path; import java.util.List; /** * Abstract class providing the settings required for all input readers. */ public abstract class GraphReader { /* the settings to use for the read in graph */ protected final Settings settings; /** * Creates a new instance associated with the given settings. * * @param settings settings to use for the new graph */ GraphReader(Settings settings) { this.settings = settings; } public abstract Graph readGraph(List<Path> files) throws IOException, IllegalArgumentException; }
package test.baseline; import static org.mockito.Matchers.*; import static org.mockito.Mockito.*; import java.io.*; import java.util.*; import java.util.regex.*; import junit.framework.*; import aQute.bnd.build.*; import aQute.bnd.differ.*; import aQute.bnd.differ.Baseline.BundleInfo; import aQute.bnd.differ.Baseline.Info; import aQute.bnd.header.*; import aQute.bnd.osgi.*; import aQute.bnd.service.*; import aQute.bnd.service.diff.*; import aQute.bnd.version.*; import aQute.lib.collections.*; import aQute.lib.io.*; import aQute.libg.reporter.*; @SuppressWarnings("resource") public class BaselineTest extends TestCase { File tmp = new File("tmp").getAbsoluteFile(); Workspace workspace; public Workspace getWorkspace() throws Exception { if (workspace != null) return workspace; IO.delete(tmp); IO.copy(new File("testresources/ws"), tmp); return workspace = new Workspace(tmp); } public void tearDown() throws Exception { IO.delete(tmp); workspace = null; } public void testJava8DefaultMethods() throws Exception { Builder older = new Builder(); older.addClasspath( new File("java8/older/bin")); older.setExportPackage("*"); Jar o = older.build(); assertTrue(older.check()); Builder newer = new Builder(); newer.addClasspath( new File("java8/newer/bin")); newer.setExportPackage("*"); Jar n = newer.build(); assertTrue(newer.check()); DiffPluginImpl differ = new DiffPluginImpl(); Baseline baseline = new Baseline(older, differ); Set<Info> infoSet = baseline.baseline(n,o, null); assertEquals(1, infoSet.size()); for ( Info info : infoSet ) { assertTrue(info.mismatch); assertEquals( new Version(0,1,0), info.suggestedVersion); assertEquals(info.packageName, "api_default_methods"); } } /** * Check if we can ignore resources in the baseline. First build two jars * that are identical except for the b/b resource. Then do baseline on them. */ public void testIgnoreResourceDiff() throws Exception { Processor processor = new Processor(); DiffPluginImpl differ = new DiffPluginImpl(); differ.setIgnore("b/b"); Baseline baseline = new Baseline(processor, differ); Builder a = new Builder(); a.setProperty("-includeresource", "a/a;literal='aa',b/b;literal='bb'"); a.setProperty("-resourceonly", "true"); Jar aj = a.build(); Builder b = new Builder(); b.setProperty("-includeresource", "a/a;literal='aa',b/b;literal='bbb'"); b.setProperty("-resourceonly", "true"); Jar bj = b.build(); Set<Info> infoSet = baseline.baseline(aj, bj, null); BundleInfo binfo = baseline.getBundleInfo(); assertFalse(binfo.mismatch); a.close(); b.close(); } public static void testBaslineJar() throws Exception { // Workspace ws = new Workspace(new File("testresources/ws")); // Project p3 = ws.getProject("p3"); // ProjectBuilder builder = (ProjectBuilder) // p3.getBuilder(null).getSubBuilder(); // builder.setBundleSymbolicName("p3"); // // Nothing specified // Jar jar = builder.getBaselineJar(false); // assertNull(jar); // jar = builder.getBaselineJar(true); // assertEquals(".", jar.getName()); // // Fallback to release repo // builder.set("-releaserepo", "Repo"); // jar = builder.getBaselineJar(false); // assertNull(jar); // jar = builder.getBaselineJar(true); // assertEquals("p3", jar.getBsn()); // assertEquals("1.0.1", jar.getVersion()); // // -baselinerepo specified // builder.set("-baselinerepo", "Release"); // jar = builder.getBaselineJar(false); // assertEquals("p3", jar.getBsn()); // assertEquals("1.2.0", jar.getVersion()); // jar = builder.getBaselineJar(true); // assertEquals("p3", jar.getBsn()); // assertEquals("1.2.0", jar.getVersion()); // // -baseline specified // builder.set("-baseline", "p3;version=1.1.0"); // jar = builder.getBaselineJar(false); // assertEquals("p3", jar.getBsn()); // assertEquals("1.1.0", jar.getVersion()); // jar = builder.getBaselineJar(true); // assertEquals("p3", jar.getBsn()); // assertEquals("1.1.0", jar.getVersion()); } /** * When a JAR is build the manifest is not set in the resources but in a * instance var. * * @throws Exception */ public void testPrematureJar() throws Exception { Builder b1 = new Builder(); b1.addClasspath(IO.getFile(new File(""), "jar/osgi.jar")); b1.setProperty(Constants.BUNDLE_VERSION, "1.0.0.${tstamp}"); b1.setExportPackage("org.osgi.service.event"); Jar j1 = b1.build(); System.out.println(j1.getResources().keySet()); assertTrue(b1.check()); File tmp = new File("tmp.jar"); try { j1.write(tmp); Jar j11 = new Jar(tmp); Thread.sleep(2000); Builder b2 = new Builder(); b2.addClasspath(IO.getFile(new File(""), "jar/osgi.jar")); b2.setProperty(Constants.BUNDLE_VERSION, "1.0.0.${tstamp}"); b2.setExportPackage("org.osgi.service.event"); Jar j2 = b2.build(); assertTrue(b2.check()); System.out.println(j2.getResources().keySet()); DiffPluginImpl differ = new DiffPluginImpl(); ReporterAdapter ra = new ReporterAdapter(); Baseline baseline = new Baseline(ra, differ); ra.setTrace(true); ra.setPedantic(true); Set<Info> infos = baseline.baseline(j2, j11, null); print(baseline.getDiff(), " "); assertEquals(Delta.UNCHANGED, baseline.getDiff().getDelta()); } finally { tmp.delete(); } } static Pattern VERSION_HEADER_P = Pattern.compile("Bundle-Header:(" + Verifier.VERSION_STRING + ")", Pattern.CASE_INSENSITIVE); void print(Diff diff, String indent) { if (diff.getDelta() == Delta.UNCHANGED) return; System.out.println(indent + " " + diff); for (Diff sub : diff.getChildren()) { print(sub, indent + " "); } } /** * In repo: * * <pre> * p3-1.1.0.jar * p3-1.2.0.jar * </pre> * * @throws Exception */ public void testRepository() throws Exception { Jar v1_2_0_a = mock(Jar.class); when(v1_2_0_a.getVersion()).thenReturn("1.2.0.b"); when(v1_2_0_a.getBsn()).thenReturn("p3"); RepositoryPlugin repo = mock(RepositoryPlugin.class); getWorkspace().addBasicPlugin(repo); @SuppressWarnings("unchecked") Map<String,String> map = any(Map.class); when(repo.get(anyString(), any(Version.class), map)).thenReturn( IO.getFile("testresources/ws/cnf/releaserepo/p3/p3-1.2.0.jar")); System.out.println(repo.get("p3", new Version("1.2.0.b"), new Attrs())); when(repo.canWrite()).thenReturn(true); when(repo.getName()).thenReturn("Baseline"); when(repo.versions("p3")).thenReturn( new SortedList<Version>(new Version("1.1.0.a"), new Version("1.1.0.b"), new Version("1.2.0.a"), new Version("1.2.0.b"))); Project p3 = getWorkspace().getProject("p3"); p3.setBundleVersion("1.3.0"); ProjectBuilder builder = (ProjectBuilder) p3.getBuilder(null).getSubBuilder(); builder.setProperty(Constants.BASELINE, "*"); builder.setProperty(Constants.BASELINEREPO, "Baseline"); // Nothing specified Jar jar = builder.getBaselineJar(); assertEquals("1.2.0", new Version(jar.getVersion()).getWithoutQualifier().toString()); if (!builder.check()) fail(); { // check for error when repository contains later versions builder = (ProjectBuilder) p3.getBuilder(null).getSubBuilder(); builder.setBundleVersion("1.1.3"); builder.setTrace(true); builder.setProperty(Constants.BASELINE, "*"); builder.setProperty(Constants.BASELINEREPO, "Baseline"); jar = builder.getBaselineJar(); assertNull(jar); if (!builder.check("The baseline version 1.2.0.b is higher than the current version 1.1.3 for p3")) fail(); } { // check for no error when repository has the same version builder = (ProjectBuilder) p3.getBuilder(null).getSubBuilder(); builder.setBundleVersion("1.2.0.b"); builder.setTrace(true); builder.setProperty(Constants.BASELINE, "*"); builder.setProperty(Constants.BASELINEREPO, "Baseline"); jar = builder.getBaselineJar(); assertNotNull(jar); if (!builder.check()) fail(); } { // check for no error when repository has the same version builder = (ProjectBuilder) p3.getBuilder(null).getSubBuilder(); builder.setBundleVersion("1.2.0.b"); builder.setTrace(true); builder.setProperty(Constants.BASELINE, "*"); builder.setProperty(Constants.BASELINEREPO, "Baseline"); builder.build(); if (!builder.check("The bundle version \\(1.2.0/1.2.0\\) is too low, must be at least 1.3.0")) fail(); } } /** * Check what happens when there is nothing in the repo ... We do not * generate an error when version <=1.0.0, otherwise we generate an error. * * @throws Exception */ public void testNothingInRepo() throws Exception { File tmp = new File("tmp"); tmp.mkdirs(); try { RepositoryPlugin repo = mock(RepositoryPlugin.class); when(repo.canWrite()).thenReturn(true); when(repo.getName()).thenReturn("Baseline"); when(repo.versions("p3")).thenReturn(new TreeSet<Version>()); getWorkspace().addBasicPlugin(repo); Project p3 = getWorkspace().getProject("p3"); p3.setProperty(Constants.BASELINE, "*"); p3.setProperty(Constants.BASELINEREPO, "Baseline"); p3.setBundleVersion("0"); p3.build(); assertTrue(p3.check()); p3.setBundleVersion("1.0.0.XXXXXX"); p3.build(); assertTrue(p3.check()); p3.setBundleVersion("5"); p3.build(); assertTrue(p3.check("There is no baseline for p3 in the baseline repo")); } finally { IO.delete(tmp); } } // Adding a method to a ProviderType produces a MINOR bump (1.0.0 -> 1.1.0) public void testProviderTypeBump() throws Exception { Processor processor = new Processor(); DiffPluginImpl differ = new DiffPluginImpl(); Baseline baseline = new Baseline(processor, differ); Jar older = new Jar(new File("testresources/api-orig.jar")); Jar newer = new Jar(new File("testresources/api-providerbump.jar")); Set<Info> infoSet = baseline.baseline(newer, older, null); System.out.println(differ.tree(newer).get("<api>")); assertEquals(1, infoSet.size()); Info info = infoSet.iterator().next(); assertTrue(info.mismatch); assertEquals("dummy.api", info.packageName); assertEquals("1.1.0", info.suggestedVersion.toString()); } // Adding a method to a ConsumerType produces a MINOR bump (1.0.0 -> 2.0.0) public static void testConsumerTypeBump() throws Exception { Processor processor = new Processor(); DiffPluginImpl differ = new DiffPluginImpl(); Baseline baseline = new Baseline(processor, differ); Jar older = new Jar(new File("testresources/api-orig.jar")); Jar newer = new Jar(new File("testresources/api-consumerbump.jar")); Set<Info> infoSet = baseline.baseline(newer, older, null); assertEquals(1, infoSet.size()); Info info = infoSet.iterator().next(); assertTrue(info.mismatch); assertEquals("dummy.api", info.packageName); assertEquals("2.0.0", info.suggestedVersion.toString()); } }
package biomodel.parser; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import org.sbml.libsbml.ASTNode; import org.sbml.libsbml.KineticLaw; import org.sbml.libsbml.Model; import org.sbml.libsbml.ModifierSpeciesReference; import org.sbml.libsbml.Reaction; import org.sbml.libsbml.Rule; import org.sbml.libsbml.SBMLDocument; import org.sbml.libsbml.Species; import org.sbml.libsbml.SpeciesReference; import biomodel.annotation.AnnotationUtility; import biomodel.network.BaseSpecies; import biomodel.network.DiffusibleConstitutiveSpecies; import biomodel.network.DiffusibleSpecies; import biomodel.network.GeneticNetwork; import biomodel.network.Influence; import biomodel.network.Promoter; import biomodel.network.SpasticSpecies; import biomodel.network.SpeciesInterface; import biomodel.network.SynthesisNode; import biomodel.util.GlobalConstants; import sbol.SBOLSynthesizer; /** * This class parses a genetic circuit model. * * @author Nam Nguyen * */ public class GCMParser { private String separator; public GCMParser(String filename) { this(filename, false); } public GCMParser(String filename, boolean debug) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } //this.debug = debug; gcm = new BioModel(filename.substring(0, filename.length() - filename.split(separator)[filename.split(separator).length - 1] .length())); gcm.load(filename); data = new StringBuffer(); try { BufferedReader in = new BufferedReader(new FileReader(filename)); String str; while ((str = in.readLine()) != null) { data.append(str + "\n"); } in.close(); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("Error opening file"); } } public GCMParser(BioModel gcm, boolean debug) { if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } //this.debug = debug; this.gcm = gcm; } public GeneticNetwork buildNetwork() { SBMLDocument sbml = gcm.flattenModel(); if (sbml == null) return null; return buildTopLevelNetwork(sbml); } public GeneticNetwork buildTopLevelNetwork(SBMLDocument sbml) { speciesList = new HashMap<String, SpeciesInterface>(); promoterList = new HashMap<String, Promoter>(); complexMap = new HashMap<String, ArrayList<Influence>>(); partsMap = new HashMap<String, ArrayList<Influence>>(); // Need to first parse all species that aren't promoters before parsing promoters // since latter process refers to the species list for (long i=0; i<sbml.getModel().getNumSpecies(); i++) { Species species = sbml.getModel().getSpecies(i); if (!BioModel.isPromoterSpecies(species)) parseSpeciesData(sbml,species); } for (long i=0; i<sbml.getModel().getNumSpecies(); i++) { Species species = sbml.getModel().getSpecies(i); if (BioModel.isPromoterSpecies(species)) parsePromoterData(sbml,species); } GeneticNetwork network = new GeneticNetwork(speciesList, complexMap, partsMap, promoterList, gcm); network.setSBMLFile(gcm.getSBMLFile()); if (sbml != null) { network.setSBML(sbml); } return network; } public HashMap<String, SpeciesInterface> getSpecies() { return speciesList; } public void setSpecies(HashMap<String, SpeciesInterface> speciesList) { this.speciesList = speciesList; } public HashMap<String, Promoter> getPromoters() { return promoterList; } public void setPromoters(HashMap<String, Promoter> promoterList) { this.promoterList = promoterList; } private void parsePromoterData(SBMLDocument sbml, Species promoter) { Promoter p = new Promoter(); p.setId(promoter.getId()); promoterList.put(promoter.getId(), p); p.setInitialAmount(promoter.getInitialAmount()); String component = ""; String promoterId = promoter.getId(); if (promoter.getId().contains("__")) { component = promoter.getId().substring(0,promoter.getId().lastIndexOf("__")+2); promoterId = promoterId.substring(promoterId.lastIndexOf("__")+2); } Reaction production = sbml.getModel().getReaction(component+"Production_"+promoterId); if (production != null) { p.setCompartment(production.getCompartment()); if (production.getKineticLaw().getLocalParameter(GlobalConstants.ACTIVATED_STRING) != null) { p.setKact(production.getKineticLaw().getLocalParameter(GlobalConstants.ACTIVATED_STRING).getValue()); } else { p.setKact(sbml.getModel().getParameter(GlobalConstants.ACTIVATED_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.KBASAL_STRING) != null) { p.setKbasal(production.getKineticLaw().getLocalParameter(GlobalConstants.KBASAL_STRING).getValue()); } else { p.setKbasal(sbml.getModel().getParameter(GlobalConstants.KBASAL_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.OCR_STRING) != null) { p.setKoc(production.getKineticLaw().getLocalParameter(GlobalConstants.OCR_STRING).getValue()); } else { p.setKoc(sbml.getModel().getParameter(GlobalConstants.OCR_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING) != null) { p.setStoich(production.getKineticLaw().getLocalParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue()); } else { p.setStoich(sbml.getModel().getParameter(GlobalConstants.STOICHIOMETRY_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING)!=null && production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING)!=null) { p.setKrnap(production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING).getValue(), production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING).getValue()); } else { p.setKrnap(sbml.getModel().getParameter(GlobalConstants.FORWARD_RNAP_BINDING_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_RNAP_BINDING_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING)!=null && production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING)!=null) { p.setKArnap(production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING).getValue(), production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING).getValue()); } else { p.setKArnap(sbml.getModel().getParameter(GlobalConstants.FORWARD_ACTIVATED_RNAP_BINDING_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_ACTIVATED_RNAP_BINDING_STRING).getValue()); } for (long j = 0; j < production.getNumProducts(); j++) { SpeciesReference product = production.getProduct(j); if (!BioModel.isMRNASpecies(sbml.getModel().getSpecies(product.getSpecies()))) p.addOutput(product.getSpecies(),speciesList.get(product.getSpecies())); } for (long i = 0; i < production.getNumModifiers(); i++) { ModifierSpeciesReference modifier = production.getModifier(i); if (BioModel.isRepressor(modifier) || BioModel.isRegulator(modifier)) { for (long j = 0; j < production.getNumProducts(); j++) { SpeciesReference product = production.getProduct(j); Influence infl = new Influence(); infl.generateName(); infl.setType("tee"); infl.setInput(modifier.getSpecies()); if (BioModel.isMRNASpecies(sbml.getModel().getSpecies(product.getSpecies()))) { infl.setOutput("none"); } else { infl.setOutput(product.getSpecies()); // p.addOutput(product.getSpecies(),speciesList.get(product.getSpecies())); } p.addToReactionMap(modifier.getSpecies(), infl); p.addRepressor(modifier.getSpecies(), speciesList.get(modifier.getSpecies())); speciesList.get(modifier.getSpecies()).setRepressor(true); if (production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_"+modifier.getId()+"_"))!=null && production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_"+modifier.getId()+"_"))!=null) { infl.setRep(production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KREP_STRING.replace("_","_"+modifier.getId()+"_")).getValue(), production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KREP_STRING.replace("_","_"+modifier.getId()+"_")).getValue()); } else { infl.setRep(sbml.getModel().getParameter(GlobalConstants.FORWARD_KREP_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_KREP_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + modifier.getId() + "_r") != null) { infl.setCoop(production.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + modifier.getId() + "_r").getValue()); } else { infl.setCoop(sbml.getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue()); } } } if (BioModel.isActivator(modifier) || BioModel.isRegulator(modifier)) { for (long j = 0; j < production.getNumProducts(); j++) { SpeciesReference product = production.getProduct(j); Influence infl = new Influence(); infl.generateName(); infl.setType("vee"); infl.setInput(modifier.getSpecies()); if (BioModel.isMRNASpecies(sbml.getModel().getSpecies(product.getSpecies()))) { infl.setOutput("none"); } else { infl.setOutput(product.getSpecies()); // p.addOutput(product.getSpecies(),speciesList.get(product.getSpecies())); } p.addToReactionMap(modifier.getSpecies(), infl); p.addActivator(modifier.getSpecies(), speciesList.get(modifier.getSpecies())); speciesList.get(modifier.getSpecies()).setActivator(true); if (production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_"+modifier.getId()+"_"))!=null && production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_"+modifier.getId()+"_"))!=null) { infl.setAct(production.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KACT_STRING.replace("_","_"+modifier.getId()+"_")).getValue(), production.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KACT_STRING.replace("_","_"+modifier.getId()+"_")).getValue()); } else { infl.setAct(sbml.getModel().getParameter(GlobalConstants.FORWARD_KACT_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_KACT_STRING).getValue()); } if (production.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + modifier.getId() + "_a") != null) { infl.setCoop(production.getKineticLaw().getLocalParameter(GlobalConstants.COOPERATIVITY_STRING + "_" + modifier.getId() + "_a").getValue()); } else { infl.setCoop(sbml.getModel().getParameter(GlobalConstants.COOPERATIVITY_STRING).getValue()); } } } } sbml.getModel().removeReaction(production.getId()); } } /** * Parses the data and put it into the species * * @param name * the name of the species * @param properties * the properties of the species */ private void parseSpeciesData(SBMLDocument sbml,Species species) { SpeciesInterface speciesIF = null; String component = ""; String speciesId = species.getId(); if (species.getId().contains("__")) { component = species.getId().substring(0,species.getId().lastIndexOf("__")+2); speciesId = speciesId.substring(speciesId.lastIndexOf("__")+2); } Reaction degradation = sbml.getModel().getReaction(component+"Degradation_"+speciesId); Reaction diffusion = sbml.getModel().getReaction(component+"MembraneDiffusion_"+speciesId); Reaction constitutive = sbml.getModel().getReaction(component+"Constitutive_"+speciesId); Reaction complex = sbml.getModel().getReaction(component+"Complex_"+speciesId); /*if (property.getProperty(GlobalConstants.TYPE).contains(GlobalConstants.CONSTANT)) { speciesIF = new ConstantSpecies(); } else*/ if (diffusion != null && constitutive != null) { speciesIF = new DiffusibleConstitutiveSpecies(); speciesIF.setDiffusible(true); } else if (diffusion != null) { speciesIF = new DiffusibleSpecies(); speciesIF.setDiffusible(true); } else if (constitutive != null) { speciesIF = new SpasticSpecies(); speciesIF.setDiffusible(false); } else { speciesIF = new BaseSpecies(); speciesIF.setDiffusible(false); } speciesList.put(species.getId(), speciesIF); if (constitutive != null) { sbml.getModel().removeReaction(constitutive.getId()); } speciesIF.setType(BioModel.getSpeciesType(sbml,species.getId())); // String annotation = species.getAnnotationString().replace("<annotation>","").replace("</annotation>",""); // String [] annotations = annotation.split(","); // for (int i=0;i<annotations.length;i++) // if (annotations[i].startsWith(GlobalConstants.TYPE)) { // String [] type = annotations[i].split("="); // speciesIF.setType(type[1]); // } else if (annotations[i].startsWith(GlobalConstants.SBOL_RBS)) { // String [] type = annotations[i].split("="); // speciesIF.setRBS(type[1]); // } else if (annotations[i].startsWith(GlobalConstants.SBOL_ORF)) { // String [] type = annotations[i].split("="); // speciesIF.setORF(type[1]); if (species.isSetInitialAmount()) { speciesIF.setInitialAmount(species.getInitialAmount()); } else if (species.isSetInitialConcentration()) { speciesIF.setInitialConcentration(species.getInitialConcentration()); } if (degradation != null) { if (degradation.getKineticLaw().getLocalParameter(GlobalConstants.KDECAY_STRING)!=null) { speciesIF.setDecay(degradation.getKineticLaw().getLocalParameter(GlobalConstants.KDECAY_STRING).getValue()); } else { speciesIF.setDecay(sbml.getModel().getParameter(GlobalConstants.KDECAY_STRING).getValue()); } if (degradation.getAnnotationString().contains("grid") == false) sbml.getModel().removeReaction(degradation.getId()); } else { speciesIF.setDecay(0.0); } if (complex != null) { if (complex.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KCOMPLEX_STRING)!=null && complex.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KCOMPLEX_STRING)!=null) { speciesIF.setKc(complex.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_KCOMPLEX_STRING).getValue(), complex.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_KCOMPLEX_STRING).getValue()); } else { speciesIF.setKc(sbml.getModel().getParameter(GlobalConstants.FORWARD_KCOMPLEX_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_KCOMPLEX_STRING).getValue()); } } else { speciesIF.setKc(0.0,1.0); } if (diffusion != null) { if (diffusion.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_MEMDIFF_STRING)!=null && diffusion.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_MEMDIFF_STRING)!=null) { speciesIF.setKmdiff(diffusion.getKineticLaw().getLocalParameter(GlobalConstants.FORWARD_MEMDIFF_STRING).getValue(), diffusion.getKineticLaw().getLocalParameter(GlobalConstants.REVERSE_MEMDIFF_STRING).getValue()); } else { speciesIF.setKmdiff(sbml.getModel().getParameter(GlobalConstants.FORWARD_MEMDIFF_STRING).getValue(), sbml.getModel().getParameter(GlobalConstants.REVERSE_MEMDIFF_STRING).getValue()); } //sbml.getModel().removeReaction(diffusion.getId()); } else { speciesIF.setKmdiff(0.0,1.0); } /* if (property.containsKey(GlobalConstants.KASSOCIATION_STRING)) { specie.addProperty(GlobalConstants.KASSOCIATION_STRING, property.getProperty(GlobalConstants.KASSOCIATION_STRING)); } else { specie.addProperty(GlobalConstants.KASSOCIATION_STRING, gcm.getParameter(GlobalConstants.KASSOCIATION_STRING)); } if (property.containsKey(GlobalConstants.KECDIFF_STRING)) { specie.addProperty(GlobalConstants.KECDIFF_STRING, property.getProperty(GlobalConstants.KECDIFF_STRING)); } else { specie.addProperty(GlobalConstants.KECDIFF_STRING, gcm.getParameter(GlobalConstants.KECDIFF_STRING)); } if (property.containsKey(GlobalConstants.KECDECAY_STRING)) { specie.addProperty(GlobalConstants.KECDECAY_STRING, property.getProperty(GlobalConstants.KECDECAY_STRING)); } else { specie.addProperty(GlobalConstants.KECDECAY_STRING, gcm.getParameter(GlobalConstants.KECDECAY_STRING)); } */ speciesIF.setId(species.getId()); speciesIF.setName(species.getName()); speciesIF.setStateName(species.getId()); if (complex != null) { for (long i = 0; i < complex.getNumReactants(); i++) { Influence infl = new Influence(); infl.generateName(); infl.setType("plus"); infl.setCoop(complex.getReactant(i).getStoichiometry()); String input = complex.getReactant(i).getSpecies(); String output = complex.getProduct(0).getSpecies(); infl.setInput(input); infl.setOutput(output); //Maps complex species to complex formation influences of which they're outputs ArrayList<Influence> complexInfluences = null; if (complexMap.containsKey(output)) { complexInfluences = complexMap.get(output); } else { complexInfluences = new ArrayList<Influence>(); complexMap.put(output, complexInfluences); } complexInfluences.add(infl); //Maps part species to complex formation influences of which they're inputs complexInfluences = null; if (partsMap.containsKey(input)) { complexInfluences = partsMap.get(input); } else { complexInfluences = new ArrayList<Influence>(); partsMap.put(input, complexInfluences); } complexInfluences.add(infl); } sbml.getModel().removeReaction(complex.getId()); } } public boolean parsePromoterSbol(Model sbmlModel, Species sbmlPromoter) { // Create synthesis node corresponding to sbml promoter LinkedList<String> sbolURIs = AnnotationUtility.parseSBOLAnnotation(sbmlPromoter); SynthesisNode synNode = new SynthesisNode(sbmlPromoter.getMetaId(), sbolURIs); synMap.put(synNode.getId(), synNode); // Determine if promoter belongs to a component String component = ""; String promoterId = sbmlPromoter.getId(); if (sbmlPromoter.getId().contains("__")) { component = sbmlPromoter.getId().substring(0, sbmlPromoter.getId().lastIndexOf("__")+2); promoterId = promoterId.substring(promoterId.lastIndexOf("__")+2); } // Connect synthesis node for promoter to synthesis nodes for its products // Remove promoter production reaction from sbml Reaction production = sbmlModel.getModel().getReaction(component + "Production_" + promoterId); if (production != null) { for (long i = 0; i < production.getNumProducts(); i++) { String productMetaID = speciesMetaMap.get(production.getProduct(i).getSpecies()); synNode.addNextNode(synMap.get(productMetaID)); } sbmlModel.getModel().removeReaction(production.getId()); } return sbolURIs.size() > 0; } public boolean parseReactionSbol(Reaction sbmlReaction) { // Create synthesis node corresponding to sbml reaction LinkedList<String> sbolURIs = AnnotationUtility.parseSBOLAnnotation(sbmlReaction); SynthesisNode synNode = new SynthesisNode(sbmlReaction.getMetaId(), sbolURIs); synMap.put(synNode.getId(), synNode); // Connect synthesis nodes for reactants, modifiers to synthesis node for reaction for (long i = 0; i < sbmlReaction.getNumReactants(); i++) { String reactantMetaID = speciesMetaMap.get(sbmlReaction.getReactant(i).getSpecies()); synMap.get(reactantMetaID).addNextNode(synNode); } for (long i = 0; i < sbmlReaction.getNumModifiers(); i++) { String modifierMetaID = speciesMetaMap.get(sbmlReaction.getModifier(i).getSpecies()); synMap.get(modifierMetaID).addNextNode(synNode); } // Connect synthesis node for reaction to synthesis nodes for its products for (long i = 0; i < sbmlReaction.getNumProducts(); i++) { String productMetaID = speciesMetaMap.get(sbmlReaction.getProduct(i).getSpecies()); synNode.addNextNode(synMap.get(productMetaID)); } // Map global parameters to reactions in which they appear KineticLaw kl = sbmlReaction.getKineticLaw(); Set<String> localParams = new HashSet<String>(); for (long i = 0; i < kl.getNumParameters(); i++) { localParams.add(kl.getParameter(i).getId()); } for (String input : parseInputHelper(kl.getMath())) { if (!speciesMetaMap.containsKey(input) && !localParams.contains(input)) { if (!paramInputMap.containsKey(input)) paramInputMap.put(input, new HashSet<String>());; paramInputMap.get(input).add(sbmlReaction.getMetaId()); } } // for (long i = 0; i < kl.getNumParameters(); i++) { // String wet = kl.getParameter(i).getId(); // String wat = kl.getParameter(i).getName(); // if (!paramInputMap.containsKey(kl.getParameter(i).getName())) // paramInputMap.put(kl.getParameter(i).getName(), new HashSet<String>()); // paramInputMap.get(kl.getParameter(i).getName()).add(sbmlReaction.getId()); return sbolURIs.size() > 0; } public boolean parseRuleSbol(Rule sbmlRule) { // Create synthesis node corresponding to sbml rule LinkedList<String> sbolURIs = AnnotationUtility.parseSBOLAnnotation(sbmlRule); SynthesisNode synNode = new SynthesisNode(sbmlRule.getMetaId(), sbolURIs); synMap.put(synNode.getId(), synNode); // Connect synthesis nodes for input species to synthesis node for rule // or maps input parameters to rules for (String input : parseInputHelper(sbmlRule.getMath())) { if (speciesMetaMap.containsKey(input)) synMap.get(speciesMetaMap.get(input)).addNextNode(synNode); else { if (!paramInputMap.containsKey(input)) paramInputMap.put(input, new HashSet<String>()); paramInputMap.get(input).add(sbmlRule.getMetaId()); } } // Connects synthesis node for rule to synthesis node for its output species // or maps output parameter to rule String output = sbmlRule.getVariable(); if (output != null) { if (speciesMetaMap.containsKey(output)) synNode.addNextNode(synMap.get(speciesMetaMap.get(output))); else { if (!paramOutputMap.containsKey(output)) paramOutputMap.put(output, new HashSet<String>()); paramOutputMap.get(output).add(sbmlRule.getMetaId()); } } return sbolURIs.size() > 0; } public LinkedList<String> parseInputHelper(ASTNode astNode) { LinkedList<String> inputs = new LinkedList<String>(); for (long i = 0; i < astNode.getNumChildren(); i++) { ASTNode childNode = astNode.getChild(i); if (!childNode.isOperator() && !childNode.isNumber()) inputs.add(childNode.getName()); inputs.addAll(parseInputHelper(childNode)); } return inputs; } public boolean parseSpeciesSbol(Model sbmlModel, Species sbmlSpecies) { // Create synthesis node corresponding to sbml species LinkedList<String> sbolURIs = AnnotationUtility.parseSBOLAnnotation(sbmlSpecies); SynthesisNode synNode = new SynthesisNode(sbmlSpecies.getMetaId(), sbolURIs); synMap.put(synNode.getId(), synNode); // Determine if species belongs to a gcm component String component = ""; String speciesId = sbmlSpecies.getId(); if (sbmlSpecies.getId().contains("__")) { component = sbmlSpecies.getId().substring(0, sbmlSpecies.getId().lastIndexOf("__") + 2); speciesId = speciesId.substring(speciesId.lastIndexOf("__")+2); } // Remove species degradation reaction from sbml Reaction degradation = sbmlModel.getReaction(component + "Degradation_" + speciesId); if (degradation != null) sbmlModel.removeReaction(degradation.getId()); // Remove species diffusion reaction from sbml Reaction diffusion = sbmlModel.getReaction(component + "MembraneDiffusion_" + speciesId); if (diffusion != null) sbmlModel.removeReaction(diffusion.getId()); // Remove species constitutive production reaction from sbml Reaction constitutive = sbmlModel.getReaction(component + "Constitutive_" + speciesId); if (constitutive != null) sbmlModel.removeReaction(constitutive.getId()); // Build complex map for use in connecting synthesis nodes // Remove species complex formation reaction from sbml Reaction complexFormation = sbmlModel.getReaction(component + "Complex_" + speciesId); if (complexFormation != null) { for (long i = 0; i < complexFormation.getNumReactants(); i++) { Influence infl = new Influence(); String inputMetaID = speciesMetaMap.get(complexFormation.getReactant(i).getSpecies()); String outputMetaID = speciesMetaMap.get(complexFormation.getProduct(0).getSpecies()); infl.setInput(inputMetaID); //Maps complex species to complex formation influences of which they're outputs ArrayList<Influence> complexInfluences = null; if (complexMap.containsKey(outputMetaID)) { complexInfluences = complexMap.get(outputMetaID); } else { complexInfluences = new ArrayList<Influence>(); complexMap.put(outputMetaID, complexInfluences); } complexInfluences.add(infl); } sbmlModel.getModel().removeReaction(complexFormation.getId()); } return sbolURIs.size() > 0; } public void connectMappedSynthesisNodes() { // Connect synthesis nodes for species that form complexes for (String complexId : complexMap.keySet()) for (Influence infl : complexMap.get(complexId)) synMap.get(infl.getInput()).addNextNode(synMap.get(complexId)); // Connect synthesis nodes for rules to synthesis nodes for rules or reactions on the basis of shared parameters for (String param : paramInputMap.keySet()) if (paramOutputMap.containsKey(param)) for (String origin : paramOutputMap.get(param)) for (String destination : paramInputMap.get(param)) synMap.get(origin).addNextNode(synMap.get(destination)); } public SBOLSynthesizer buildSbolSynthesizer() { SBMLDocument sbml = gcm.flattenModel(); if (sbml == null) return null; return buildTopLevelSbolSynthesizer(sbml); } // Now uses meta IDs rather than plain IDs to build up synthesis node network // Done primarily because rules have plain IDs that match their output parameter // This caused problems when connecting their synthesis nodes public SBOLSynthesizer buildTopLevelSbolSynthesizer(SBMLDocument sbml) { boolean sbolDetected = false; synMap = new HashMap<String, SynthesisNode>(); // initialize map of model element IDs to synthesis nodes complexMap = new HashMap<String, ArrayList<Influence>>(); paramInputMap = new HashMap<String, Set<String>>(); // initialize map of parameters to reactions in which they appear paramOutputMap = new HashMap<String, Set<String>>(); // initialize map of parameters to rules for which they're outputs speciesMetaMap = new HashMap<String, String>(); Model sbmlModel = sbml.getModel(); for (long i = 0; i < sbmlModel.getNumSpecies(); i++) { Species sbmlSpecies = sbmlModel.getSpecies(i); speciesMetaMap.put(sbmlSpecies.getId(), sbmlSpecies.getMetaId()); } // Create and connect synthesis nodes for species and promoters // Note that all non-promoter species must be parsed first since parsePromoterSbol may refer to them // when connecting synthesis nodes for (long i = 0 ; i < sbmlModel.getNumSpecies(); i++) { Species sbmlSpecies = sbmlModel.getSpecies(i); if (!BioModel.isPromoterSpecies(sbmlSpecies)) if (parseSpeciesSbol(sbmlModel, sbmlSpecies)) sbolDetected = true; } for (long i = 0 ; i < sbmlModel.getNumSpecies(); i++) { Species sbmlSpecies = sbmlModel.getSpecies(i); if (BioModel.isPromoterSpecies(sbmlSpecies)) if (parsePromoterSbol(sbmlModel, sbmlSpecies)) sbolDetected = true; } // Create and connect synthesis nodes for reactions not auto-generated by iBioSim for (long i = 0 ; i < sbmlModel.getNumReactions(); i++) { if (parseReactionSbol(sbmlModel.getReaction(i))) sbolDetected = true; } for (long i = 0; i < sbmlModel.getNumRules(); i++) { if (parseRuleSbol(sbmlModel.getRule(i))) sbolDetected = true; } // Finishes connecting synthesis nodes in accordance with various maps (see above) if (sbolDetected) { connectMappedSynthesisNodes(); SBOLSynthesizer synthesizer = new SBOLSynthesizer(synMap.values()); return synthesizer; } else return null; } /* public void setParameters(HashMap<String, String> parameters) { gcm.setParameters(parameters); } */ // Holds the text of the GCM private StringBuffer data = null; private HashMap<String, SpeciesInterface> speciesList; private HashMap<String, Promoter> promoterList; private HashMap<String, ArrayList<Influence>> complexMap; private HashMap<String, ArrayList<Influence>> partsMap; private HashMap<String, SynthesisNode> synMap; private HashMap<String, Set<String>> paramInputMap; private HashMap<String, Set<String>> paramOutputMap; private HashMap<String, String> speciesMetaMap; private BioModel gcm = null; // A regex that matches information //private static final String STATE = "(^|\\n) *([^- \\n]*) *\\[(.*)\\]"; //private static final String REACTION = "(^|\\n) *([^ \\n]*) *\\-\\> *([^ \n]*) *\\[(.*)arrowhead=([^,\\]]*)(.*)"; //private static final String PROPERTY_NUMBER = "([a-zA-Z]+)=\"([\\d]*[\\.\\d]?\\d+)\""; // private static final String PROPERTY_STATE = "([a-zA-Z]+)=([^\\s,.\"]+)"; // private static final String PROPERTY_QUOTE = // "([a-zA-Z]+)=\"([^\\s,.\"]+)\""; //private static final String PROPERTY_STATE = "([a-zA-Z\\s\\-]+)=([^\\s,]+)"; // Debug level //private boolean debug = false; }
package com.randspy.tictactoe.console; import com.randspy.tictactoe.spies.SpyInput; import com.randspy.tictactoe.spies.SpyOutput; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class GameTest { private SpyInput input; private SpyOutput output; private Game game; private void setUserInputs(String ... numbers) { for (String number : numbers) { input.userInputs.add(number); } } @Before public void setUp() { output = new SpyOutput(); input = new SpyInput(); game = new Game(input, output); } @Test public void whenTieInTheEnd() { setUserInputs("5", "3", "4", "2", "9"); game.run(); String endResult = " "|o|x|x|\n" + " "|x|x|o|\n" + " "|o|o|x|\n" + " "There was a tie.\n"; String expectedResult = output.printedOutput.get(1) + output.printedOutput.get(0); assertEquals(expectedResult, endResult); assertEquals(expectedResult, endResult); } @Test public void whenComputerWins() { setUserInputs("5", "4", "7", "8"); game.run(); String endResult = " "|o|o|o|\n" + " "|x|x|o|\n" + " "|x|x| |\n" + " "Computer won.\n"; String expectedResult = output.printedOutput.get(1) + output.printedOutput.get(0); assertEquals(expectedResult, endResult); } @Test public void whenUserTriesToSetAlreadyUsedFieldShouldGetMessageWithWaring() { setUserInputs("5", "1", "4", "7", "8"); game.run(); String endResult = "Already occupied field.\n"; String expectedResult = output.printedOutput.get(output.printedOutput.size() - 6); assertEquals(expectedResult, endResult); } @Test public void whenUserTriesToSetNumberBelowRangeShouldGetMessageWithWaring() { setUserInputs("0", "5", "4", "7", "8"); game.run(); String endResult = "Illegal input.\n"; String expectedResult = output.printedOutput.get(output.printedOutput.size() - 3); assertEquals(expectedResult, endResult); } }
package au.com.mountainpass.ryvr; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.context.annotation.ComponentScan; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import au.com.mountainpass.inflector.springboot.InflectorApplication; import au.com.mountainpass.ryvr.config.RyvrConfiguration; import au.com.mountainpass.ryvr.jdbc.JdbcRyvr; import au.com.mountainpass.ryvr.model.RyvrsCollection; import au.com.mountainpass.ryvr.testclient.RyvrTestClient; import au.com.mountainpass.ryvr.testclient.model.RootResponse; import au.com.mountainpass.ryvr.testclient.model.RyvrResponse; import au.com.mountainpass.ryvr.testclient.model.RyvrsCollectionResponse; import au.com.mountainpass.ryvr.testclient.model.SwaggerResponse; import cucumber.api.Scenario; import cucumber.api.java.After; import cucumber.api.java.Before; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; @ComponentScan("au.com.mountainpass") @ContextConfiguration(classes = { InflectorApplication.class, RyvrConfiguration.class }) @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class StepDefs { @Autowired private RyvrTestClient client; @Autowired private EmbeddedDatabase db; @Autowired private JdbcTemplate jt; private RootResponse rootResponseFuture; private RyvrResponse ryvrResponse; @Autowired private RyvrsCollection ryvrsCollection; private RyvrsCollectionResponse ryvrsCollectionResponse; private SwaggerResponse swaggerResponseFuture; private String currentTable; private List<Map<String, String>> currentEvents; @Given("^a database \"([^\"]*)\"$") public void aDatabase(final String dbName) throws Throwable { db = new EmbeddedDatabaseBuilder().setName(dbName) .setType(EmbeddedDatabaseType.H2).setScriptEncoding("UTF-8") .ignoreFailedDrops(true).addScript("initH2.sql").build(); jt = new JdbcTemplate(db); } @When("^a request is made for the API Docs$") public void aRequestIsMadeForTheAPIDocs() throws Throwable { swaggerResponseFuture = client.getApiDocs(); } @When("^a request is made to the server's base URL$") public void aRequestIsMadeToTheServersBaseURL() throws Throwable { rootResponseFuture = client.getRoot(); } @Given("^a \"([^\"]*)\" ryvr for \"([^\"]*)\" for table \"([^\"]*)\" ordered by \"([^\"]*)\"$") public void aRyvrForForTableOrderedBy(final String name, final String dbName, final String table, String orderedBy) throws Throwable { final JdbcRyvr ryvr = new JdbcRyvr(name, jt, table, orderedBy); ryvrsCollection.addRyvr(ryvr); } @Given("^it has a table \"([^\"]*)\" with the following events$") public void itHasATableWithTheFollowingEvents(final String table, final List<Map<String, String>> events) throws Throwable { createTable(table); insertRows(table, events); } public void insertRows(final String table, final List<Map<String, String>> events) { jt.batchUpdate( "insert into " + table + "(ID, ACCOUNT, DESCRIPTION, AMOUNT) values (?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public int getBatchSize() { return events.size(); } @Override public void setValues(final PreparedStatement ps, final int i) throws SQLException { // TODO Auto-generated method stub final Map<String, String> row = events.get(i); ps.setInt(1, Integer.parseInt(row.get("ID"))); ps.setString(2, row.get("ACCOUNT")); ps.setString(3, row.get("DESCRIPTION")); ps.setBigDecimal(4, new BigDecimal(row.get("AMOUNT"))); } }); } public void createTable(final String name) { final StringBuffer statementBuffer = new StringBuffer(); statementBuffer.append("create table "); statementBuffer.append(name); // | ID | ACCOUNT | DESCRIPTION | AMOUNT | statementBuffer.append( " (ID INT, ACCOUNT VARCHAR, DESCRIPTION VARCHAR, AMOUNT Decimal(19,4))"); jt.execute(statementBuffer.toString()); } @Then("^it will contain$") public void itWillContain(final List<Map<String, String>> events) throws Throwable { ryvrResponse.assertHasItems(events); } @Then("^it will have the following links$") public void itWillHaveTheFollowingLinks(final List<String> links) throws Throwable { ryvrResponse.assertHasLinks(links); } @Then("^it will \\*not\\* have the following links$") public void itWillNotHaveTheFollowingLinks(final List<String> links) throws Throwable { ryvrResponse.assertDoesntHaveLinks(links); } @Before public void setUp(final Scenario scenario) { client.before(scenario); ryvrsCollection.clear(); } @After public void tearDown(final Scenario scenario) { client.after(scenario); if (db != null) { db.shutdown(); } } @Then("^the API Docs will contain an operation for getting the API Docs$") public void theAPIDocsWillContainAnPperationForGettingTheAPIDocs() throws Throwable { swaggerResponseFuture.assertHasGetApiDocsOperation(); } @Then("^the count of ryvrs will be (\\d+)$") public void theCountOfRyvrsWillBe(final int count) throws Throwable { ryvrsCollectionResponse.assertCount(count); } @Then("^the root entity will contain a link to the api-docs$") public void theRootEntityWillContainALinkToTheApiDocs() throws Throwable { rootResponseFuture.assertHasApiDocsLink(); } @Then("^the root entity will contain a link to the ryvrs$") public void theRootEntityWillContainALinkToTheRyvrs() throws Throwable { rootResponseFuture.assertHasRyvrsLink(); } @Then("^the root entity will have an application name of \"([^\"]*)\"$") public void theRootEntityWillHaveAnApplicationNameOf( final String applicationName) throws Throwable { rootResponseFuture.assertHasTitle(applicationName); } @When("^the \"([^\"]*)\" ryvr is retrieved$") public void theRyvrIsRetrieved(final String name) throws Throwable { ryvrResponse = client.getRyvr(name); } @When("^the ryvrs list is retrieved$") public void theRyvrsListIsRetrieved() throws Throwable { ryvrsCollectionResponse = client.getRyvrsCollection(); } @Then("^the ryvrs list will be empty$") public void theRyvrsListWillBeEmpty() throws Throwable { ryvrsCollectionResponse.assertIsEmpty(); } @Then("^the ryvrs list will contain the following entries$") public void theRyvrsListWillContainTheFollowingEntries( final List<String> names) throws Throwable { ryvrsCollectionResponse.assertHasItem(names); } @Given("^there are no ryvrs configured$") public void thereAreNoRyvrsConfigured() throws Throwable { // do nothing } @When("^the previous page is requested$") public void thePreviousPageIsRequested() throws Throwable { ryvrResponse = ryvrResponse.followLink("prev"); } @When("^the first page is requested$") public void theFirstPageIsRequested() throws Throwable { ryvrResponse = ryvrResponse.followLink("first"); } @When("^the current page is requested$") public void theCurrentPageIsRequested() throws Throwable { ryvrResponse = ryvrResponse.followLink("current"); } @When("^the next page is requested$") public void theNextPageIsRequested() throws Throwable { ryvrResponse = ryvrResponse.followLink("next"); } @When("^the self link is requested$") public void theSelfLinkIsRequested() throws Throwable { ryvrResponse = ryvrResponse.followLink("self"); } @Given("^it has a table \"([^\"]*)\" with the following structure$") public void itHasATableWithTheFollowingStructure(final String table, final List<String> structure) throws Throwable { createTable(table); this.currentTable = table; } @Given("^it has (\\d+) events$") public void itHasEvents(int noOfEvents) throws Throwable { List<Map<String, String>> events = new ArrayList<>(noOfEvents); for (int i = 0; i < noOfEvents; ++i) { Map<String, String> event = new HashMap<>(4); event.put("ID", Integer.toString(i)); event.put("ACCOUNT", "78901234"); event.put("DESCRIPTION", "Buying Stuff"); event.put("AMOUNT", Double.toString(i * -20.00 - i)); events.add(event); } this.currentEvents = events; insertRows(this.currentTable, events); } @Then("^it will have the following structure$") public void itWillHaveTheFollowingStructure(List<String> structure) throws Throwable { ryvrResponse.assertItemsHaveStructure(structure); } @Then("^it will have the last (\\d+) events$") public void itWillHaveTheLastEvents(int noOfEvents) throws Throwable { List<Map<String, String>> lastEvents = currentEvents.subList( currentEvents.size() - noOfEvents, currentEvents.size()); ryvrResponse.assertHasItems(lastEvents); } }
package eu.openanalytics.rsb; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.regex.Pattern; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; import javax.activation.MimetypesFileTypeMap; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig.Feature; import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion; import eu.openanalytics.rsb.rest.types.ErrorResult; import eu.openanalytics.rsb.rest.types.ObjectFactory; /** * Shared utilities. * * @author "OpenAnalytics &lt;rsb.development@openanalytics.eu&gt;" */ public abstract class Util { private final static Pattern APPLICATION_NAME_VALIDATOR = Pattern.compile("\\w+"); private final static ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper(); private final static ObjectMapper PRETTY_JSON_OBJECT_MAPPER = new ObjectMapper(); private final static JAXBContext ERROR_RESULT_JAXB_CONTEXT; private final static DatatypeFactory XML_DATATYPE_FACTORY; private static final MimetypesFileTypeMap MIMETYPES_FILETYPE_MAP = new MimetypesFileTypeMap(); private static final String DEFAULT_FILE_EXTENSION = "dat"; private static final Map<String, String> DEFAULT_FILE_EXTENSIONS = new HashMap<String, String>(); static { PRETTY_JSON_OBJECT_MAPPER.configure(Feature.INDENT_OUTPUT, true); PRETTY_JSON_OBJECT_MAPPER.configure(Feature.SORT_PROPERTIES_ALPHABETICALLY, true); PRETTY_JSON_OBJECT_MAPPER.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL); try { ERROR_RESULT_JAXB_CONTEXT = JAXBContext.newInstance(ErrorResult.class); XML_DATATYPE_FACTORY = DatatypeFactory.newInstance(); MIMETYPES_FILETYPE_MAP.addMimeTypes(Constants.JSON_CONTENT_TYPE + " json\n" + Constants.XML_CONTENT_TYPE + " xml\n" + Constants.TEXT_CONTENT_TYPE + " txt\n" + Constants.TEXT_CONTENT_TYPE + " R\n" + Constants.TEXT_CONTENT_TYPE + " Rnw\n" + Constants.PDF_CONTENT_TYPE + " pdf\n" + Constants.ZIP_CONTENT_TYPE + " zip"); } catch (final Exception e) { throw new IllegalStateException(e); } DEFAULT_FILE_EXTENSIONS.put(Constants.JSON_CONTENT_TYPE, "json"); DEFAULT_FILE_EXTENSIONS.put(Constants.XML_CONTENT_TYPE, "xml"); DEFAULT_FILE_EXTENSIONS.put(Constants.TEXT_CONTENT_TYPE, "txt"); DEFAULT_FILE_EXTENSIONS.put(Constants.PDF_CONTENT_TYPE, "pdf"); DEFAULT_FILE_EXTENSIONS.put(Constants.ZIP_CONTENT_TYPE, "zip"); } public final static ObjectFactory REST_OBJECT_FACTORY = new ObjectFactory(); public final static eu.openanalytics.rsb.soap.types.ObjectFactory SOAP_OBJECT_FACTORY = new eu.openanalytics.rsb.soap.types.ObjectFactory(); private Util() { throw new UnsupportedOperationException("do not instantiate"); } /** * Returns the must probable resource type for a MimeType. * * @param mimeType * @return */ public static String getResourceType(final MimeType mimeType) { final String result = DEFAULT_FILE_EXTENSIONS.get(mimeType.toString()); return result != null ? result : DEFAULT_FILE_EXTENSION; } /** * Returns the must probable content type for a file. * * @param file * @return "application/octet-stream" if unknown. */ public static String getContentType(final File file) { return MIMETYPES_FILETYPE_MAP.getContentType(file); } /** * Returns the must probable mime type for a file. * * @param file * @return {@link eu.openanalytics.rsb.Constants#DEFAULT_MIME_TYPE} if unknown. */ public static MimeType getMimeType(final File file) { try { return new MimeType(getContentType(file)); } catch (final MimeTypeParseException mtpe) { return Constants.DEFAULT_MIME_TYPE; } } /** * Builds a result URI. * * @param applicationName * @param jobId * @param httpHeaders * @param uriInfo * @return * @throws URISyntaxException */ public static URI buildResultUri(final String applicationName, final String jobId, final HttpHeaders httpHeaders, final UriInfo uriInfo) throws URISyntaxException { return getUriBuilder(uriInfo, httpHeaders).path(Constants.RESULTS_PATH).path(applicationName).path(jobId).build(); } /** * Builds a data directory URI. * * @param applicationName * @param jobId * @param httpHeaders * @param uriInfo * @return * @throws URISyntaxException */ public static URI buildDataDirectoryUri(final HttpHeaders httpHeaders, final UriInfo uriInfo, final String... directoryPathElements) throws URISyntaxException { UriBuilder uriBuilder = getUriBuilder(uriInfo, httpHeaders).path(Constants.DATA_DIR_PATH); for (final String directoryPathElement : directoryPathElements) { if (StringUtils.isNotEmpty(directoryPathElement)) { uriBuilder = uriBuilder.path(directoryPathElement); } } return uriBuilder.build(); } /** * Validates that the passed string is a valid application name. * * @param name * @return */ public static boolean isValidApplicationName(final String name) { return StringUtils.isNotBlank(name) && APPLICATION_NAME_VALIDATOR.matcher(name).matches(); } /** * Extracts an UriBuilder for the current request, taking into account the possibility of header-based URI override. * * @param uriInfo * @param httpHeaders * @return * @throws URISyntaxException */ public static UriBuilder getUriBuilder(final UriInfo uriInfo, final HttpHeaders httpHeaders) throws URISyntaxException { final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder(); final List<String> hosts = httpHeaders.getRequestHeader(HttpHeaders.HOST); if ((hosts != null) && (!hosts.isEmpty())) { final String host = hosts.get(0); uriBuilder.host(StringUtils.substringBefore(host, ":")); final String port = StringUtils.substringAfter(host, ":"); if (StringUtils.isNotBlank(port)) { uriBuilder.port(Integer.valueOf(port)); } } final String protocol = getSingleHeader(httpHeaders, Constants.FORWARDED_PROTOCOL_HTTP_HEADER); if (StringUtils.isNotBlank(protocol)) { uriBuilder.scheme(protocol); } return uriBuilder; } /** * Converts a {@link GregorianCalendar} into a {@link XMLGregorianCalendar} * * @param calendar * @return */ public static XMLGregorianCalendar convertToXmlDate(final GregorianCalendar calendar) { final GregorianCalendar zuluDate = new GregorianCalendar(); zuluDate.setTimeZone(TimeZone.getTimeZone("UTC")); zuluDate.setTimeInMillis(calendar.getTimeInMillis()); final XMLGregorianCalendar xmlDate = XML_DATATYPE_FACTORY.newXMLGregorianCalendar(zuluDate); return xmlDate; } /** * Gets the first header of multiple HTTP headers, returning null if no header is found for the name. * * @param httpHeaders * @param headerName * @return */ public static String getSingleHeader(final HttpHeaders httpHeaders, final String headerName) { final List<String> headers = httpHeaders.getRequestHeader(headerName); if ((headers == null) || (headers.isEmpty())) { return null; } return headers.get(0); } public static File createTemporaryDirectory(final String type) throws IOException { final File temp; temp = File.createTempFile("rsb_", type); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } return (temp); } /** * Marshals an {@link ErrorResult} to XML. * * @param errorResult * @return */ public static String toXml(final ErrorResult errorResult) { try { final Marshaller marshaller = ERROR_RESULT_JAXB_CONTEXT.createMarshaller(); final StringWriter sw = new StringWriter(); marshaller.marshal(errorResult, sw); return sw.toString(); } catch (final JAXBException je) { final String objectAsString = ToStringBuilder.reflectionToString(errorResult, ToStringStyle.SHORT_PREFIX_STYLE); throw new RuntimeException("Failed to XML marshall: " + objectAsString, je); } } /** * Marshals an {@link Object} to a JSON string. * * @param o * @return */ public static String toJson(final Object o) { try { return PRETTY_JSON_OBJECT_MAPPER.writeValueAsString(o); } catch (final IOException ioe) { final String objectAsString = ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE); throw new RuntimeException("Failed to JSON marshall: " + objectAsString, ioe); } } /** * Marshals an {@link Object} to a pretty-printed JSON file. * * @param o * @throws IOException */ public static void toPrettyJsonFile(final Object o, final File f) throws IOException { try { PRETTY_JSON_OBJECT_MAPPER.writeValue(f, o); } catch (final JsonProcessingException jpe) { final String objectAsString = ToStringBuilder.reflectionToString(o, ToStringStyle.SHORT_PREFIX_STYLE); throw new RuntimeException("Failed to JSON marshall: " + objectAsString, jpe); } } /** * Unmarshals a JSON string to a desired type. * * @param s * @return */ public static <T> T fromJson(final String s, final Class<T> clazz) { try { return JSON_OBJECT_MAPPER.readValue(s, clazz); } catch (final IOException ioe) { throw new RuntimeException("Failed to JSON unmarshall: " + s, ioe); } } }
package fxlauncher; import com.sun.javafx.application.ParametersImpl; import javax.xml.bind.JAXB; import java.io.IOException; import java.net.URI; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class CreateManifest { public static void main(String[] args) throws IOException { URI baseURI = URI.create(args[0]); String launchClass = args[1]; Path appPath = Paths.get(args[2]); FXManifest manifest = create(baseURI, launchClass, appPath); if (args.length > 3) { // Parse named parameters List<String> rawParams = new ArrayList<>(); rawParams.addAll(Arrays.asList(args).subList(3, args.length)); ParametersImpl params = new ParametersImpl(rawParams); Map<String, String> named = params.getNamed(); if (named != null) { // Configure cacheDir if (named.containsKey("cache-dir")) manifest.cacheDir = named.get("cache-dir"); // Configure acceptDowngrade if (named.containsKey("accept-downgrade")) manifest.acceptDowngrade = Boolean.valueOf(named.get("accept-downgrade")); } // Append the rest as manifest parameters StringBuilder rest = new StringBuilder(); for (String raw : params.getRaw()) { if (raw.startsWith("--cache-dir=")) continue; if (raw.startsWith("--accept-downgrade=")) continue; if (rest.length() > 0) rest.append(" "); rest.append(raw); } // Add the raw parameter string to the manifest if (rest.length() > 0) manifest.parameters = rest.toString(); } JAXB.marshal(manifest, appPath.resolve("app.xml").toFile()); } public static FXManifest create(URI baseURI, String launchClass, Path appPath) throws IOException { FXManifest manifest = new FXManifest(); manifest.ts = System.currentTimeMillis(); manifest.uri = baseURI; manifest.launchClass = launchClass; Files.walkFileTree(appPath, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!Files.isDirectory(file) && isJavaLibrary(file) && !file.getFileName().toString().startsWith("fxlauncher")) manifest.files.add(new LibraryFile(appPath, file)); return FileVisitResult.CONTINUE; } }); return manifest; } private static boolean isJavaLibrary(Path file) { String filename = file.getFileName().toString(); return filename.endsWith(".jar") || filename.endsWith(".war"); } }
/** * Created Dec 21, 2007 */ package com.crawljax.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; import org.w3c.dom.Document; /** * Test class for the XPathHelper class. * * @author mesbah * @version $Id$ */ public class XPathHelperTest { /** * Check if XPath building works correctly. */ @Test public void testGetXpathExpression() { final String html = "<body><div id='firstdiv'></div><div><span id='thespan'>" + "<a id='thea'>test</a></span></div></body>"; try { Document dom = Helper.getDocument(html); assertNotNull(dom); // first div String expectedXpath = "/HTML[1]/BODY[1]/DIV[1]"; String xpathExpr = XPathHelper.getXPathExpression(dom.getElementById("firstdiv")); assertEquals(expectedXpath, xpathExpr); // span expectedXpath = "/HTML[1]/BODY[1]/DIV[2]/SPAN[1]"; xpathExpr = XPathHelper.getXPathExpression(dom.getElementById("thespan")); assertEquals(expectedXpath, xpathExpr); expectedXpath = "/HTML[1]/BODY[1]/DIV[2]/SPAN[1]/A[1]"; xpathExpr = XPathHelper.getXPathExpression(dom.getElementById("thea")); assertEquals(expectedXpath, xpathExpr); } catch (Exception e) { fail(e.getMessage()); } } @Test public void testXPathLocation() { String html = "<HTML><LINK foo=\"bar\">woei</HTML>"; String xpath = "/HTML[1]/LINK[1]"; int start = XPathHelper.getXPathLocation(html, xpath); int end = XPathHelper.getCloseElementLocation(html, xpath); assertEquals(6, start); assertEquals(22, end); } @Test public void formatXPath() { String xPath = "//ul[@CLASS=\"Test\"]"; assertEquals("//UL[@class=\"Test\"]", XPathHelper.formatXPath(xPath)); } @Test public void getLastElementOfXPath() { String xPath = "/HTML/BODY/DIV/UL/LI[@class=\"Test\"]"; assertEquals("LI", XPathHelper.getLastElementXPath(xPath)); } @Test public void stripXPathToElement() { String xPath = "/HTML/BODY/DIV/UL/LI[@class=\"Test\"]"; assertEquals("/HTML/BODY/DIV/UL/LI", XPathHelper.stripXPathToElement(xPath)); } }
package com.iluwatar; /** * * Singleton class. * Eagerly initialized static instance guarantees thread * safety. * */ public class IvoryTower { private static IvoryTower instance = new IvoryTower(); private IvoryTower() { } public static IvoryTower getInstance() { return instance; } }
package com.jcabi.github; import com.jcabi.aspects.Tv; import javax.json.Json; import javax.json.JsonObject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.RandomStringUtils; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Assume; import org.junit.Test; /** * Test case for {@link RtContents}. * @author Andres Candal (andres.candal@rollasolution.com) * @version $Id$ * @since 0.8 * @checkstyle MultipleStringLiterals (300 lines) */ public final class RtContentsITCase { /** * RtContents can fetch readme file. * @throws Exception If some problem inside */ @Test public void canFetchReadmeFiles() throws Exception { final Repos repos = github().repos(); final Repo repo = RtContentsITCase.repo(repos); try { MatcherAssert.assertThat( repos.get(repo.coordinates()).contents().readme().path(), Matchers.equalTo("README.md") ); } finally { repos.remove(repo.coordinates()); } } /** * RtContents can get update file content. * @throws Exception If some problem inside */ @Test public void canUpdateFileContent() throws Exception { final Repos repos = github().repos(); final Repo repo = RtContentsITCase.repo(repos); final Contents contents = repos.get(repo.coordinates()).contents(); final String message = "commit message"; final String text = "new content"; try { final String path = RandomStringUtils.randomAlphabetic(Tv.TEN); final Content content = contents.create( this.jsonObject( path, new String( Base64.encodeBase64("init content".getBytes()) ), message ) ); contents.update( path, Json.createObjectBuilder() .add("path", path) .add("message", message) .add("content", Base64.encodeBase64String(text.getBytes())) .add("sha", new Content.Smart(content).sha()).build() ); MatcherAssert.assertThat( new String( Base64.decodeBase64( new Content.Smart( contents.get(path, "master") ).content() ) ), Matchers.equalTo(text) ); } finally { repos.remove(repo.coordinates()); } } /** * RtContents can remove and throw an exception when get an absent content. * @throws Exception If some problem inside */ @Test(expected = AssertionError.class) public void throwsWhenTryingToGetAnAbsentContent() throws Exception { final Repos repos = github().repos(); final Repo repo = RtContentsITCase.repo(repos); final Contents contents = repos.get(repo.coordinates()).contents(); final String message = "commit message"; try { final String path = RandomStringUtils.randomAlphabetic(Tv.TEN); final Content content = contents.create( this.jsonObject( path, new String( Base64.encodeBase64("first content".getBytes()) ), message ) ); contents.remove( Json.createObjectBuilder() .add("path", path) .add("message", message) .add("sha", new Content.Smart(content).sha()).build() ); contents.get(path, "master"); } finally { repos.remove(repo.coordinates()); } } /** * RtContents can create file content. * @throws Exception If some problem inside */ @Test public void canCreateFileContent() throws Exception { final Repos repos = github().repos(); final Repo repo = RtContentsITCase.repo(repos); try { final String path = RandomStringUtils.randomAlphabetic(Tv.TEN); MatcherAssert.assertThat( repos.get(repo.coordinates()).contents().create( this.jsonObject( path, new String( Base64.encodeBase64("some content".getBytes()) ), "theMessage" ) ).path(), Matchers.equalTo(path) ); } finally { repos.remove(repo.coordinates()); } } /** * RtContents can get content. * @throws Exception If some problem inside */ @Test public void getContent() throws Exception { final Repos repos = github().repos(); final Repo repo = RtContentsITCase.repo(repos); try { final String path = RandomStringUtils.randomAlphanumeric(Tv.TEN); final String message = String.format("testMessage"); final String cont = new String( Base64.encodeBase64( String.format("content%d", System.currentTimeMillis()) .getBytes() ) ); final Contents contents = repos.get(repo.coordinates()).contents(); contents.create(this.jsonObject(path, cont, message)); final Content content = contents.get(path, "master"); MatcherAssert.assertThat( content.path(), Matchers.equalTo(path) ); MatcherAssert.assertThat( new Content.Smart(content).content(), Matchers.equalTo(String.format("%s\n", cont)) ); } finally { repos.remove(repo.coordinates()); } } /** * Create and return JsonObject of content. * @param path Content's path * @param cont Content's Base64 string * @param message Message * @return JsonObject */ private JsonObject jsonObject( final String path, final String cont, final String message ) { return Json.createObjectBuilder() .add("path", path) .add("message", message) .add("content", cont) .build(); } /** * Create and return repo to test. * * @param repos Repos * @return Repo * @throws Exception If some problem inside */ private static Repo repo(final Repos repos) throws Exception { return repos.create( Json.createObjectBuilder().add( "name", RandomStringUtils.randomAlphanumeric(Tv.TEN) ).build() ); } /** * Create and return github to test. * * @return Repo * @throws Exception If some problem inside */ private static Github github() throws Exception { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); return new RtGithub(key); } }
package com.composum.sling.platform.staging.impl; import com.composum.platform.commons.util.JcrIteratorUtil; import com.composum.sling.core.ResourceHandle; import com.composum.sling.core.util.CoreConstants; import com.composum.sling.core.util.ResourceUtil; import com.composum.sling.core.util.SlingResourceUtil; import com.composum.sling.platform.staging.*; import com.composum.sling.platform.staging.ReleaseChangeEvent; import com.composum.sling.platform.staging.impl.SiblingOrderUpdateStrategy.Result; import com.composum.sling.platform.staging.query.Query; import com.composum.sling.platform.staging.query.QueryBuilder; import com.google.common.collect.ImmutableMap; import org.apache.commons.collections4.IteratorUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.sling.api.SlingException; import org.apache.sling.api.resource.LoginException; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.NonExistingResource; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.sling.api.resource.ValueMap; import org.osgi.framework.Constants; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Modified; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.osgi.service.component.annotations.ReferencePolicy; import org.osgi.service.metatype.annotations.AttributeDefinition; import org.osgi.service.metatype.annotations.Designate; import org.osgi.service.metatype.annotations.ObjectClassDefinition; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.Property; import javax.jcr.PropertyType; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.version.Version; import javax.jcr.version.VersionException; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionManager; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; import static com.composum.sling.core.util.CoreConstants.JCR_UUID; import static com.composum.sling.core.util.CoreConstants.NT_VERSION; import static com.composum.sling.core.util.CoreConstants.PROP_MIXINTYPES; import static com.composum.sling.core.util.CoreConstants.PROP_PRIMARY_TYPE; import static com.composum.sling.core.util.CoreConstants.PROP_UUID; import static com.composum.sling.core.util.CoreConstants.TYPE_CREATED; import static com.composum.sling.core.util.CoreConstants.TYPE_LAST_MODIFIED; import static com.composum.sling.core.util.CoreConstants.TYPE_REFERENCEABLE; import static com.composum.sling.core.util.CoreConstants.TYPE_TITLE; import static com.composum.sling.core.util.CoreConstants.TYPE_UNSTRUCTURED; import static com.composum.sling.core.util.CoreConstants.TYPE_VERSIONABLE; import static com.composum.sling.platform.staging.StagingConstants.CURRENT_RELEASE; import static com.composum.sling.platform.staging.StagingConstants.NODE_RELEASES; import static com.composum.sling.platform.staging.StagingConstants.NODE_RELEASE_METADATA; import static com.composum.sling.platform.staging.StagingConstants.NODE_RELEASE_ROOT; import static com.composum.sling.platform.staging.StagingConstants.PROP_CLOSED; import static com.composum.sling.platform.staging.StagingConstants.PROP_DEACTIVATED; import static com.composum.sling.platform.staging.StagingConstants.PROP_LAST_ACTIVATED; import static com.composum.sling.platform.staging.StagingConstants.PROP_LAST_ACTIVATED_BY; import static com.composum.sling.platform.staging.StagingConstants.PROP_LAST_DEACTIVATED; import static com.composum.sling.platform.staging.StagingConstants.PROP_LAST_DEACTIVATED_BY; import static com.composum.sling.platform.staging.StagingConstants.PROP_PREVIOUS_RELEASE_UUID; import static com.composum.sling.platform.staging.StagingConstants.PROP_RELEASE_ROOT_HISTORY; import static com.composum.sling.platform.staging.StagingConstants.PROP_VERSION; import static com.composum.sling.platform.staging.StagingConstants.PROP_VERSIONABLEUUID; import static com.composum.sling.platform.staging.StagingConstants.PROP_VERSIONHISTORY; import static com.composum.sling.platform.staging.StagingConstants.RELEASE_LABEL_PREFIX; import static com.composum.sling.platform.staging.StagingConstants.RELEASE_ROOT_PATH; import static com.composum.sling.platform.staging.StagingConstants.TYPE_MIX_RELEASE_ROOT; import static com.composum.sling.platform.staging.StagingConstants.TYPE_VERSIONREFERENCE; import static java.util.Objects.requireNonNull; import static org.apache.jackrabbit.JcrConstants.*; /** * Default implementation of {@link StagingReleaseManager} - description see there. * * @see StagingReleaseManager */ @Component( service = {StagingReleaseManager.class}, property = { Constants.SERVICE_DESCRIPTION + "=Composum Platform Staging Release Manager" } ) @Designate(ocd = DefaultStagingReleaseManager.Configuration.class) public class DefaultStagingReleaseManager implements StagingReleaseManager { private static final Logger LOG = LoggerFactory.getLogger(DefaultStagingReleaseManager.class); private final SiblingOrderUpdateStrategy siblingOrderUpdateStrategy = new SiblingOrderUpdateStrategy(); protected Configuration configuration; @Reference protected ReleaseChangeEventPublisher publisher; @Reference protected ResourceResolverFactory resolverFactory; protected final List<StagingReleaseManagerPlugin> plugins = Collections.synchronizedList(new ArrayList<>()); /** * Random number generator for creating unique ids etc. */ protected final Random random = new SecureRandom(); public DefaultStagingReleaseManager() { } @Reference( service = StagingReleaseManagerPlugin.class, policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE ) protected void addReleaseManagerPlugin(@NotNull StagingReleaseManagerPlugin plugin) { LOG.info("Adding plugin {}@{}", plugin.getClass().getName(), System.identityHashCode(plugin)); plugins.removeIf(stagingReleaseManagerPlugin -> stagingReleaseManagerPlugin == plugin); plugins.add(plugin); } @SuppressWarnings("unused") protected void removeReleaseManagerPlugin(@NotNull StagingReleaseManagerPlugin plugin) { LOG.info("Removing plugin {}@{}", plugin.getClass().getName(), System.identityHashCode(plugin)); plugins.removeIf(stagingReleaseManagerPlugin -> stagingReleaseManagerPlugin == plugin); } @Activate @Deactivate @Modified public void updateConfig(Configuration configuration) { this.configuration = configuration; } @NotNull @Override public ResourceHandle findReleaseRoot(@NotNull Resource resource) throws ReleaseRootNotFoundException { Objects.requireNonNull(resource,"resource was null"); Resource result; String path = ResourceUtil.normalize(resource.getPath()); if (SlingResourceUtil.isSameOrDescendant(RELEASE_ROOT_PATH, path)) { String releaseTreePath = path.substring(RELEASE_ROOT_PATH.length()); result = new NonExistingResource(resource.getResourceResolver(), releaseTreePath); } else { result = resource; } while (result != null && !ResourceUtil.isNodeType(result, TYPE_MIX_RELEASE_ROOT)) { result = result.getParent(); } if (result == null) { throw new ReleaseRootNotFoundException(SlingResourceUtil.getPath(resource)); } return ResourceHandle.use(result); } @NotNull @Override public List<Release> getReleases(@NotNull Resource resource) { ResourceHandle root = findReleaseRoot(resource); if (root == null) { return Collections.emptyList(); } ensureCurrentRelease(root); return getReleasesImpl(root); } /** * Finds the node below which the release data is saved - see {@link StagingConstants#RELEASE_ROOT_PATH}. */ @NotNull protected ResourceHandle getReleasesNode(@NotNull Resource releaseRoot) { return ResourceHandle.use(releaseRoot.getResourceResolver().getResource(getReleasesNodePath(releaseRoot))); } @NotNull private String getReleasesNodePath(@NotNull Resource releaseRoot) { return RELEASE_ROOT_PATH + releaseRoot.getPath() + '/' + NODE_RELEASES; } @NotNull protected List<Release> getReleasesImpl(@NotNull Resource resource) { List<Release> result = new ArrayList<>(); ResourceHandle root = findReleaseRoot(resource); if (root != null) { ResourceHandle releasesNode = getReleasesNode(root); if (releasesNode.isValid()) { for (Resource releaseNode : releasesNode.getChildren()) { ReleaseImpl release = new ReleaseImpl(root, releaseNode); result.add(release); } } } result.sort(Comparator.comparing(Release::getNumber, ReleaseNumberCreator.COMPARATOR_RELEASES)); return result; } protected ReleaseImpl ensureCurrentRelease(@NotNull ResourceHandle root) { ResourceHandle releasesNode = getReleasesNode(root); Resource currentReleaseNode = releasesNode.isValid() ? releasesNode.getChild(CURRENT_RELEASE) : null; ReleaseImpl currentRelease = null; if (currentReleaseNode == null) { // implicitly create current release which should always be there. try { createCurrentReleaseWithServiceResolver(root); root.getResourceResolver().refresh(); releasesNode = getReleasesNode(root); currentReleaseNode = releasesNode.isValid() ? releasesNode.getChild(CURRENT_RELEASE) : null; if (currentReleaseNode != null) { currentRelease = new ReleaseImpl(root, currentReleaseNode); } else { LOG.warn("Release node not accessible for {} : {}", root.getResourceResolver().getUserID(), SlingResourceUtil.getPath(root)); } } catch (RepositoryException | PersistenceException | LoginException ex) { LOG.error("Trouble creating current release for " + root.getPath(), ex); } } else { currentRelease = new ReleaseImpl(root, currentReleaseNode); } return currentRelease; } /** * Create the current release using a service resolver since this can be a user who hasn't the rights, * and this can be called during a read operation where not having the rights is perfectly OK. * If there are other releases, we copy it from the highest numbered release. (That happens if you delete the * current release to reset it). */ protected void createCurrentReleaseWithServiceResolver(@NotNull ResourceHandle currentUserRoot) throws LoginException, PersistenceException, RepositoryException { try (ResourceResolver serviceResolver = resolverFactory.getServiceResourceResolver(null)) { Resource root = serviceResolver.getResource(currentUserRoot.getPath()); if (root == null) { LOG.warn("Service resolver can't access {}", currentUserRoot.getPath()); return; } ReleaseImpl currentRelease; Optional<Release> highestNumericRelease = getReleasesImpl(root).stream() .filter(r -> !CURRENT_RELEASE.equals(r.getNumber())) .max(Comparator.comparing(Release::getNumber, ReleaseNumberCreator.COMPARATOR_RELEASES)); if (highestNumericRelease.isPresent()) { currentRelease = createReleaseImpl(ResourceHandle.use(root), ReleaseImpl.unwrap(highestNumericRelease.get()), CURRENT_RELEASE); setPreviousRelease(currentRelease, highestNumericRelease.get()); serviceResolver.delete(currentRelease.getMetaDataNode()); // clear metadata and recreate the node } currentRelease = ensureRelease(root, CURRENT_RELEASE); serviceResolver.commit(); LOG.info("Created current release for {} with {}", currentUserRoot.getPath(), serviceResolver.getUserID()); } } @NotNull @Override public Release findRelease(@NotNull Resource resource, @NotNull String releaseNumber) { ResourceHandle root = findReleaseRoot(resource); if (releaseNumber.equals(CURRENT_RELEASE)) { ReleaseImpl release = ensureCurrentRelease(root); if (release == null) // weird trouble creating it { throw new ReleaseNotFoundException("Unexpected trouble creating or reading release."); } return release; } return findReleaseImpl(root, releaseNumber); } /** * Implementation that does not autocreate the current release, as {@link #findRelease(Resource, String)} does. */ @NotNull protected Release findReleaseImpl(@NotNull Resource resource, @NotNull String releaseNumber) { ResourceHandle root = findReleaseRoot(resource); ResourceHandle releaseNode = getReleasesNode(root); releaseNode = releaseNode.isValid() ? ResourceHandle.use(releaseNode.getChild(releaseNumber)) : null; if (releaseNode == null || !releaseNode.isValid()) { throw new ReleaseNotFoundException(); } return new ReleaseImpl(root, releaseNode); } @NotNull @Override public Release findReleaseByUuid(@NotNull Resource resource, @NotNull String releaseUuid) throws ReleaseNotFoundException { for (Release release : getReleasesImpl(resource)) { if (release.getUuid().equals(releaseUuid)) { return release; } } throw new ReleaseNotFoundException(); } @NotNull @Override @Deprecated public Release createRelease(@NotNull Release copyFromRelease, @NotNull ReleaseNumberCreator releaseType) throws ReleaseExistsException, PersistenceException, RepositoryException { if (CURRENT_RELEASE.equals(copyFromRelease.getNumber())) { throw new IllegalArgumentException("Cannot create release from current release."); } return createRelease(copyFromRelease.getReleaseRoot(), copyFromRelease, releaseType); } @NotNull @Override public Release resetCurrentTo(@NotNull Release release) throws PersistenceException, RepositoryException, ReleaseProtectedException { LOG.info("Resetting current to {}", release); deleteRelease(this.findReleaseImpl(release.getReleaseRoot(), CURRENT_RELEASE)); try { return createRelease(release, givenReleaseNumber(CURRENT_RELEASE)); } catch (ReleaseExistsException e) { // impossible since current was deleted. throw new RepositoryException("Bug.", e); } } @NotNull @Override public Map<String, String> nextRealeaseNumbers(@NotNull Resource resource) { ResourceHandle root = findReleaseRoot(resource); ReleaseImpl currentRelease = ReleaseImpl.unwrap(findRelease(root, StagingConstants.CURRENT_RELEASE)); try { Release previousRelease = currentRelease.getPreviousRelease(); if (previousRelease != null) { String lastNumber = previousRelease.getNumber(); return new LinkedHashMap<String, String>() {{ put(ReleaseNumberCreator.MAJOR.name(), ReleaseNumberCreator.MAJOR.bumpRelease(lastNumber).substring(1)); put(ReleaseNumberCreator.MINOR.name(), ReleaseNumberCreator.MINOR.bumpRelease(lastNumber).substring(1)); put(ReleaseNumberCreator.BUGFIX.name(), ReleaseNumberCreator.BUGFIX.bumpRelease(lastNumber).substring(1)); }}; } } catch (RepositoryException ex) { LOG.error(ex.getMessage(), ex); } return new LinkedHashMap<String, String>() {{ // defaults for the first release put(ReleaseNumberCreator.MAJOR.name(), "1"); put(ReleaseNumberCreator.MINOR.name(), "0.1"); put(ReleaseNumberCreator.BUGFIX.name(), "0.0.1"); }}; } @NotNull @Override public Release finalizeCurrentRelease(@NotNull Resource resource, @NotNull ReleaseNumberCreator releaseType) throws ReleaseExistsException, RepositoryException, PersistenceException { ResourceHandle root = findReleaseRoot(resource); ReleaseImpl currentRelease = ReleaseImpl.unwrap(findRelease(root, StagingConstants.CURRENT_RELEASE)); String newReleaseNumber = currentRelease.getPreviousRelease() != null ? releaseType.bumpRelease(currentRelease.getPreviousRelease().getNumber()) : releaseType.bumpRelease(""); try { findReleaseImpl(root, newReleaseNumber); throw new ReleaseExistsException(root, newReleaseNumber); } catch (ReleaseNotFoundException e) { // expected } Session session = root.getResourceResolver().adaptTo(Session.class); session.move(currentRelease.getReleaseNode().getPath(), currentRelease.getReleaseNode().getParent().getPath() + "/" + newReleaseNumber); ReleaseImpl newRelease = ReleaseImpl.unwrap(findReleaseImpl(root, newReleaseNumber)); updateReleaseLabels(newRelease); closeRelease(newRelease); createReleaseImpl(root, newRelease, CURRENT_RELEASE); LOG.info("Finalizing current release to {}", newRelease); return newRelease; } @NotNull protected Release createRelease(@NotNull Resource resource, @Nullable Release rawCopyFromRelease, @NotNull ReleaseNumberCreator releaseType) throws ReleaseExistsException, ReleaseNotFoundException, PersistenceException, RepositoryException { ResourceHandle root = findReleaseRoot(resource); ReleaseImpl copyFromRelease = rawCopyFromRelease != null ? ReleaseImpl.unwrap(rawCopyFromRelease) : ensureCurrentRelease(root); String newReleaseNumber = releaseType.bumpRelease(copyFromRelease.getNumber()); try { findReleaseImpl(root, newReleaseNumber); throw new ReleaseExistsException(root, newReleaseNumber); } catch (ReleaseNotFoundException e) { // expected } return createReleaseImpl(root, copyFromRelease, newReleaseNumber); } @NotNull protected ReleaseImpl createReleaseImpl(ResourceHandle root, ReleaseImpl copyFromRelease, String newReleaseNumber) throws RepositoryException, PersistenceException { cleanupLabels(root); ReleaseImpl newRelease = ensureRelease(root, newReleaseNumber); if (null != copyFromRelease) { new NodeTreeSynchronizer().update(copyFromRelease.getReleaseNode(), newRelease.getReleaseNode()); } setPreviousRelease(newRelease, copyFromRelease); ResourceHandle.use(newRelease.getReleaseNode()).setProperty(PROP_CLOSED, (String) null); updateReleaseLabels(newRelease); return newRelease; } protected void setPreviousRelease(Release rawNewRelease, Release rawPreviousRelease) throws RepositoryException { ReleaseImpl previousRelease = ReleaseImpl.unwrap(rawPreviousRelease); ReleaseImpl newRelease = ReleaseImpl.unwrap(rawNewRelease); String prevUuid = previousRelease != null ? previousRelease.getReleaseNode().getValueMap().get(JCR_UUID, String.class) : null; ResourceHandle.use(newRelease.getReleaseNode()).setProperty(PROP_PREVIOUS_RELEASE_UUID, prevUuid, PropertyType.REFERENCE); } @NotNull @Override public List<ReleasedVersionable> listReleaseContents(@NotNull Release rawRelease) { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); List<ReleasedVersionable> result = new ArrayList<>(); Resource releaseWorkspaceCopy = requireNonNull(release.getReleaseNode().getChild(NODE_RELEASE_ROOT)); Query query = release.getReleaseRoot() .getResourceResolver() .adaptTo(QueryBuilder.class) .createQuery(); query.path(releaseWorkspaceCopy.getPath()).type(TYPE_VERSIONREFERENCE); for (Resource versionReference : query.execute()) { result.add(ReleasedVersionable.fromVersionReference(releaseWorkspaceCopy, versionReference)); } return result; } @NotNull @Override public List<ReleasedVersionable> compareReleases(@NotNull Release release, @Nullable Release previousRelease) throws RepositoryException { List<ReleasedVersionable> result = new ArrayList<>(); if (previousRelease == null) { previousRelease = release.getPreviousRelease(); } if (previousRelease == null) // return everything { return listReleaseContents(release); } List<ReleasedVersionable> releaseContents = listReleaseContents(release); Map<String, ReleasedVersionable> releaseByVersionHistory = releaseContents.stream() .collect(Collectors.toMap(ReleasedVersionable::getVersionHistory, Function.identity())); List<ReleasedVersionable> previousContents = listReleaseContents(previousRelease); Map<String, ReleasedVersionable> previousByVersionHistory = previousContents.stream() .collect(Collectors.toMap(ReleasedVersionable::getVersionHistory, Function.identity())); for (ReleasedVersionable releasedVersionable : releaseContents) { if (!releasedVersionable.equals(previousByVersionHistory.get(releasedVersionable.getVersionHistory()))) { result.add(releasedVersionable); } } for (ReleasedVersionable previousVersionable : previousContents) { if (!releaseByVersionHistory.containsKey(previousVersionable.getVersionHistory())) { previousVersionable.setVersionUuid(null); result.add(previousVersionable); } } return result; } @NotNull @Override public List<ReleasedVersionable> listWorkspaceContents(@NotNull Resource resource) { ResourceHandle root = findReleaseRoot(resource); ensureCurrentRelease(ResourceHandle.use(root)); Query query = root.getResourceResolver() .adaptTo(QueryBuilder.class) .createQuery(); query.path(root.getPath()).type(TYPE_VERSIONABLE); List<ReleasedVersionable> result = new ArrayList<>(); for (Resource versionable : query.execute()) { result.add(ReleasedVersionable.forBaseVersion(versionable)); } return result; } @Nullable @Override public ReleasedVersionable findReleasedVersionableByUuid(@NotNull Release rawRelease, @NotNull String versionHistoryUuid) { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); Resource releaseWorkspaceCopy = release.getWorkspaceCopyNode(); Query query = releaseWorkspaceCopy.getResourceResolver() .adaptTo(QueryBuilder.class) .createQuery(); query.path(releaseWorkspaceCopy.getPath()).type(TYPE_VERSIONREFERENCE).condition( query.conditionBuilder().property(PROP_VERSIONHISTORY).eq().val(versionHistoryUuid) ); Iterator<Resource> versionReferences = query.execute().iterator(); Resource versionReference = versionReferences.hasNext() ? versionReferences.next() : null; return versionReference != null ? ReleasedVersionable.fromVersionReference(releaseWorkspaceCopy, versionReference) : null; } @Nullable @Override public ReleasedVersionable findReleasedVersionable(@NotNull Release rawRelease, @NotNull Resource versionable) { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); String expectedPath = release.mapToContentCopy(versionable.getPath()); Resource versionReference = versionable.getResourceResolver().getResource(expectedPath); if (ResourceUtil.isNonExistingResource(versionable)) { if (versionReference != null) { return ReleasedVersionable.fromVersionReference(release.getWorkspaceCopyNode(), versionReference); } return null; } ReleasedVersionable currentVersionable = ReleasedVersionable.forBaseVersion(versionable); if (versionReference != null) { // if it's at the expected path ReleasedVersionable releasedVersionable = ReleasedVersionable.fromVersionReference(release.getWorkspaceCopyNode(), versionReference); if (StringUtils.equals(releasedVersionable.getVersionHistory(), currentVersionable.getVersionHistory())) { return releasedVersionable; } } // otherwise we have to search (was moved or isn't present at all). return findReleasedVersionableByUuid(release, currentVersionable.getVersionHistory()); } @Nullable @Override public ReleasedVersionable findReleasedVersionable(@NotNull Release rawRelease, @NotNull String path) { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); String abspath = release.absolutePath(path); return findReleasedVersionable(release, new NonExistingResource(release.getReleaseRoot().getResourceResolver(), abspath)); } @NotNull @Override public Map<String, Result> updateRelease(@NotNull Release release, @NotNull List<ReleasedVersionable> releasedVersionableList) throws RepositoryException, PersistenceException, ReleaseClosedException, ReleaseChangeFailedException { ReleaseChangeEvent event = new ReleaseChangeEvent(release); Map<String, Result> result = new TreeMap<>(); for (ReleasedVersionable releasedVersionable : releasedVersionableList) { Map<String, Result> partialResult = updateReleaseInternal(release, releasedVersionable, event); result = Result.combine(result, partialResult); } applyPlugins(release, releasedVersionableList, event); publisher.publishActivation(event); return result; } @NotNull @Override public Map<String, Result> revert(@NotNull Release release, @NotNull String pathToRevert, @Nullable Release rawFromRelease) throws RepositoryException, PersistenceException , ReleaseClosedException, ReleaseChangeFailedException { Map<String, Result> result; ReleasedVersionable versionableInCurrentRelease = findReleasedVersionable(release, pathToRevert); if (rawFromRelease == null) { // special case: remove from release, e.g. if accidentially introduced. if (versionableInCurrentRelease != null) { versionableInCurrentRelease.setVersionUuid(null); return updateRelease(release, Collections.singletonList(versionableInCurrentRelease)); } else { return Collections.emptyMap(); } } ReleaseImpl fromRelease = requireNonNull(ReleaseImpl.unwrap(rawFromRelease)); pathToRevert = fromRelease.absolutePath(pathToRevert); ReleaseChangeEvent event = new ReleaseChangeEvent(release); ReleasedVersionable versionableInPreviousRelease = findReleasedVersionable(fromRelease, pathToRevert); if (versionableInPreviousRelease == null) { // remove whatever is there at that path, if there is anything if (versionableInCurrentRelease == null || !versionableInCurrentRelease.isActive()) { return new HashMap<>(); } versionableInCurrentRelease.setActive(false); return updateRelease(release, Collections.singletonList(versionableInCurrentRelease)); } else { // like updateRelease, but update parents from the previous release instead of the workspace, // and only if there originally was no parent. Resource versionReferenceResource = fromRelease.getWorkspaceCopyNode().getChild(versionableInPreviousRelease.getRelativePath()); result = new ReleaseUpdater(release, versionableInPreviousRelease, event, versionReferenceResource).callForRevert(); applyPlugins(release, Collections.singletonList(versionableInPreviousRelease), event); } publisher.publishActivation(event); return result; } @NotNull protected Map<String, Result> updateReleaseInternal(@NotNull Release rawRelease, @NotNull ReleasedVersionable releasedVersionable, ReleaseChangeEvent event) throws RepositoryException, PersistenceException, ReleaseClosedException { return new ReleaseUpdater(rawRelease, releasedVersionable, event).callForUpdate(); } /** * Method object that performs the heavy lifting for update or revert. We use a method object to be able to * structure things better without passing around gazillions of (possibly even return-)parameters. */ protected class ReleaseUpdater { @NotNull protected final ReleaseImpl release; @NotNull protected final ReleasedVersionable releasedVersionable; @NotNull protected final ReleaseChangeEvent event; protected final boolean delete; @NotNull protected final ResourceResolver resolver; protected Resource copiedVersionReferenceResource = null; protected final NodeTreeSynchronizer sync = new NodeTreeSynchronizer().addIgnoredAttributes(StagingConstants.PROP_CHANGE_NUMBER); protected Resource versionReference; protected final Resource releaseWorkspaceCopy; protected final String newPath; protected ReleasedVersionable previousRV; protected final Map<String, Result> result = new HashMap<>(); public ReleaseUpdater(@NotNull Release rawRelease, @NotNull ReleasedVersionable releasedVersionable, @NotNull ReleaseChangeEvent event) throws ReleaseClosedException, RepositoryException { this.releasedVersionable = releasedVersionable; delete = releasedVersionable.getVersionUuid() == null; this.event = event; release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); if (release.isClosed()) { throw new ReleaseClosedException(); } validateForUpdate(releasedVersionable, release); releaseWorkspaceCopy = release.getWorkspaceCopyNode(); newPath = releaseWorkspaceCopy.getPath() + '/' + releasedVersionable.getRelativePath(); resolver = release.getReleaseRoot().getResourceResolver(); determineCurrentUseInRelease(); } public ReleaseUpdater(@NotNull Release release, @NotNull ReleasedVersionable releasedVersionable, @NotNull ReleaseChangeEvent event, @Nullable Resource copiedVersionReferenceResource) throws ReleaseClosedException, RepositoryException { this(release, releasedVersionable, event); this.copiedVersionReferenceResource = copiedVersionReferenceResource; } /** * Finds out whether the releasedVersionable is already in the release-> versionReference, previousRV . */ protected void determineCurrentUseInRelease() { versionReference = releaseWorkspaceCopy.getResourceResolver().getResource(newPath); previousRV = versionReference != null ? ReleasedVersionable.fromVersionReference(releaseWorkspaceCopy, versionReference) : null; if (versionReference == null || !StringUtils.equals(previousRV.getVersionHistory(), releasedVersionable.getVersionHistory())) { // check whether it was moved. Caution: queries work only for comitted content Query query = releaseWorkspaceCopy.getResourceResolver() .adaptTo(QueryBuilder.class) .createQuery(); query.path(releaseWorkspaceCopy.getPath()).type(TYPE_VERSIONREFERENCE).condition( query.conditionBuilder().property(PROP_VERSIONABLEUUID).eq().val(releasedVersionable.getVersionableUuid()) ); Iterator<Resource> versionReferences = query.execute().iterator(); versionReference = versionReferences.hasNext() ? versionReferences.next() : null; previousRV = versionReference != null ? ReleasedVersionable.fromVersionReference(releaseWorkspaceCopy, versionReference) : null; } } public Map<String, Result> callForUpdate() throws RepositoryException, PersistenceException { moveOrCreateVersionReference(); if (!delete) { releasedVersionable.writeToVersionReference(releaseWorkspaceCopy, requireNonNull(versionReference)); adjustParentsDeletedFlags(); } bumpReleaseChangeNumber(release); release.updateLastModified(); updateReleaseLabel(); updateEvent(); updateParentsAndCreateResult(); return result; } public Map<String, Result> callForRevert() throws RepositoryException, PersistenceException { moveOrCreateVersionReference(); if (!delete) { releasedVersionable.writeToVersionReference(releaseWorkspaceCopy, requireNonNull(versionReference)); adjustParentsDeletedFlags(); } bumpReleaseChangeNumber(release); release.updateLastModified(); updateReleaseLabel(); updateEvent(); // do not update parents from workspace - we only update parents we create return result; } /** * We create, move or delete the versionReference, as appropriate for our operation. */ protected void moveOrCreateVersionReference() throws RepositoryException, PersistenceException { if (delete) { deleteVersionReference(); } else { // !delete if (versionReference == null) { createMissingParents(); versionReference = ResourceUtil.getOrCreateResource(release.getReleaseNode().getResourceResolver(), newPath, TYPE_UNSTRUCTURED + '/' + TYPE_VERSIONREFERENCE); } else if (!versionReference.getPath().equals(newPath)) { // move to a different path Resource oldParent = versionReference.getParent(); createMissingParents(); checkAndRemoveOldReferenceForMove(newPath); resolver.adaptTo(Session.class).move(versionReference.getPath(), newPath); versionReference = resolver.getResource(newPath); cleanupOrphans(releaseWorkspaceCopy.getPath(), oldParent); } else { // stays at same path String existingVersionHistory = versionReference.getValueMap().get(PROP_VERSIONHISTORY, String.class); if (!StringUtils.equals(existingVersionHistory, releasedVersionable.getVersionHistory())) { LOG.warn("Overriding a different versionable {} at the requested path {}", existingVersionHistory, releasedVersionable.getRelativePath()); } } } } /** * Deletes the version reference and now obsolete parent nodes without any child nodes left. */ protected void deleteVersionReference() throws PersistenceException { if (versionReference != null) { Resource parent = versionReference.getParent(); event.addMoveOrUpdate(versionReference.getPath(), null); resolver.delete(versionReference); cleanupOrphans(releaseWorkspaceCopy.getPath(), parent); } } /** * Removes old nodes that are not version references and have no children. That can happen when a versionreference * is moved to another node and there is no version reference left below it's old parent. */ protected void cleanupOrphans(String releaseWorkspaceCopyPath, Resource parent) throws PersistenceException { boolean inRelease = false; while (parent != null && (inRelease = StringUtils.startsWith(parent.getPath(), releaseWorkspaceCopyPath + "/")) && !parent.hasChildren() ) { Resource todelete = parent; parent = parent.getParent(); LOG.info("Deleting obsolete {}", todelete.getPath()); event.addMoveOrUpdate(todelete.getPath(), null); resolver.delete(todelete); } if (inRelease) { // parent is a node that has children maybeSetDeletedFlag(parent); } } /** * When moving, we need to check whether there already is a version reference. This one has to be deleted, * otherwise the move will fail. A warning is logged, but we assume the user knows what he is doing; it can * will show up in the version differences and can be reverted, anyway. */ protected void checkAndRemoveOldReferenceForMove(String newPath) throws PersistenceException { Resource resourceAtPath = resolver.getResource(newPath); if (resourceAtPath != null) { if (!ResourceUtil.isPrimaryType(resourceAtPath, TYPE_VERSIONREFERENCE)) { throw new IllegalArgumentException("Trying to replace a non-versionreference with a " + "versionreference - something is fishy, here: " + newPath); } VersionReferenceImpl oldVersionReference = new VersionReferenceImpl(release, resourceAtPath); ReleasedVersionable releasedVersionable = oldVersionReference.getReleasedVersionable(); resolver.delete(resourceAtPath); LOG.warn("Removing VersionReference that is going to be overwritten: {} : {}", newPath, releasedVersionable); } } protected void adjustParentsDeletedFlags() { if (releasedVersionable.isActive()) { resetDeletedFlag(versionReference.getParent()); } else { maybeSetDeletedFlag(versionReference.getParent()); } } /** * If a versionreference is active, we need to make sure all parents are active since it won't be visible otherwise. */ protected void resetDeletedFlag(Resource resource) { if (resource != null && SlingResourceUtil.isSameOrDescendant(release.getWorkspaceCopyNode().getPath(), resource.getPath())) { if (resource.getValueMap().get(PROP_DEACTIVATED, false)) { resource.adaptTo(ModifiableValueMap.class).remove(PROP_DEACTIVATED); event.addMoveOrUpdate(null, resource.getPath()); } resetDeletedFlag(resource.getParent()); } } /** * Check that all parents have either an active versionreference below or are marked as deactivated. */ protected void maybeSetDeletedFlag(Resource resource) { if (resource != null && SlingResourceUtil.isSameOrDescendant(release.getWorkspaceCopyNode().getPath(), resource.getPath())) { if (resource.getValueMap().get(PROP_DEACTIVATED, false)) { return; } if (!hasActiveVersionReferenceDescendant(resource)) { resource.adaptTo(ModifiableValueMap.class).put(PROP_DEACTIVATED, true); event.addMoveOrUpdate(resource.getPath(), null); maybeSetDeletedFlag(resource.getParent()); } } } protected boolean hasActiveVersionReferenceDescendant(Resource parent) { if (parent.getValueMap().get(PROP_DEACTIVATED, false)) { return false; } if (VersionReferenceImpl.isVersionReference(parent)) { return true; } for (Resource child : parent.getChildren()) { if (hasActiveVersionReferenceDescendant(child)) { return true; } } return false; } protected void createMissingParents() throws RepositoryException, PersistenceException { if (copiedVersionReferenceResource == null) { createParentNodesWithoutTemplate(ResourceUtil.getParent(newPath)); } else { copyParentIfMissing(ResourceUtil.getParent(newPath), copiedVersionReferenceResource.getParent()); } } @NotNull protected Resource createParentNodesWithoutTemplate(String path) throws PersistenceException { Resource nodeResource = resolver.getResource(path); if (null == nodeResource) { Resource parent = createParentNodesWithoutTemplate(ResourceUtil.getParent(path)); Map<String, Object> props = ImmutableMap.of(PROP_PRIMARY_TYPE, TYPE_UNSTRUCTURED, ResourceUtil.JCR_FROZENPRIMARYTYPE, TYPE_UNSTRUCTURED); nodeResource = resolver.create(parent, ResourceUtil.getName(path), props); event.addMoveOrUpdate(null, path); } return nodeResource; } /** * Create all levels of parents; on the first created parent update the sibling order. * * @return the possibly created node with path nodeToCreate */ @NotNull protected Resource copyParentIfMissing(String nodeToCreate, Resource nodeTemplate) throws RepositoryException { String parentPath = ResourceUtil.getParent(nodeToCreate); Resource parent = resolver.getResource(parentPath); boolean updateSiblingOrderOnCreate = false; if (parent == null) { parent = copyParentIfMissing(parentPath, nodeTemplate.getParent()); } else { updateSiblingOrderOnCreate = true; } String nodeName = ResourceUtil.getName(nodeToCreate); Resource node = parent.getChild(nodeName); if (node == null) { node = ResourceUtil.getOrCreateChild(parent, nodeName, TYPE_UNSTRUCTURED); sync.updateAttributes(ResourceHandle.use(nodeTemplate), ResourceHandle.use(node), StagingConstants.REAL_PROPNAMES_TO_FROZEN_NAMES); if (updateSiblingOrderOnCreate) { updateSiblingOrderAndSaveResult(ResourceHandle.use(nodeTemplate), ResourceHandle.use(node)); } event.addMoveOrUpdate(null, nodeToCreate); } return node; } protected void updateParentsAndCreateResult() throws RepositoryException { if (!delete && releasedVersionable.isActive()) { updateParentsFromWorkspace(); } } /** * Goes through all parents of the version reference, sets their attributes from the working copy * and fixes the node ordering if necessary. */ protected void updateParentsFromWorkspace() throws RepositoryException { ResourceHandle template = ResourceHandle.use(release.getReleaseRoot()); ResourceHandle inRelease = ResourceHandle.use(release.getWorkspaceCopyNode()); String[] levels = releasedVersionable.getRelativePath().split("/"); Iterator<String> levelIterator = IteratorUtils.arrayIterator(levels); while (template.isValid() && inRelease.isValid() && !inRelease.isOfType(TYPE_VERSIONREFERENCE)) { boolean attributesChanged = sync.updateAttributes(template, inRelease, StagingConstants.REAL_PROPNAMES_TO_FROZEN_NAMES); if (attributesChanged) { event.addMoveOrUpdate(template.getPath(), template.getPath()); } if (!levelIterator.hasNext()) { break; } String level = levelIterator.next(); template = ResourceHandle.use(template.getChild(level)); inRelease = ResourceHandle.use(inRelease.getChild(level)); if (template.isValid() && inRelease.isValid()) { // we do that for all nodes except the root but including the version reference itself: updateSiblingOrderAndSaveResult(template, inRelease); } } if (levelIterator.hasNext() && !template.isValid()) { throw new IllegalArgumentException("Could not copy attributes of parent nodes since node used as template not valid: " + inRelease.getPath()); } } protected void updateSiblingOrderAndSaveResult(ResourceHandle from, ResourceHandle to) throws RepositoryException { Result siblingResult = updateSiblingOrder(from, to); if (siblingResult != Result.unchanged) { String releasePath = release.unmapFromContentCopy(to.getPath()); String parent = ResourceUtil.getParent(releasePath); result.put(parent, siblingResult); event.addMoveOrUpdate(parent, parent); } } protected void updateEvent() { boolean wasThere = previousRV != null && previousRV.isActive() && previousRV.getVersionUuid() != null; String wasPath = wasThere ? release.absolutePath(previousRV.getRelativePath()) : null; boolean isThere = releasedVersionable.isActive() && releasedVersionable.getVersionUuid() != null; String isPath = isThere ? release.absolutePath(releasedVersionable.getRelativePath()) : null; if (wasThere || isThere) { event.addMoveOrUpdate(wasPath, isPath); } } /** * Sets the label {@link StagingConstants#RELEASE_LABEL_PREFIX}-{releasenumber} on the version the releasedVersionable refers to. */ protected void updateReleaseLabel() throws RepositoryException { Resource root = release.getReleaseRoot(); Session session = root.getResourceResolver().adaptTo(Session.class); if (session == null) { throw new RepositoryException("No session for " + root.getPath()); // impossible } VersionManager versionManager = session.getWorkspace().getVersionManager(); VersionHistory versionHistory = null; try { versionHistory = versionManager.getVersionHistory(release.getReleaseRoot().getPath() + '/' + releasedVersionable.getRelativePath()); if (!versionHistory.getIdentifier().equals(releasedVersionable.getVersionHistory())) { versionHistory = null; } } catch (PathNotFoundException e) { // moved or deleted. Try versionhistoryuuid } if (versionHistory == null) { versionHistory = (VersionHistory) session.getNodeByIdentifier(releasedVersionable.getVersionHistory()); } if (versionHistory == null) { LOG.debug("No version history anymore for {} : {}", release, releasedVersionable); return; } String label = release.getReleaseLabel(); if (StringUtils.isBlank(releasedVersionable.getVersionUuid())) { try { versionHistory.removeVersionLabel(label); } catch (VersionException e) { LOG.debug("Label {} wasn't set - OK.", label); } return; } for (Version version : JcrIteratorUtil.asIterable(versionHistory.getAllVersions())) { if (releasedVersionable.getVersionUuid().equals(version.getIdentifier())) { versionHistory.addVersionLabel(version.getName(), label, true); LOG.debug("Setting label {} on version {}", label, version.getIdentifier()); return; } } throw new IllegalArgumentException("Version not found for " + releasedVersionable + " in release " + release); } } protected void applyPlugins(Release rawRelease, List<ReleasedVersionable> releasedVersionableList, ReleaseChangeEvent event) throws RepositoryException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); ArrayList<StagingReleaseManagerPlugin> pluginscopy = new ArrayList<>(plugins); // avoid concurrent modifiation problems Set<String> changedPaths = new HashSet<>(); for (ReleasedVersionable releasedVersionable : releasedVersionableList) { changedPaths.add(release.mapToContentCopy(releasedVersionable.getRelativePath())); } for (StagingReleaseManagerPlugin plugin : pluginscopy) { plugin.fixupReleaseForChanges(release, release.getWorkspaceCopyNode(), changedPaths, event); } } /** * We check that the mandatory fields are set and that it isn't the root version. */ protected void validateForUpdate(ReleasedVersionable releasedVersionable, ReleaseImpl release) throws RepositoryException { Validate.notNull(releasedVersionable.getVersionHistory(), "No versionhistory set for %s/%s", release, releasedVersionable.getRelativePath()); Validate.notBlank(releasedVersionable.getRelativePath(), "No relative path set for %s %s", release, releasedVersionable); if (StringUtils.isNotBlank(releasedVersionable.getVersionUuid())) { Resource version = ResourceUtil.getByUuid(release.getReleaseRoot().getResourceResolver(), releasedVersionable.getVersionUuid()); Validate.isTrue(ResourceUtil.isPrimaryType(version, NT_VERSION), "Not a version: ", SlingResourceUtil.getPath(version)); Validate.isTrue(!"jcr:rootVersion".equals(version.getName()), "Versionable was never checked in: %s/%s", release, releasedVersionable.getRelativePath()); Validate.isTrue(StringUtils.equals(releasedVersionable.getVersionHistory(), version.getChild("..").getValueMap().get(JCR_UUID, String.class)), "Version history and version do not match for %s %s", release, releasedVersionable); } } /** * Sets the label on the versionables contained in all versionables in the release */ protected void updateReleaseLabels(@NotNull ReleaseImpl release) throws RepositoryException { for (Resource releaseContent : SlingResourceUtil.descendants(release.getWorkspaceCopyNode())) { if (ResourceUtil.isNodeType(releaseContent, TYPE_VERSIONREFERENCE)) { String versionUuid = releaseContent.getValueMap().get(PROP_VERSION, String.class); Resource version = ResourceUtil.getByUuid(releaseContent.getResourceResolver(), versionUuid); VersionHistory versionHistory = (VersionHistory) version.getParent().adaptTo(Node.class); versionHistory.addVersionLabel(version.getName(), release.getReleaseLabel(), true); } } } /** * Adjusts the place of {to} wrt. it's siblings to be consistent with {from}. * * @return true if the ordering was deterministic, false if there was heuristics involved and the user should check the result. */ protected Result updateSiblingOrder(ResourceHandle from, ResourceHandle to) throws RepositoryException { return getSiblingOrderUpdateStrategy().adjustSiblingOrderOfDestination(from, to); } protected SiblingOrderUpdateStrategy getSiblingOrderUpdateStrategy() { return siblingOrderUpdateStrategy; } @Override @NotNull public ResourceResolver getResolverForRelease(@NotNull Release release, @Nullable ReleaseMapper releaseMapper, boolean closeResolverOnClose) { return new StagingResourceResolver(release, ReleaseImpl.unwrap(release).getReleaseRoot().getResourceResolver(), releaseMapper != null ? releaseMapper : ReleaseMapper.ALLPERMISSIVE, configuration, closeResolverOnClose); } @Override public void setMark(@NotNull String mark, @Nullable Release rawRelease, boolean full) throws RepositoryException, ReleaseChangeFailedException { ReleaseImpl release = Objects.requireNonNull(ReleaseImpl.unwrap(rawRelease)); ResourceHandle releasesnode = ResourceHandle.use(release.getReleaseNode().getParent()); // the cpl:releases node // property type REFERENCE prevents deleting it accidentially releasesnode.setProperty(mark, release.getUuid(), PropertyType.REFERENCE); publisher.publishActivation(ReleaseChangeEvent.fullUpdate(release).setForceCheck(full)); } @Override public void deleteMark(@NotNull String mark, @NotNull Release rawRelease) throws RepositoryException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); ResourceHandle releasesnode = ResourceHandle.use(release.getReleaseNode().getParent()); // the cpl:releases node if (StringUtils.equals(mark, releasesnode.getProperty(mark, String.class))) { throw new IllegalArgumentException("Release does not carry mark " + mark + " : " + rawRelease); } releasesnode.setProperty(mark, (String) null); } @Override public void deleteRelease(@NotNull Release rawRelease) throws RepositoryException, PersistenceException, ReleaseProtectedException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); if (!release.getMarks().isEmpty()) { throw new ReleaseProtectedException(); } // check whether there are any releases pointing to this one as previous release. Reroute them to our predecessor. for (Release otherRelease : getReleasesImpl(release.getReleaseRoot())) { if (release.equals(otherRelease.getPreviousRelease())) { setPreviousRelease(otherRelease, release.getPreviousRelease()); } } release.getReleaseRoot().getResourceResolver().delete(release.getReleaseNode()); cleanupLabels(release.getReleaseRoot()); } @Nullable @Override public Release findReleaseByMark(@Nullable Resource resource, @NotNull String mark) throws ReleaseRootNotFoundException { if (resource == null) { return null; } ResourceHandle root = findReleaseRoot(resource); ResourceHandle releasesNode = getReleasesNode(root); if (!releasesNode.isValid()) { return null; } String uuid = releasesNode.getProperty(mark, String.class); if (StringUtils.isBlank(uuid)) { return null; } for (Resource releaseNode : releasesNode.getChildren()) { if (uuid.equals(releaseNode.getValueMap().get(PROP_UUID, String.class))) { return new ReleaseImpl(root, releaseNode); } } return null; } @Override public Release findReleaseByReleaseResource(Resource releaseResource) { if (releaseResource == null) { return null; } for (Release release : getReleasesImpl(releaseResource)) { if (SlingResourceUtil.isSameOrDescendant(ReleaseImpl.unwrap(release).getReleaseNode().getPath(), releaseResource.getPath())) { return release; } } return null; } @NotNull @Override public ReleasedVersionable restoreVersionable(@NotNull Release rawRelease, @NotNull ReleasedVersionable releasedVersionable) throws RepositoryException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); listWorkspaceContents(release.getReleaseRoot()) .forEach((existingVersionable) -> Validate.isTrue(!StringUtils.equals(existingVersionable.getVersionHistory(), releasedVersionable.getVersionHistory()), "Cannot restore versionable %s from relese %s that exists at %s", releasedVersionable.getVersionHistory(), release, existingVersionable.getRelativePath())); String newPath = release.absolutePath(releasedVersionable.getRelativePath()); Session session = release.getReleaseRoot().getResourceResolver().adaptTo(Session.class); Version version = (Version) session.getNodeByIdentifier(releasedVersionable.getVersionUuid()); session.getWorkspace().getVersionManager().restore(newPath, version, false); return ReleasedVersionable.forBaseVersion(release.getReleaseRoot().getResourceResolver().getResource(newPath)); } /** * Remove all labels starting with {@value StagingConstants#RELEASE_LABEL_PREFIX} from version histories pointing * into our release root that do not name a release that actually exists. * * @return the number of broken labels */ @Override public int cleanupLabels(@NotNull Resource resource) throws RepositoryException { long start = System.currentTimeMillis(); int count = 0; ResourceHandle root = findReleaseRoot(resource); Set<String> expectedLabels = getReleasesImpl(root).stream().map(Release::getReleaseLabel).collect(Collectors.toSet()); Query query = root.getResourceResolver() .adaptTo(QueryBuilder.class) .createQuery(); query.path("/jcr:system/jcr:versionStorage").type("nt:versionHistory").condition( query.conditionBuilder().property("default").like().val(root.getPath() + "/%") ); for (Resource versionHistory : query.execute()) { Resource labelResource = versionHistory.getChild(ResourceUtil.JCR_VERSIONLABELS); ValueMap valueMap = labelResource.getValueMap(); for (String label : valueMap.keySet()) { if (label.startsWith(RELEASE_LABEL_PREFIX) && !expectedLabels.contains(label)) { Property versionProperty = valueMap.get(label, Property.class); Node version = versionProperty.getNode(); VersionHistory versionHistoryNode = (VersionHistory) version.getParent(); versionHistoryNode.removeVersionLabel(label); LOG.debug("Removing obsolete label {} from {}", label, labelResource.getPath()); count++; } } } LOG.info("cleanupLabels removed {} obsolete labels in {}s", 0.001 * (System.currentTimeMillis() - start)); return count; } @Override public void closeRelease(@NotNull Release rawRelease) throws RepositoryException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); if (release.getNumber().equals(CURRENT_RELEASE)) { throw new IllegalArgumentException("Current release cannot be closed."); } LOG.info("Closing release {}", release); ResourceHandle.use(release.getReleaseNode()).setProperty(PROP_CLOSED, true); } @NotNull @Override public String bumpReleaseChangeNumber(@NotNull Release rawRelease) throws RepositoryException { ReleaseImpl release = requireNonNull(ReleaseImpl.unwrap(rawRelease)); String newChangeNumber = "chg" + Math.abs(random.nextLong()); // Since this changes randomly, we don't have to be afraid of concurrent modifications. ModifiableValueMap modifiableValueMap = release.workspaceCopyNode.adaptTo(ModifiableValueMap.class); String oldChangeNumber = modifiableValueMap.get(StagingConstants.PROP_CHANGE_NUMBER, String.class); modifiableValueMap.put(StagingConstants.PROP_CHANGE_NUMBER, newChangeNumber); LOG.info("Updating release change number to {} from originally {}", newChangeNumber, oldChangeNumber); return newChangeNumber; } /** * Ensures the technical resources for a release are there. If the release is created, the root is completely empty. */ protected ReleaseImpl ensureRelease(@NotNull Resource theRoot, @NotNull String releaseLabel) throws RepositoryException, PersistenceException { ResourceHandle root = ResourceHandle.use(theRoot); if (!root.isValid() && !root.isOfType(TYPE_MIX_RELEASE_ROOT)) { throw new IllegalArgumentException("Not a release root: " + theRoot.getPath()); } ResourceHandle releasesNode = getReleasesNode(root); if (!releasesNode.isValid()) { try { releasesNode = ResourceHandle.use( ResourceUtil.getOrCreateResource(root.getResourceResolver(), getReleasesNodePath(root), TYPE_UNSTRUCTURED)); } catch (IllegalArgumentException | RepositoryException e) { LOG.error("Could not create {}", getReleasesNodePath(root)); throw e; } } Resource releaseNode = ResourceUtil.getOrCreateChild(releasesNode, releaseLabel, TYPE_UNSTRUCTURED); SlingResourceUtil.addMixin(releaseNode, TYPE_REFERENCEABLE); String[] history = releasesNode.getProperty(PROP_RELEASE_ROOT_HISTORY, new String[0]); if (!Arrays.asList(history).contains(theRoot.getPath())) { ArrayList<String> newHistory = new ArrayList<>(Arrays.asList(history)); newHistory.add(theRoot.getPath()); releasesNode.setProperty(PROP_RELEASE_ROOT_HISTORY, newHistory); } Resource releaseWorkspaceCopy = ResourceUtil.getOrCreateChild(releaseNode, NODE_RELEASE_ROOT, TYPE_UNSTRUCTURED); // set a frozen primary type to ensure a sane state ResourceHandle.use(releaseWorkspaceCopy).setProperty(ResourceUtil.JCR_FROZENPRIMARYTYPE, ResourceUtil.TYPE_SLING_ORDERED_FOLDER); ResourceHandle metaData = ResourceHandle.use(releaseNode.getChild(NODE_RELEASE_METADATA)); if (!metaData.isValid()) { metaData = ResourceHandle.use(root.getResourceResolver().create(releaseNode, NODE_RELEASE_METADATA, ImmutableMap.of(PROP_PRIMARY_TYPE, TYPE_UNSTRUCTURED, PROP_MIXINTYPES, new String[]{TYPE_CREATED, TYPE_LAST_MODIFIED, TYPE_TITLE}))); } return new ReleaseImpl(root, releaseNode); // incl. validation } /** * Pseudo- {@link ReleaseNumberCreator} that returns a given release name */ @NotNull ReleaseNumberCreator givenReleaseNumber(@NotNull final String name) { return new ReleaseNumberCreator() { @NotNull @Override public String name() { return "self"; } @NotNull @Override public String bumpRelease(@NotNull String oldname) { return name; } }; } public static class ReleaseImpl implements Release { @NotNull final Resource releaseRoot; @NotNull final Resource releaseNode; @NotNull final Resource workspaceCopyNode; private List<String> marks; private transient Optional<ReleaseImpl> prevRelease; ReleaseImpl(@NotNull Resource releaseRoot, @NotNull Resource releaseNode) { this.releaseRoot = requireNonNull(releaseRoot); this.releaseNode = requireNonNull(releaseNode); this.workspaceCopyNode = requireNonNull(getReleaseNode().getChild(NODE_RELEASE_ROOT)); validate(); } /** * A quick sanity check that all needed nodes are there. */ public void validate() { ResourceHandle root = ResourceHandle.use(releaseRoot); if (!root.isValid() && !root.isOfType(TYPE_MIX_RELEASE_ROOT)) { throw new IllegalArgumentException("Not a release root: " + releaseRoot.getPath()); } if (!releaseNode.getPath().startsWith(RELEASE_ROOT_PATH + root.getPath() + "/" + NODE_RELEASES)) { throw new IllegalArgumentException("Suspicious release node " + releaseNode.getPath() + " in " + this); } if (releaseNode.getChild(NODE_RELEASE_METADATA) == null) { throw new IllegalArgumentException("No metadata node in " + this); } } @Override @NotNull public String getUuid() { return ResourceHandle.use(releaseNode).getProperty(PROP_UUID); } @Override @NotNull public String getNumber() { return releaseNode.getName(); } @Override @NotNull public String getPath() { return releaseNode.getPath(); } @Override @NotNull public Resource getReleaseRoot() { return releaseRoot; } @Override @NotNull public Resource getMetaDataNode() { return requireNonNull(releaseNode.getChild(NODE_RELEASE_METADATA), "No metadata node on " + releaseNode.getPath()); } @NotNull @Override public String getChangeNumber() { String changeNumber = getWorkspaceCopyNode() != null ? getWorkspaceCopyNode().getValueMap().get(StagingConstants.PROP_CHANGE_NUMBER, String.class) : null; if (StringUtils.isBlank(changeNumber)) { // for old releases we create a fake number; will be updated on next change. changeNumber = getWorkspaceCopyNode() != null ? getWorkspaceCopyNode().getPath() : "chgunset"; } return changeNumber; } @NotNull @Override public List<String> getMarks() { if (marks == null) { marks = new ArrayList<>(); for (Map.Entry entry : releaseNode.getParent().getValueMap().entrySet()) { if (getUuid().equals(entry.getValue())) { marks.add(String.valueOf(entry.getKey())); } } } return Collections.unmodifiableList(marks); } @Override public boolean isClosed() { return releaseNode.getValueMap().get(PROP_CLOSED, false); } @Nullable @Override public Release getPreviousRelease() throws RepositoryException { if (prevRelease == null) { Resource prevReleaseResource = ResourceUtil.getReferredResource(releaseNode.getChild(PROP_PREVIOUS_RELEASE_UUID)); prevRelease = Optional.ofNullable(prevReleaseResource != null ? new ReleaseImpl(releaseRoot, prevReleaseResource) : null); } return prevRelease.orElse(null); } /** * The resource that contains the data for the release - including the subnode {@value StagingConstants#NODE_RELEASE_ROOT} * with the copy of the data. Don't touch {@value StagingConstants#NODE_RELEASE_ROOT} - always use the * {@link StagingReleaseManager} for that! */ @NotNull public Resource getReleaseNode() { return releaseNode; } /** * The node that contains the root of workspace copy for the release. */ @NotNull public Resource getWorkspaceCopyNode() { return workspaceCopyNode; } @Override public boolean appliesToPath(@Nullable String path) { return SlingResourceUtil.isSameOrDescendant(releaseRoot.getPath(), path); } @NotNull @Override public String absolutePath(@Nullable String path) { if (StringUtils.startsWith(path, "/")) { if (SlingResourceUtil.isSameOrDescendant(workspaceCopyNode.getPath(), path)) { String relativePath = SlingResourceUtil.relativePath(workspaceCopyNode.getPath(), path); return getReleaseRoot().getPath() + '/' + relativePath; } else if (appliesToPath(path)) { return path; } else { throw new IllegalArgumentException("Path does not belong to release:" + path); } } if (StringUtils.isBlank(path)) { return getReleaseRoot().getPath(); } return getReleaseRoot().getPath() + '/' + path; } @Override public String toString() { return "Release('" + getNumber() + "'," + releaseRoot.getPath() + ")"; } /** * This is used to unwrap release to be able to access implementation specific methods, * and performs a sanity check that the release is still there - that's also a weak * measure to ensure this was created in the {@link DefaultStagingReleaseManager}, not outside. */ public static ReleaseImpl unwrap(@Nullable Release release) { if (release != null) { ((ReleaseImpl) release).validate(); } return (ReleaseImpl) release; } protected void updateLastModified() throws RepositoryException { ResourceHandle metaData = ResourceHandle.use(getMetaDataNode()); if (metaData.isOfType(TYPE_LAST_MODIFIED)) { metaData.setProperty(JCR_LASTMODIFIED, Calendar.getInstance()); metaData.setProperty(CoreConstants.JCR_LASTMODIFIED_BY, getReleaseRoot().getResourceResolver().getUserID()); } } /** * Maps paths pointing into the release content to the release content copy. * * @param path an absolute or relative path * @return if path is absolute, return the path in the releases content copy that corresponds to that path - we don't check whether it actually exists. * If it is relative, returns the path in the releases content copy that has that path relative to the release. */ @NotNull public String mapToContentCopy(@NotNull String path) { if (path.startsWith("/")) { if (appliesToPath(path)) { path = ResourceUtil.normalize(path); if (releaseRoot.getPath().equals(path)) { path = getWorkspaceCopyNode().getPath(); } else if (null != path) { assert path.startsWith(releaseRoot.getPath()); path = getWorkspaceCopyNode().getPath() + '/' + path.substring(releaseRoot.getPath().length() + 1); } } } else { // relative path ResourceUtil.normalize(getWorkspaceCopyNode().getPath() + '/' + path); } return path; } /** * Reverse of {@link #mapToContentCopy(String)}: reconstructs original path from a path pointing to the content copy. */ @NotNull public String unmapFromContentCopy(@NotNull String contentCopyPath) { String path = ResourceUtil.normalize(contentCopyPath); if (SlingResourceUtil.isSameOrDescendant(getWorkspaceCopyNode().getPath(), path)) { path = getReleaseRoot().getPath() + path.substring(getWorkspaceCopyNode().getPath().length()); } return path != null ? path : contentCopyPath; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReleaseImpl release = (ReleaseImpl) o; return StringUtils.equals(releaseRoot.getPath(), release.getReleaseRoot().getPath()) && StringUtils.equals(releaseNode.getPath(), release.getReleaseNode().getPath()); } @Nullable @Override public VersionReference versionReference(@Nullable String relativePath) { VersionReference result = null; if (relativePath != null) { Resource versionReference = getWorkspaceCopyNode().getChild(relativePath); if (versionReference != null) { result = new VersionReferenceImpl(this, versionReference); } } return result; } @Override public int hashCode() { return Objects.hash(releaseRoot, releaseNode); } } protected static class VersionReferenceImpl implements VersionReference { @NotNull private final ReleaseImpl release; @NotNull private final ResourceHandle versionReference; /** Lazily calculated resource in the version store this version refers to. */ @Nullable private transient Resource versionResource; protected VersionReferenceImpl(@NotNull ReleaseImpl release, @NotNull Resource versionReference) { this.release = Objects.requireNonNull(release); this.versionReference = ResourceHandle.use(requireNonNull(versionReference)); if (!isVersionReference(versionReference)) { throw new IllegalArgumentException("Not a version reference: " + versionReference.getPath()); } } public static boolean isVersionReference(@NotNull Resource versionReference) { return versionReference.isResourceType(TYPE_VERSIONREFERENCE); } @Override @NotNull public ReleasedVersionable getReleasedVersionable() { return ReleasedVersionable.fromVersionReference(release.getWorkspaceCopyNode(), versionReference); } @Override public boolean isActive() { return !versionReference.getProperty(PROP_DEACTIVATED, false); } @Override @Nullable public Calendar getLastActivated() { Calendar lastActivated = versionReference != null ? versionReference.getProperty(PROP_LAST_ACTIVATED, Calendar.class) : null; return lastActivated; } @Override @Nullable public String getLastActivatedBy() { return versionReference.getProperty(PROP_LAST_ACTIVATED_BY, String.class); } @Override @Nullable public Calendar getLastDeactivated() { return versionReference.getProperty(PROP_LAST_DEACTIVATED, Calendar.class); } @Override @Nullable public String getLastDeactivatedBy() { return versionReference.getProperty(PROP_LAST_DEACTIVATED_BY, String.class); } @Override @Nullable public Resource getVersionResource() { if (versionResource == null) { try { ResourceResolver resourceResolver = release.getReleaseRoot().getResourceResolver(); versionResource = ResourceUtil.getByUuid(resourceResolver, getReleasedVersionable().getVersionUuid()); } catch (RepositoryException | ClassCastException e) { throw new SlingException("Trouble accessing version " + getReleasedVersionable().getVersionUuid(), e); } } return versionResource; } @Nullable @Override public Calendar getVersionCreated() { Resource versionResource = getVersionResource(); return versionResource != null ? versionResource.getValueMap().get(JCR_CREATED, Calendar.class) : null; } @Override @NotNull public Release getRelease() { return release; } @NotNull @Override public String getPath() { return release.absolutePath(getReleasedVersionable().getRelativePath()); } @NotNull @Override public String getType() { String type = versionReference.getProperty(JCR_FROZENPRIMARYTYPE, String.class); if (StringUtils.isBlank(type)) { // fallback for backwards compatibility - the primaryType wasn't always saved. ResourceHandle versionResource = ResourceHandle.use(getVersionResource()); type = versionResource.isValid() ? versionResource.getProperty(JCR_FROZENNODE+"/" + JCR_FROZENPRIMARYTYPE, String.class) : null; } return Objects.requireNonNull(type, "Bug: could not determine primary type of reference " + versionReference.getPath()); // can't happen } @Override public String toString() { return new ToStringBuilder(this) .append("versionReference", SlingResourceUtil.getPath(versionReference)) .toString(); } } @ObjectClassDefinition( name = "Composum Platform Staging Release Manager Configuration" ) public @interface Configuration { @AttributeDefinition( name = "Overlayed Nodes", description = "Some nodes that are overlayed from the top level of the working content into the release" ) String[] overlayed_nodes() default {}; @AttributeDefinition( name = "Removed Paths", description = "Some paths that are removed form the overlayed nodes (relative to the release top level)" ) String[] removed_paths() default {}; } }
package group7.anemone; import java.awt.geom.Point2D; import java.util.ArrayList; import processing.core.PApplet; import processing.core.PFont; // We aren't going to serialise this. @SuppressWarnings("serial") public class Simulation extends PApplet { Environment env = new Environment(this); Agent selectedAgent = null; PFont f = createFont("Arial",12,true); int mouseMode=0; public static void main(String args[]){ // Run the applet when the Java application is run PApplet.main(new String[] { "--present", "group7.anemone.Simulation" }); } public void setup() { frameRate(30); size(screen.width, screen.height); for(int i = 0; i < 10; i++){ int x = (int) Math.floor(Math.random() * width); int y = (int) Math.floor(Math.random() * height); env.addFish(new Point2D.Double(x, y)); } env.getAllAgents().get(0).setThrust(2, 2); for(int i = 0; i < 10; i++){ int x = (int) Math.floor(Math.random() * width); int y = (int) Math.floor(Math.random() * height); env.addFood(new Point2D.Double(x, y)); } } public void mousePressed(){ ArrayList<Agent> agents = env.getAllAgents(); Agent agent_clicked = null; /* * Check if the mouse has clicked on a button */ if ((mouseX>screen.width-70)&(mouseX<screen.width-20)&(mouseY>20)&(mouseY<70)) { mouseMode=1; } /* * Mouse Modes are as follows: * 0 = Click tool - Select agents to see infromation on them in the top left hand corner * 1 = Food tool - Place food where you click */ switch(mouseMode){ case 0: for(int i = 0; i < agents.size(); i++){ //loop through each agent and find one clicked Agent ag = agents.get(i); if(Math.sqrt(Math.pow(mouseX - ag.getX(), 2) + Math.pow(mouseY - ag.getY(), 2)) < 10){ agent_clicked = ag; break; } } if(agent_clicked != null){ //agent was clicked so update selected selectedAgent = agent_clicked; } break; case 1: env.addFood(new Point2D.Double(mouseX, mouseY)); break; } } public void draw(){ background(0); //Draws background, basically refreshes the screen //Draw the 'Buttons to click on for food stroke(84,255,159); fill(84,255,159); rect(screen.width-70,20,50,50); fill(0); textFont(f); text("Food",screen.width-60,50); env.updateAllAgents(); //'Ticks' for the new frame, sensors sense, networks network and collisions are checked. env.updateCollisions(); //update the environment with the new collisions handleCollisions(); checkDeaths(); ArrayList<Agent> agents = env.getAllAgents(); //Returns an arraylist of agents ArrayList<Food> food = env.getAllFood(); //Returns an arraylist of all the food on the map for(int i = 0; i < agents.size(); i++){ //Runs through arraylist of agents, will draw them on the canvas Agent ag = agents.get(i); //draw the field of view for the agent stroke(128); noFill(); double range = ag.getVisionRange() * 2; pushMatrix(); translate(ag.getX(), ag.getY()); rotate((float) toRadians(ag.getViewHeading() - ag.getFOV())); line(0, 0, (int) (range / 2), 0); popMatrix(); pushMatrix(); translate(ag.getX(), ag.getY()); rotate((float) toRadians(ag.getViewHeading() + ag.getFOV())); line(0, 0, (int) (range / 2), 0); popMatrix(); arc((float) ag.getX(), (float) ag.getY(), (float) range, (float) range, (float) toRadians(ag.getViewHeading() - ag.getFOV()) , (float) toRadians(ag.getViewHeading() + ag.getFOV())); //draw our circle representation for the agent noStroke(); fill(255, 127, 0); ellipse(ag.getX(), ag.getY(), 20, 20); } fill(0, 255, 0); stroke(0,255,0); for(int i = 0; i < food.size(); i++){ //Runs through arraylist of food, will draw them on the canvas Food fd = food.get(i); ellipse(fd.getX(), fd.getY(), 5, 5); } fill(255); textFont(f); text("FrameRate: " + frameRate, 10, 10); //Displays framerate in the top left hand corner if(selectedAgent != null){ //If an agent is seleted, display its coordinates in the top left hand corner, under the framerate fill(255); textFont(f); text("Selected agent x = "+selectedAgent.getX(), 10, 25); text("Selected agent y = "+selectedAgent.getY(), 10, 40); text("Selected agent health = "+selectedAgent.getHealth(), 10, 55); } } private double toRadians(double deg){ return deg * Math.PI / 180; } private void checkDeaths(){ //mwahahaha >:) ArrayList<Agent> agents = env.getAllAgents(); for (Agent ag: agents) { if(ag.getHealth() <= 0){ env.removeAgent(ag); selectedAgent = null; } } } private void handleCollisions(){ ArrayList<Collision> collisions = env.getCollisions(); for (Collision cc: collisions) { //check collisions to food int type = cc.getType(); switch(type){ case Collision.TYPE_FOOD: eatFood(cc);break; } } } private void eatFood(Collision cc) { Food fd = (Food) cc.getCollidedObject(); env.removeFood(fd); cc.getAgent().updateHealth(fd.getValue()); } }
package group7.anemone; import java.awt.geom.Point2D; import java.util.ArrayList; import processing.core.PApplet; import processing.core.PFont; // We aren't going to serialise this. //This comment exists because I'm testing out how branching and merging works. @SuppressWarnings("serial") public class Simulation extends PApplet { Environment env = new Environment(this); Agent selectedAgent = null; PFont f = createFont("Arial",12,true); int mouseMode=0; public static void main(String args[]){ // Run the applet when the Java application is run PApplet.main(new String[] { "--present", "group7.anemone.Simulation" }); } public void setup() { frameRate(30); size(screen.width, screen.height); for(int i = 0; i < 1; i++){ int x = (int) Math.floor(Math.random() * width); int y = (int) Math.floor(Math.random() * height); int heading = (int) Math.floor(Math.random() * 360); env.addFish(new Point2D.Double(x, y), heading); } //env.getAllAgents().get(0).setThrust(2, 2); for(int i = 0; i < 0; i++){ int x = (int) Math.floor(Math.random() * width); int y = (int) Math.floor(Math.random() * height); env.addFood(new Point2D.Double(x, y)); } } public void mousePressed(){ ArrayList<Agent> agents = env.getAllAgents(); Agent agent_clicked = null; /* * Check if the mouse has clicked on a button */ if ((mouseX>screen.width-140)&(mouseX<screen.width-90)&(mouseY>20)&(mouseY<70)) { //Check select button button mouseMode=0; } else if ((mouseX>screen.width-70)&(mouseX<screen.width-20)&(mouseY>20)&(mouseY<70)) { //Check food button mouseMode=1; } /* * Mouse Modes are as follows: * 0 = Click tool - Select agents to see infromation on them in the top left hand corner * 1 = Food tool - Place food where you click */ switch(mouseMode){ case 0: for(int i = 0; i < agents.size(); i++){ //loop through each agent and find one clicked Agent ag = agents.get(i); if(Math.sqrt(Math.pow(mouseX - ag.getX(), 2) + Math.pow(mouseY - ag.getY(), 2)) < 10){ agent_clicked = ag; break; } } if(agent_clicked != null){ //agent was clicked so update selected selectedAgent = agent_clicked; } break; case 1: env.addFood(new Point2D.Double(mouseX, mouseY)); break; } } public void draw(){ background(0); //Draws background, basically refreshes the screen //Draw the 'Buttons to click on for food stroke(84,255,159); fill(84,255,159); rect(screen.width-70,20,50,50); //Draw Food Button stroke(72,118,255); fill(72,118,255); rect(screen.width-140,20,50,50); fill(0); textFont(f); text("Food",screen.width-60,50); text("Select",screen.width-130,50); env.updateAllAgents(); //'Ticks' for the new frame, sensors sense, networks network and collisions are checked. env.updateCollisions(); //update the environment with the new collisions env.updateAgentsSight(); //update all the agents to everything they can see in their field of view handleCollisions(); checkDeaths(); ArrayList<Agent> agents = env.getAllAgents(); //Returns an arraylist of agents ArrayList<Food> food = env.getAllFood(); //Returns an arraylist of all the food on the map for(int i = 0; i < agents.size(); i++){ //Runs through arraylist of agents, will draw them on the canvas Agent ag = agents.get(i); //draw the field of view for the agent stroke(128); noFill(); double range = ag.getVisionRange() * 2; pushMatrix(); translate(ag.getX(), ag.getY()); rotate((float) toRadians(ag.getViewHeading() - ag.getFOV())); line(0, 0, (int) (range / 2), 0); popMatrix(); pushMatrix(); translate(ag.getX(), ag.getY()); rotate((float) toRadians(ag.getViewHeading() + ag.getFOV())); line(0, 0, (int) (range / 2), 0); popMatrix(); arc((float) ag.getX(), (float) ag.getY(), (float) range, (float) range, (float) toRadians(ag.getViewHeading() - ag.getFOV()) , (float) toRadians(ag.getViewHeading() + ag.getFOV())); //draw our circle representation for the agent noStroke(); fill(255, 127, 0); ellipse(ag.getX(), ag.getY(), 20, 20); } fill(0, 255, 0); stroke(0,255,0); for(int i = 0; i < food.size(); i++){ //Runs through arraylist of food, will draw them on the canvas Food fd = food.get(i); ellipse(fd.getX(), fd.getY(), 5, 5); } fill(255); textFont(f); text("FrameRate: " + frameRate, 10, 10); //Displays framerate in the top left hand corner if(selectedAgent != null){ //If an agent is seleted, display its coordinates in the top left hand corner, under the framerate fill(255); textFont(f); text("Selected agent x = "+selectedAgent.getX(), 10, 25); text("Selected agent y = "+selectedAgent.getY(), 10, 40); text("Selected agent health = "+selectedAgent.getHealth(), 10, 55); text("Selected agent total see = "+selectedAgent.getCanSee().size(), 10, 70); } } private double toRadians(double deg){ return deg * Math.PI / 180; } private void checkDeaths(){ //mwahahaha >:) ArrayList<Agent> agents = env.getAllAgents(); for (Agent ag: agents) { if(ag.getHealth() <= 0){ env.removeAgent(ag); if(selectedAgent == ag) selectedAgent = null; } } } private void handleCollisions(){ ArrayList<Collision> collisions = env.getCollisions(); for (Collision cc: collisions) { //check collisions to food int type = cc.getType(); switch(type){ case Collision.TYPE_FOOD: eatFood(cc);break; } } } private void eatFood(Collision cc) { Food fd = (Food) cc.getCollidedObject(); env.removeFood(fd); cc.getAgent().updateHealth(fd.getValue()); } }
package com.thindeck.steps; import com.google.common.base.Joiner; import com.jcabi.github.Github; import com.jcabi.github.Repo; import com.jcabi.github.mock.MkGithub; import com.jcabi.matchers.XhtmlMatchers; import com.thindeck.api.Context; import com.thindeck.api.Step; import com.thindeck.api.mock.MkContext; import javax.json.Json; import org.apache.commons.codec.binary.Base64; import org.hamcrest.MatcherAssert; import org.junit.Test; import org.xembly.Directives; /** * Test case for {@link ReadConfig}. * * @author Carlos Miranda (miranda.cma@gmail.com) * @version $Id$ * @since 0.3 */ public final class ReadConfigTest { /** * Fetch repo configuration and update memo accordingly. * @throws Exception If something goes wrong */ @Test public void fetchesRepoConfigAndUpdatesMemo() throws Exception { final Github ghub = new MkGithub("thindeck"); final Repo repo = ghub.repos().create( Json.createObjectBuilder() .add("name", "test") .build() ); final String config = Joiner.on('\n').join( "domains: [\"example.com\", \"test.example.com\"]", "ports: [80, 443]" ); repo.contents().create( Json.createObjectBuilder() .add("path", ".thindeck.yml") .add("message", "Thindeck config") .add( "content", new String( Base64.encodeBase64( config.getBytes() ) ) ).build() ); final Context ctx = new MkContext(); ctx.memo().update( new Directives() .xpath("/memo") .add("uri").set("git://github.com/thindeck/test.git") ); final Step step = new ReadConfig(ghub); step.exec(ctx); MatcherAssert.assertThat( ctx.memo().read(), XhtmlMatchers.hasXPaths( "//memo/domains/domain[.='example.com']", "//memo/domains/domain[.='test.example.com']", "//memo/ports/port[.='80']", "//memo/ports/port[.='443']" ) ); } }
package edu.hm.hafner.analysis; import java.io.IOException; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Predicate; import org.eclipse.collections.impl.block.factory.Predicates; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import edu.hm.hafner.analysis.assertions.SoftAssertions; import edu.hm.hafner.util.SerializableTest; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static edu.hm.hafner.analysis.assertions.Assertions.*; import static java.util.Arrays.*; /** * Unit tests for {@link Report}. * * @author Marcel Binder * @author Ullrich Hafner */ @SuppressWarnings("PMD.GodClass") class ReportTest extends SerializableTest<Report> { private static final String SERIALIZATION_NAME = "report.ser"; private static final Issue HIGH = new IssueBuilder().setMessage("issue-1") .setFileName("file-1") .setSeverity(Severity.WARNING_HIGH) .build(); private static final Issue NORMAL_1 = new IssueBuilder().setMessage("issue-2") .setFileName("file-1") .setSeverity(Severity.WARNING_NORMAL) .build(); private static final Issue NORMAL_2 = new IssueBuilder().setMessage("issue-3") .setFileName("file-1") .setSeverity(Severity.WARNING_NORMAL) .build(); private static final Issue LOW_2_A = new IssueBuilder().setMessage("issue-4") .setFileName("file-2") .setSeverity(Severity.WARNING_LOW) .build(); private static final Issue LOW_2_B = new IssueBuilder().setMessage("issue-5") .setFileName("file-2") .setSeverity(Severity.WARNING_LOW) .build(); private static final Issue LOW_FILE_3 = new IssueBuilder().setMessage("issue-6") .setFileName("file-3") .setSeverity(Severity.WARNING_LOW) .build(); private static final String NO_NAME = ""; @Test void shouldProvideOriginMappings() { Report report = new Report(); assertThat(report.getNameOfOrigin("id")).isEqualTo(NO_NAME); report.setNameOfOrigin("id", "name"); assertThat(report.getNameOfOrigin("id")).isEqualTo("name"); report.setNameOfOrigin("second", "another name"); assertThat(report.getNameOfOrigin("id")).isEqualTo("name"); assertThat(report.getNameOfOrigin("second")).isEqualTo("another name"); report.setNameOfOrigin("id", "changed"); assertThat(report.getNameOfOrigin("id")).isEqualTo("changed"); assertThat(report.getNameOfOrigin("second")).isEqualTo("another name"); } @Test void shouldMergeOriginMappings() { Report first = new Report(); first.setNameOfOrigin("first", "first name"); assertThat(first.getNameOfOrigin("first")).isEqualTo("first name"); Report second = new Report(); second.setNameOfOrigin("second", "second name"); assertThat(second.getNameOfOrigin("second")).isEqualTo("second name"); assertThat(first.getNameOfOrigin("second")).isEqualTo(NO_NAME); assertThat(second.getNameOfOrigin("first")).isEqualTo(NO_NAME); first.addAll(second); assertThat(first.getNameOfOrigin("first")).isEqualTo("first name"); assertThat(first.getNameOfOrigin("second")).isEqualTo("second name"); Report third = first.copyEmptyInstance(); assertThat(third.getNameOfOrigin("first")).isEqualTo("first name"); assertThat(third.getNameOfOrigin("second")).isEqualTo("second name"); } @Test void shouldStoreFileNames() { Report report = new Report(); assertThat(report.getFileNames()).isEmpty(); report.addFileName("one"); report.addFileName("one"); assertThat(report.getFileNames()).containsExactly("one"); report.addFileName("two"); assertThat(report.getFileNames()).containsExactlyInAnyOrder("one", "two"); } @Test void shouldVerifyExistenceOfProperties() { Report report = new Report(); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); IssueBuilder builder = new IssueBuilder(); report.add(builder.build()); // add the first issue assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); verifyOrigin(report); verifyModule(report); verifyPackage(report); verifyFile(report); verifyFolder(report); verifyCategory(report); verifyType(report); verifySeverity(report); } private void verifySeverity(final Report report) { Issue additional = new IssueBuilder().setSeverity(Severity.WARNING_HIGH).build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isTrue(); report.remove(additional.getId()); } private void verifyType(final Report report) { Issue additional = new IssueBuilder().setType("type").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isTrue(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } private void verifyCategory(final Report report) { Issue additional = new IssueBuilder().setCategory("category").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isTrue(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } private void verifyFile(final Report report) { Issue additional = new IssueBuilder().setFileName("file").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isTrue(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } @SuppressFBWarnings("DMI") private void verifyFolder(final Report report) { IssueBuilder builder = new IssueBuilder(); Issue additional = builder.setFileName("/tmp/file.txt").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isTrue(); assertThat(report.hasFolders()).isTrue(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); Issue withPackageName = builder.setPackageName("something").build(); report.add(withPackageName); assertThat(report.hasPackages()).isTrue(); assertThat(report.hasFolders()).isFalse(); report.remove(withPackageName.getId()); report.remove(additional.getId()); } private void verifyPackage(final Report report) { Issue additional = new IssueBuilder().setPackageName("package").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isTrue(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } private void verifyModule(final Report report) { Issue additional = new IssueBuilder().setModuleName("module").build(); report.add(additional); assertThat(report.hasTools()).isFalse(); assertThat(report.hasModules()).isTrue(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } private void verifyOrigin(final Report report) { Issue additional = new IssueBuilder().setOrigin("origin").build(); report.add(additional); assertThat(report.hasTools()).isTrue(); assertThat(report.hasModules()).isFalse(); assertThat(report.hasPackages()).isFalse(); assertThat(report.hasFiles()).isFalse(); assertThat(report.hasFolders()).isFalse(); assertThat(report.hasCategories()).isFalse(); assertThat(report.hasTypes()).isFalse(); assertThat(report.hasSeverities()).isFalse(); report.remove(additional.getId()); } @Test void shouldFilterPriorities() { Report report = new Report(); report.addAll(allIssuesAsList()); assertThat(report.getSeverities()) .containsExactlyInAnyOrder(Severity.WARNING_HIGH, Severity.WARNING_NORMAL, Severity.WARNING_LOW); report.add(new IssueBuilder().setSeverity(Severity.ERROR).build()); assertThat(report.getSeverities()).containsExactlyInAnyOrder( Severity.WARNING_HIGH, Severity.WARNING_NORMAL, Severity.WARNING_LOW, Severity.ERROR); assertThat(report.getSizeOf(Severity.ERROR)).isEqualTo(1); assertThat(report.getSizeOf(Severity.WARNING_HIGH)).isEqualTo(1); assertThat(report.getSizeOf(Severity.WARNING_NORMAL)).isEqualTo(2); assertThat(report.getSizeOf(Severity.WARNING_LOW)).isEqualTo(3); assertThat(report.getSizeOf(Severity.ERROR.getName())).isEqualTo(1); assertThat(report.getSizeOf(Severity.WARNING_HIGH.getName())).isEqualTo(1); assertThat(report.getSizeOf(Severity.WARNING_NORMAL.getName())).isEqualTo(2); assertThat(report.getSizeOf(Severity.WARNING_LOW.getName())).isEqualTo(3); } @Test @SuppressWarnings("NullAway") void shouldGroupIssuesByProperty() { Report report = new Report(); report.addAll(allIssuesAsList()); Map<String, Report> byPriority = report.groupByProperty("severity"); assertThat(byPriority).hasSize(3); assertThat(byPriority.get(Severity.WARNING_HIGH.toString())).hasSize(1); assertThat(byPriority.get(Severity.WARNING_NORMAL.toString())).hasSize(2); assertThat(byPriority.get(Severity.WARNING_LOW.toString())).hasSize(3); Map<String, Report> byFile = report.groupByProperty("fileName"); assertThat(byFile).hasSize(3); assertThat(byFile.get("file-1")).hasSize(3); assertThat(byFile.get("file-2")).hasSize(2); assertThat(byFile.get("file-3")).hasSize(1); } /** * Ensures that each method that creates a copy of another issue instance also copies the corresponding properties. */ @Test void shouldProvideNoWritingIterator() { Report report = new Report(); report.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); Iterator<Issue> iterator = report.iterator(); iterator.next(); assertThatThrownBy(iterator::remove).isInstanceOf(UnsupportedOperationException.class); } /** * Ensures that each method that creates a copy of another issue instance also copies the corresponding properties. */ @Test void shouldCopyProperties() { Report expected = new Report(); expected.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); expected.logInfo("Hello"); expected.logInfo("World!"); expected.logError("Boom!"); Report copy = expected.copy(); assertThat(copy).isEqualTo(expected); assertThatAllIssuesHaveBeenAdded(copy); Report report = new Report(); report.addAll(expected); assertThat(report).isEqualTo(expected); assertThatAllIssuesHaveBeenAdded(report); Report empty = expected.copyEmptyInstance(); assertThat(empty).isEmpty(); assertThat(empty.getErrorMessages()).isEqualTo(expected.getErrorMessages()); assertThat(empty.getInfoMessages()).isEqualTo(expected.getInfoMessages()); assertThat(empty.getDuplicatesSize()).isEqualTo(expected.getDuplicatesSize()); Report filtered = expected.filter(Predicates.alwaysTrue()); assertThat(filtered).isEqualTo(expected); assertThatAllIssuesHaveBeenAdded(filtered); } /** Verifies some additional variants of the {@link Report#addAll(Report[])}. */ @Test void shouldVerifyPathInteriorCoverageOfAddAll() { Report first = new Report().add(HIGH); first.logInfo("1 info"); first.logError("1 error"); Report second = new Report().addAll(NORMAL_1, NORMAL_2); second.logInfo("2 info"); second.logError("2 error"); Report third = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); third.logInfo("3 info"); third.logError("3 error"); Report report = new Report(); report.addAll(first); assertThat((Iterable<Issue>) report).containsExactly(HIGH); assertThat(report.getInfoMessages()).containsExactly("1 info"); assertThat(report.getErrorMessages()).containsExactly("1 error"); report.addAll(second, third); assertThatAllIssuesHaveBeenAdded(report); assertThat(report.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(report.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); Report altogether = new Report(); altogether.addAll(first, second, third); assertThatAllIssuesHaveBeenAdded(report); assertThat(report.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(report.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); Report inConstructor = new Report(first, second, third); assertThatAllIssuesHaveBeenAdded(inConstructor); assertThat(inConstructor.getInfoMessages()).containsExactly("1 info", "2 info", "3 info"); assertThat(inConstructor.getErrorMessages()).containsExactly("1 error", "2 error", "3 error"); } @Test void shouldBeEmptyWhenCreated() { Report report = new Report(); assertThat(report).isEmpty(); assertThat(report.isNotEmpty()).isFalse(); assertThat(report).hasSize(0); assertThat(report.size()).isEqualTo(0); assertThatReportHasSeverities(report, 0, 0, 0, 0); } private void assertThatReportHasSeverities(final Report report, final int expectedSizeError, final int expectedSizeHigh, final int expectedSizeNormal, final int expectedSizeLow) { assertThat(report.getSizeOf(Severity.ERROR)).isEqualTo(expectedSizeError); assertThat(report.getSizeOf(Severity.WARNING_HIGH)).isEqualTo(expectedSizeHigh); assertThat(report.getSizeOf(Severity.WARNING_NORMAL)).isEqualTo(expectedSizeNormal); assertThat(report.getSizeOf(Severity.WARNING_LOW)).isEqualTo(expectedSizeLow); } @Test void shouldAddMultipleIssuesOneByOne() { Report report = new Report(); report.add(HIGH); report.add(NORMAL_1); report.add(NORMAL_2); report.add(LOW_2_A); report.add(LOW_2_B); report.add(LOW_FILE_3); assertThatAllIssuesHaveBeenAdded(report); } @Test void shouldAddMultipleIssuesAsCollection() { Report report = new Report(); List<Issue> issueList = allIssuesAsList(); report.addAll(issueList); assertThatAllIssuesHaveBeenAdded(report); } @Test void shouldIterateOverAllElementsInCorrectOrder() { Report report = new Report(); report.add(HIGH); report.addAll(NORMAL_1, NORMAL_2); report.addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); Iterator<Issue> iterator = report.iterator(); assertThat(iterator.next()).isSameAs(HIGH); assertThat(iterator.next()).isSameAs(NORMAL_1); assertThat(iterator.next()).isSameAs(NORMAL_2); assertThat(iterator.next()).isSameAs(LOW_2_A); assertThat(iterator.next()).isSameAs(LOW_2_B); assertThat(iterator.next()).isSameAs(LOW_FILE_3); } @Test void shouldSkipAddedElements() { Report report = new Report().addAll(allIssuesAsList()); Report fromEmpty = new Report(); fromEmpty.addAll(report); assertThatAllIssuesHaveBeenAdded(fromEmpty); fromEmpty.addAll(report); assertThat(fromEmpty).hasSize(6) .hasDuplicatesSize(6); assertThatReportHasSeverities(report, 0, 1, 2, 3); Report left = new Report().addAll(HIGH, NORMAL_1, NORMAL_2); Report right = new Report().addAll(LOW_2_A, LOW_2_B, LOW_FILE_3); Report everything = new Report(); everything.addAll(left, right); assertThat(everything).hasSize(6); } @Test void shouldAddMultipleIssuesToNonEmpty() { Report report = new Report(); report.add(HIGH); report.addAll(asList(NORMAL_1, NORMAL_2)); report.addAll(asList(LOW_2_A, LOW_2_B, LOW_FILE_3)); assertThatAllIssuesHaveBeenAdded(report); } private void assertThatAllIssuesHaveBeenAdded(final Report report) { try (SoftAssertions softly = new SoftAssertions()) { softly.assertThat(report) .hasSize(6) .hasDuplicatesSize(0); assertThatReportHasSeverities(report, 0, 1, 2, 3); softly.assertThat(report.getFiles()) .containsExactly("file-1", "file-2", "file-3"); softly.assertThat(report.getFiles()) .containsExactly("file-1", "file-2", "file-3"); softly.assertThat((Iterable<Issue>) report) .containsExactly(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); softly.assertThat(report.isNotEmpty()).isTrue(); softly.assertThat(report.size()).isEqualTo(6); softly.assertThat(report.getPropertyCount(Issue::getFileName)).containsEntry("file-1", 3); softly.assertThat(report.getPropertyCount(Issue::getFileName)).containsEntry("file-2", 2); softly.assertThat(report.getPropertyCount(Issue::getFileName)).containsEntry("file-3", 1); } } @Test void shouldSkipDuplicates() { Report report = new Report(); report.add(HIGH); assertThat(report).hasSize(1).hasDuplicatesSize(0); report.add(HIGH); assertThat(report).hasSize(1).hasDuplicatesSize(1); report.addAll(asList(HIGH, LOW_2_A)); assertThat(report).hasSize(2).hasDuplicatesSize(2); report.addAll(asList(NORMAL_1, NORMAL_2)); assertThat(report).hasSize(4).hasDuplicatesSize(2); assertThat(report.iterator()).toIterable().containsExactly(HIGH, LOW_2_A, NORMAL_1, NORMAL_2); assertThatReportHasSeverities(report, 0, 1, 2, 1); assertThat(report.getFiles()).containsExactly("file-1", "file-2"); } @Test void shouldRemoveById() { shouldRemoveOneIssue(HIGH, NORMAL_1, NORMAL_2); shouldRemoveOneIssue(NORMAL_1, HIGH, NORMAL_2); shouldRemoveOneIssue(NORMAL_1, NORMAL_2, HIGH); } private void shouldRemoveOneIssue(final Issue... initialElements) { Report report = new Report(); report.addAll(asList(initialElements)); assertThat(report.remove(HIGH.getId())).isEqualTo(HIGH); assertThat((Iterable<Issue>) report).containsExactly(NORMAL_1, NORMAL_2); } @Test void shouldThrowExceptionWhenRemovingWithWrongKey() { Report report = new Report(); UUID id = HIGH.getId(); assertThatThrownBy(() -> report.remove(id)) .isInstanceOf(NoSuchElementException.class) .hasMessageContaining(id.toString()); } @Test void shouldFindIfOnlyOneIssue() { Report report = new Report(); report.addAll(Collections.singletonList(HIGH)); Issue found = report.findById(HIGH.getId()); assertThat(found).isSameAs(HIGH); } @Test void shouldFindWithinMultipleIssues() { shouldFindIssue(HIGH, NORMAL_1, NORMAL_2); shouldFindIssue(NORMAL_1, HIGH, NORMAL_2); shouldFindIssue(NORMAL_1, NORMAL_2, HIGH); } private void shouldFindIssue(final Issue... elements) { Report report = new Report(); report.addAll(asList(elements)); Issue found = report.findById(HIGH.getId()); assertThat(found).isSameAs(HIGH); } @Test void shouldThrowExceptionWhenSearchingWithWrongKey() { shouldFindNothing(HIGH); shouldFindNothing(HIGH, NORMAL_1); } private void shouldFindNothing(final Issue... elements) { Report report = new Report(); report.addAll(asList(elements)); UUID id = NORMAL_2.getId(); assertThatThrownBy(() -> report.findById(id)) .isInstanceOf(NoSuchElementException.class) .hasMessageContaining(id.toString()); } @Test void shouldReturnEmptyListIfPropertyDoesNotMatch() { Report report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); Set<Issue> found = report.findByProperty(Issue.bySeverity(Severity.WARNING_LOW)); assertThat(found).isEmpty(); } @Test void testFindByProperty() { Report report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); Set<Issue> found = report.findByProperty(Issue.bySeverity(Severity.WARNING_HIGH)); assertThat(found).hasSize(1); assertThat(found).containsExactly(HIGH); } @Test void shouldReturnIndexedValue() { Report report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThat(report.get(0)).isSameAs(HIGH); assertThat(report.get(1)).isSameAs(NORMAL_1); assertThat(report.get(2)).isSameAs(NORMAL_2); } @Test @SuppressFBWarnings("RV") void shouldThrowExceptionOnWrongIndex() { Report report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThatThrownBy(() -> report.get(-1)) .isInstanceOf(IndexOutOfBoundsException.class) .hasMessageContaining("-1"); assertThatThrownBy(() -> report.get(3)) .isInstanceOf(IndexOutOfBoundsException.class) .hasMessageContaining("3"); } @Test void shouldReturnFiles() { Report report = new Report(); report.addAll(allIssuesAsList()); assertThat(report.getFiles()).contains("file-1", "file-1", "file-3"); } private List<Issue> allIssuesAsList() { return asList(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); } @Test void shouldReturnSizeInToString() { Report report = new Report(); report.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); assertThat(report.toString()).contains("3"); } @Test void shouldReturnProperties() { Report report = new Report(); report.addAll(allIssuesAsList()); Set<String> properties = report.getProperties(Issue::getMessage); assertThat(properties) .contains(HIGH.getMessage()) .contains(NORMAL_1.getMessage()) .contains(NORMAL_2.getMessage()); } @Test void testCopy() { Report original = new Report(); original.addAll(asList(HIGH, NORMAL_1, NORMAL_2)); Report copy = original.copy(); assertThat(copy).isNotSameAs(original); assertThat(copy.iterator()).toIterable().containsExactly(HIGH, NORMAL_1, NORMAL_2); copy.add(LOW_2_A); assertThat(original.iterator()).toIterable().containsExactly(HIGH, NORMAL_1, NORMAL_2); assertThat(copy.iterator()).toIterable().containsExactly(HIGH, NORMAL_1, NORMAL_2, LOW_2_A); } @Test void shouldFilterByProperty() { assertFilterFor(IssueBuilder::setPackageName, Report::getPackages, "packageName", Issue::byPackageName); assertFilterFor(IssueBuilder::setModuleName, Report::getModules, "moduleName", Issue::byModuleName); assertFilterFor(IssueBuilder::setOrigin, Report::getTools, "toolName", Issue::byOrigin); assertFilterFor(IssueBuilder::setCategory, Report::getCategories, "category", Issue::byCategory); assertFilterFor(IssueBuilder::setType, Report::getTypes, "type", Issue::byType); assertFilterFor(IssueBuilder::setFileName, Report::getFiles, "fileName", Issue::byFileName); } private void assertFilterFor(final BiFunction<IssueBuilder, String, IssueBuilder> builderSetter, final Function<Report, Set<String>> propertyGetter, final String propertyName, final Function<String, Predicate<Issue>> predicate) { Report report = new Report(); IssueBuilder builder = new IssueBuilder(); for (int i = 1; i < 4; i++) { for (int j = i; j < 4; j++) { Issue build = builderSetter.apply(builder, "name " + i).setMessage(i + " " + j).build(); report.add(build); } } assertThat(report).hasSize(6); Set<String> properties = propertyGetter.apply(report); assertThat(properties).as("Wrong values for property " + propertyName) .containsExactlyInAnyOrder("name 1", "name 2", "name 3"); assertThat(report.filter(predicate.apply("name 1"))).hasSize(3); assertThat(report.filter(predicate.apply("name 2"))).hasSize(2); assertThat(report.filter(predicate.apply("name 3"))).hasSize(1); } @Test void shouldStoreAndRetrieveLogAndErrorMessagesInCorrectOrder() { Report report = new Report(); assertThat(report.getInfoMessages()).hasSize(0); assertThat(report.getErrorMessages()).hasSize(0); report.logInfo("%d: %s %s", 1, "Hello", "World"); report.logInfo("%d: %s %s", 2, "Hello", "World"); assertThat(report.getInfoMessages()).hasSize(2); assertThat(report.getInfoMessages()).containsExactly("1: Hello World", "2: Hello World"); report.logError("%d: %s %s", 1, "Hello", "World"); report.logError("%d: %s %s", 2, "Hello", "World"); assertThat(report.getInfoMessages()).hasSize(2); assertThat(report.getInfoMessages()).containsExactly("1: Hello World", "2: Hello World"); assertThat(report.getErrorMessages()).hasSize(2); assertThat(report.getErrorMessages()).containsExactly("1: Hello World", "2: Hello World"); } @Override protected Report createSerializable() { return new Report().addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); } /** * Verifies that saved serialized format (from a previous release) still can be resolved with the current * implementation of {@link Issue}. */ @Test void shouldReadIssueFromOldSerialization() { byte[] restored = readAllBytes(SERIALIZATION_NAME); assertThatSerializableCanBeRestoredFrom(restored); } /** Verifies that equals checks all properties. */ @Test void shouldBeNotEqualsAPropertyChanges() { Report report = new Report(); report.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); Report other = new Report(); other.addAll(report); other.addAll(HIGH, NORMAL_1, NORMAL_2, LOW_2_A, LOW_2_B, LOW_FILE_3); assertThat(report).isNotEqualTo(other); // there should be duplicates assertThat(report).hasDuplicatesSize(0); assertThat(other).hasDuplicatesSize(6); } /** * Serializes an issues to a file. Use this method in case the issue properties have been changed and the * readResolve method has been adapted accordingly so that the old serialization still can be read. * * @param args * not used * * @throws IOException * if the file could not be written */ public static void main(final String... args) throws IOException { new ReportTest().createSerializationFile(); } @Override protected Class<?> getTestResourceClass() { return ReportTest.class; } }
package uk.ac.ox.zoo.seeg.abraid.mp.modelwrapper.configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.FileConfiguration; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.log4j.Logger; import uk.ac.ox.zoo.seeg.abraid.mp.modelwrapper.util.OSChecker; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; public class ConfigurationServiceImpl implements ConfigurationService { private static final Logger LOGGER = Logger.getLogger(ConfigurationServiceImpl.class); private static final String LOG_LOADING_CONFIGURATION_FILE = "Loading configuration file %s"; private static final String LOG_UPDATING_AUTH_CONFIGURATION = "Updating auth configuration: %s %s"; private static final String LOG_UPDATING_REPOSITORY_URL_CONFIGURATION = "Updating repository url configuration: %s"; private static final String LOG_UPDATING_VERSION_CONFIGURATION = "Updating repository version configuration: %s"; private static final String LOG_UPDATING_R_PATH = "Updating R path configuration: %s"; private static final String LOG_UPDATING_RUN_DURATION = "Updating max run duration configuration: %s"; private static final String LOG_UPDATING_COVARIATE_DIR = "Updating covariate dir configuration: %s"; private static final String DEFAULT_LINUX_CACHE_DIR = "/var/lib/abraid/modelwrapper"; private static final String DEFAULT_WINDOWS_CACHE_DIR = System.getenv("LOCALAPPDATA") + "\\abraid\\modelwrapper"; private static final String DEFAULT_COVARIATE_SUB_DIR = "covariates"; private static final String DEFAULT_LINUX_R_PATH = "/usr/bin/R"; private static final String DEFAULT_WINDOWS_R_PATH = System.getenv("R_HOME") + "\\bin\\R.exe"; private static final String USERNAME_KEY = "auth.username"; private static final String PASSWORD_KEY = "auth.password_hash"; private static final String CACHE_DIR_KEY = "cache.data.dir"; private static final String MODEL_REPOSITORY_KEY = "model.repo.url"; private static final String MODEL_VERSION_KEY = "model.repo.version"; private static final String R_EXECUTABLE_KEY = "r.executable.path"; private static final String R_MAX_DURATION_KEY = "r.max.duration"; private static final String COVARIATE_DIRECTORY_KEY = "covariate.dir"; private final FileConfiguration basicProperties; private final OSChecker osChecker; public ConfigurationServiceImpl(File basicProperties, OSChecker osChecker) throws ConfigurationException { LOGGER.info(String.format(LOG_LOADING_CONFIGURATION_FILE, basicProperties.toString())); this.basicProperties = new PropertiesConfiguration(basicProperties); this.basicProperties.setAutoSave(true); this.osChecker = osChecker; } /** * Updates the current modelwrapper authentication details. * @param username The new username. * @param passwordHash The bcrypt hash of the new password. */ @Override public void setAuthenticationDetails(String username, String passwordHash) { LOGGER.info(String.format(LOG_UPDATING_AUTH_CONFIGURATION, username, passwordHash)); basicProperties.setProperty(USERNAME_KEY, username); basicProperties.setProperty(PASSWORD_KEY, passwordHash); } /** * Gets the current modelwrapper authentication username. * @return The username */ @Override public String getAuthenticationUsername() { return basicProperties.getString(USERNAME_KEY); } /** * Gets the current modelwrapper authentication password hash. * @return The password hash. */ @Override public String getAuthenticationPasswordHash() { return basicProperties.getString(PASSWORD_KEY); } /** * Get the current remote repository url to use as a source for the model. * @return The repository url. */ @Override public String getModelRepositoryUrl() { return basicProperties.getString(MODEL_REPOSITORY_KEY); } /** * Set the current remote repository url to use as a source for the model. * @param repositoryUrl The repository url. */ @Override public void setModelRepositoryUrl(String repositoryUrl) { LOGGER.info(String.format(LOG_UPDATING_REPOSITORY_URL_CONFIGURATION, repositoryUrl)); basicProperties.setProperty(MODEL_REPOSITORY_KEY, repositoryUrl); } /** * Get the current model version to use to run the model. * @return The model version. */ @Override public String getModelRepositoryVersion() { return basicProperties.getString(MODEL_VERSION_KEY); } /** * Set the current model version to use to run the model. * @param version The model version. */ @Override public void setModelRepositoryVersion(String version) { LOGGER.info(String.format(LOG_UPDATING_VERSION_CONFIGURATION, version)); basicProperties.setProperty(MODEL_VERSION_KEY, version); } /** * Gets the current directory to use for data caching. * @return The cache directory. */ @Override public String getCacheDirectory() { String defaultDir = osChecker.isWindows() ? DEFAULT_WINDOWS_CACHE_DIR : DEFAULT_LINUX_CACHE_DIR; return basicProperties.getString(CACHE_DIR_KEY, defaultDir); } /** * Gets the current path to the R executable binary. * @return The R path. * @throws ConfigurationException When a value for the R path is not set and R is not present in default locations. */ @Override public String getRExecutablePath() throws ConfigurationException { if (basicProperties.containsKey(R_EXECUTABLE_KEY)) { return basicProperties.getString(R_EXECUTABLE_KEY); } else { return findDefaultR(); } } /** * Sets the current path to the R executable binary. * @param path The R path. */ @Override public void setRExecutablePath(String path) { LOGGER.info(String.format(LOG_UPDATING_R_PATH, path)); basicProperties.setProperty(R_EXECUTABLE_KEY, path); } /** * Gets the current maximum model run duration. * @return The max duration. */ @Override public int getMaxModelRunDuration() { return basicProperties.getInt(R_MAX_DURATION_KEY, Integer.MAX_VALUE); } /** * Sets the current maximum model run duration. * @param value The max duration. */ @Override public void setMaxModelRunDuration(int value) { LOGGER.info(String.format(LOG_UPDATING_RUN_DURATION, value)); basicProperties.setProperty(R_MAX_DURATION_KEY, value); } /** * Gets the current directory for covariate files. * @return The directory for covariate files. */ @Override public String getCovariateDirectory() { Path defaultDirPath = Paths.get(getCacheDirectory(), DEFAULT_COVARIATE_SUB_DIR); String defaultDir = defaultDirPath.toFile().getAbsolutePath(); return basicProperties.getString(COVARIATE_DIRECTORY_KEY, defaultDir); } /** * Sets the current directory for covariate files. * @param path The directory for covariate files. */ @Override public void setCovariateDirectory(String path) { LOGGER.info(String.format(LOG_UPDATING_COVARIATE_DIR, path)); basicProperties.setProperty(COVARIATE_DIRECTORY_KEY, path); } private String findDefaultR() throws ConfigurationException { String rPath = osChecker.isWindows() ? DEFAULT_WINDOWS_R_PATH : DEFAULT_LINUX_R_PATH; File r = Paths.get(rPath).toFile(); if (r.exists() && r.canExecute()) { return r.getAbsolutePath(); } else { throw new ConfigurationException("Could not find R."); } } }
package seedu.jobs.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.jobs.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.jobs.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.jobs.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.jobs.commons.core.EventsCenter; import seedu.jobs.commons.events.model.AddressBookChangedEvent; import seedu.jobs.commons.events.ui.JumpToListRequestEvent; import seedu.jobs.commons.events.ui.ShowHelpRequestEvent; import seedu.jobs.logic.commands.AddCommand; import seedu.jobs.logic.commands.ClearCommand; import seedu.jobs.logic.commands.Command; import seedu.jobs.logic.commands.CommandResult; import seedu.jobs.logic.commands.DeleteCommand; import seedu.jobs.logic.commands.ExitCommand; import seedu.jobs.logic.commands.FindCommand; import seedu.jobs.logic.commands.HelpCommand; import seedu.jobs.logic.commands.ListCommand; import seedu.jobs.logic.commands.SelectCommand; import seedu.jobs.logic.commands.exceptions.CommandException; import seedu.jobs.model.Model; import seedu.jobs.model.ModelManager; import seedu.jobs.model.ReadOnlyTaskBook; import seedu.jobs.model.TaskBook; import seedu.jobs.model.tag.Tag; import seedu.jobs.model.tag.UniqueTagList; import seedu.jobs.model.task.Description; import seedu.jobs.model.task.Email; import seedu.jobs.model.task.Name; import seedu.jobs.model.task.ReadOnlyTask; import seedu.jobs.model.task.Task; import seedu.jobs.model.task.Time; import seedu.jobs.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; //These are for checking the correctness of the events raised private ReadOnlyTaskBook latestSavedAddressBook; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(AddressBookChangedEvent abce) { latestSavedAddressBook = new TaskBook(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempAddressBookFile = saveFolder.getRoot().getPath() + "TempAddressBook.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempAddressBookFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedAddressBook = new TaskBook(model.getAddressBook()); // last saved assumed to be up to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and that the result message is correct. * Also confirms that both the 'address book' and the 'last shown list' are as specified. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskBook, List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskBook expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that the result message is correct. * Both the 'address book' and the 'last shown list' are verified to be unchanged. * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskBook, List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { TaskBook expectedAddressBook = new TaskBook(model.getAddressBook()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedAddressBook, expectedShownList); } /** * Executes the command, confirms that the result message is correct * and that a CommandException is thrown if expected * and also confirms that the following three parts of the LogicManager object's state are as expected:<br> * - the internal address book data are same as those in the {@code expectedAddressBook} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedAddressBook} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskBook expectedAddressBook, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } //Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); //Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedAddressBook, model.getAddressBook()); assertEquals(expectedAddressBook, latestSavedAddressBook); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBook(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBook(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBook(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); //TODO // assertCommandFailure("add wrong start/args wrong args", expectedMessage); // assertCommandFailure("add task start/01/01/01 00:00 01/01/01 00:00", expectedMessage); // assertCommandFailure("add task start/01/01/01 00:00 end/01/01/01 00:00 desciption/invalid prefix", expectedMessage); } @Test public void execute_add_invalidTaskData() { //151 characters assertCommandFailure("add A123456789A123456789A123456789A123456789A123456789A123456789A123456789" + "A123456789A123456789A123456789A123456789A123456789A123456789A123456789A1234567891", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add Valid start/01-02-17 18:49", Time.MESSAGE_TIME_CONSTRAINT); assertCommandFailure("add Valid start/02:01:05 18:49", Time.MESSAGE_TIME_CONSTRAINT); //TODO //recur constraint assertCommandFailure("add valid desc/A123456789A123456789A123456789A123456789A123456789A123456789A123456789" + "A123456789A123456789A123456789A123456789A123456789A123456789A123456789A1234567891", Description.MESSAGE_DESCRIPTION_CONSTRAINT); assertCommandFailure("add Valid tag/invalid_-[.tag", Tag.MESSAGE_TAG_CONSTRAINTS); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskBook expectedAB = new TaskBook(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal address book // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBook expectedAB = helper.generateAddressBook(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare address book state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord , expectedMessage); //index missing assertCommandFailure(commandWord + " +1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); //index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); //index cannot be 0 assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given command * targeting a single task in the shown list, using visible index. * @param commandWord to test assuming it targets a single task in the last shown list * based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new TaskBook()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBook expectedAB = helper.generateAddressBook(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_PERSON_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBook expectedAB = helper.generateAddressBook(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBook expectedAB = helper.generateAddressBook(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name(Optional.of("Test Task")); Time start = new Time(Optional.of("03/18/17 15:00")); Time end = new Time(Optional.of("03/18/17 16:00")); Description desc = new Description(Optional.of("Valid task")); Tag tag1 = new Tag("tag1"); Tag tag2 = new Tag("longertag2"); UniqueTagList tags = new UniqueTagList(tag1, tag2); return new Task(name, start, end, desc, tags); } /** * Generates a valid task using the given seed. * Running this function with the same parameter values guarantees the returned task will have the same state. * Each unique seed will generate a unique Task object. * * @param seed used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name(Optional.of("Task " + seed)), new Time(Optional.of("03/18/17 15:00")), new Time(Optional.of("03/18/17 16:00")), new Description(Optional.of("House of " + seed)), new UniqueTagList(new Tag("tag" + Math.abs(seed)), new Tag("tag" + Math.abs(seed + 1))) ); } /** Generates the correct add command based on the task given */ String generateAddCommand(Task t) { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(t.getName().toString()); cmd.append(" start/").append(t.getStartTime()); cmd.append(" end/").append(t.getEndTime()); cmd.append(" desc/").append(t.getDescription()); UniqueTagList tags = t.getTags(); for (Tag tag: tags) { cmd.append(" tag/").append(tag.tagName); } return cmd.toString(); } /** * Generates an AddressBook with auto-generated tasks. */ TaskBook generateAddressBook(int numGenerated) throws Exception { TaskBook addressBook = new TaskBook(); addToAddressBook(addressBook, numGenerated); return addressBook; } /** * Generates an AddressBook based on the list of Tasks given. */ TaskBook generateAddressBook(List<Task> tasks) throws Exception { TaskBook addressBook = new TaskBook(); addToAddressBook(addressBook, tasks); return addressBook; } /** * Adds auto-generated Task objects to the given AddressBook * @param addressBook The AddressBook to which the Tasks will be added */ void addToAddressBook(TaskBook addressBook, int numGenerated) throws Exception { addToAddressBook(addressBook, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given AddressBook */ void addToAddressBook(TaskBook addressBook, List<Task> tasksToAdd) throws Exception { for (Task t: tasksToAdd) { addressBook.addTask(t); } } /** * Adds auto-generated Task objects to the given model * @param model The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task t: tasksToAdd) { model.addTask(t); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(Optional.of(name)), new Time(Optional.of("03/18/17 15:00")), new Time(Optional.of("03/18/17 16:00")), new Description(Optional.of("Valid task")), new UniqueTagList(new Tag("tag")) ); } } }
package mho.qbar.objects; import mho.wheels.numbers.Numbers; import mho.wheels.structures.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import static mho.wheels.ordering.Ordering.*; public final class Interval implements Comparable<Interval> { /** * [0, 0] */ public static final @NotNull Interval ZERO = new Interval(Rational.ZERO, Rational.ZERO); /** * [1, 1] */ public static final @NotNull Interval ONE = new Interval(Rational.ONE, Rational.ONE); public static final @NotNull Interval ALL = new Interval(null, null); public final @Nullable Rational lower; public final @Nullable Rational upper; private Interval(@Nullable Rational lower, @Nullable Rational upper) { this.lower = lower; this.upper = upper; } /** * Creates a finitely-bounded {@code Interval} from {@code Rationals}. * * <ul> * <li>{@code lower} cannot be null.</li> * <li>{@code upper} cannot be null.</li> * <li>{@code lower} must be less than or equal to {@code upper}.</li> * </ul> * * @param lower the lower bound * @param upper the upper bound * @return [{@code lower}, {@code upper}] */ public static @NotNull Interval of(@NotNull Rational lower, @NotNull Rational upper) { if (gt(lower, upper)) throw new IllegalArgumentException("lower bound cannot be greater than upper bound"); return new Interval(lower, upper); } public static @NotNull Interval lessThanOrEqualTo(@NotNull Rational upper) { return new Interval(null, upper); } public static @NotNull Interval greaterThanOrEqualTo(@NotNull Rational lower) { return new Interval(lower, null); } /** * Creates an interval containing exactly one {@code Rational}. * * <ul> * <li>{@code x} cannot be null.</li> * </ul> * * @param x the value contained in this {@code Interval} * @return [{@code x}, {@code x}] */ public static @NotNull Interval of(@NotNull Rational x) { return new Interval(x, x); } /** * Determines whether {@code this} has finite bounds. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether {@code this} is finitely-bounded */ public boolean isFinitelyBounded() { return lower != null && upper != null; } /** * Determines whether {@code this} contains {@code x}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param x the test {@code Rational} * @return {@code x}&#x2208;{@code this} */ public boolean contains(@NotNull Rational x) { if (lower == null && upper == null) return true; if (lower == null) return le(x, upper); if (upper == null) return ge(x, lower); return ge(x, lower) && le(x, upper); } /** * Determines the diameter (length) of {@code this}, or null if {@code this} has infinite diameter. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result may be any non-negative {@code Rational}, or null.</li> * </ul> * * @return &#x03bc;({@code this}) */ public @Nullable Rational diameter() { if (lower == null || upper == null) return null; return Rational.subtract(upper, lower); } /** * Determines the convex hull of two {@code Interval}s, or the {@code Interval} with minimal diameter that is a * superset of the two {@code Interval}s. * * <ul> * <li>{@code a} cannot be null.</li> * <li>{@code b} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param a the first {@code Interval} * @param b the second {@code Interval} * @return Conv({@code a}, {@code b}) */ public static @NotNull Interval convexHull(@NotNull Interval a, @NotNull Interval b) { return new Interval( a.lower == null || b.lower == null ? null : min(a.lower, b.lower), a.upper == null || b.upper == null ? null : max(a.upper, b.upper) ); } /** * Determines the convex hull of a set of {@code Interval}s, or the {@code Interval} with minimal diameter that is * a superset of all of the {@code Interval}s. * * <ul> * <li>{@code as} cannot be null or empty and may not contain any null elements.</li> * <li>The result is not null.</li> * </ul> * * @param as the {@code Interval}s. * @return Conv({@code as}) */ public static @NotNull Interval convexHull(@NotNull SortedSet<Interval> as) { if (as.isEmpty()) throw new IllegalArgumentException("cannot take convex hull of empty set"); Rational lower = as.first().lower; Rational upper = null; for (Interval a : as) { if (a.upper == null) return new Interval(lower, null); if (upper == null || gt(a.upper, upper)) { upper = a.upper; } } return new Interval(lower, upper); } public static @Nullable Interval intersection(@NotNull Interval a, @NotNull Interval b) { Rational lower; if (a.lower == null && b.lower == null) { lower = null; } else if (a.lower == null) { lower = b.lower; } else if (b.lower == null) { lower = a.lower; } else { lower = max(a.lower, b.lower); } Rational upper; if (a.upper == null && b.upper == null) { upper = null; } else if (a.upper == null) { upper = b.upper; } else if (b.upper == null) { upper = a.upper; } else { upper = min(a.upper, b.upper); } if (lower != null && upper != null && gt(lower, upper)) return null; return new Interval(lower, upper); } public static boolean disjoint(@NotNull Interval a, @NotNull Interval b) { return intersection(a, b) == null; } /** * Transforms a set of {@code Interval}s into a set of disjoint {@code Interval}s with the same union as the * original set. * * <ul> * <li>{@code as} cannot be null and may not contain any null elements.</li> * <li>The result is a sorted set of pairwise disjoint {@code Interval}s.</li> * </ul> * * @param as a set of {@code Interval}s * @return a set of disjoint {@code Interval}s whose union is the same as the union of {@code as} */ public static SortedSet<Interval> makeDisjoint(SortedSet<Interval> as) { SortedSet<Interval> simplified = new TreeSet<>(); Interval acc = null; for (Interval a : as) { if (acc == null) { acc = a; } else if (disjoint(acc, a)) { simplified.add(acc); acc = a; } else { acc = convexHull(acc, a); } } if (acc != null) simplified.add(acc); return simplified; } /** * Returns the midpoint of {@code this}. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is not null.</li> * </ul> * * @return the average of {@code lower} and {@code upper}. */ public @NotNull Rational midpoint() { if (lower == null || upper == null) throw new ArithmeticException("an unbounded interval has no midpoint"); return Rational.add(lower, upper).shiftRight(1); } /** * Splits {@code this} into two intervals at {@code x}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code x} cannot be null.</li> * <li>{@code this} must contain {@code x}.</li> * <li>The result is a pair of {@code Interval}s, neither null, such that the upper bound of the first is equal * to the lower bound of the second.</li> * </ul> * * @param x the point at which {@code this} is split. * @return the two pieces of {@code this}. */ public @NotNull Pair<Interval, Interval> split(@NotNull Rational x) { if (!contains(x)) throw new ArithmeticException("interval does not contain specified split point"); return new Pair<>(new Interval(lower, x), new Interval(x, upper)); } /** * Splits {@code this} into two equal {@code Interval}s. * * <ul> * <li>{@code this} must be finitely bounded.</li> * <li>The result is a pair of equal-diameter, finitely-bounded {@code Interval}s such the the upper bound of the * first is equal to the lower bound of the second.</li> * </ul> * * @return the two halves of {@code this}. */ public @NotNull Pair<Interval, Interval> bisect() { return split(midpoint()); } public static @NotNull Interval roundingPreimage(float f) { if (Float.isNaN(f)) throw new ArithmeticException("cannot find preimage of NaN"); if (Float.isInfinite(f)) { if (f > 0) { return new Interval(Rational.LARGEST_FLOAT, null); } else { return new Interval(null, Rational.LARGEST_FLOAT.negate()); } } Rational r = Rational.of(f); float predecessor = Numbers.predecessor(f); Rational lower = predecessor == Float.NEGATIVE_INFINITY ? null : Rational.add(r, Rational.of(predecessor)).shiftRight(1); float successor = Numbers.successor(f); Rational upper = successor == Float.POSITIVE_INFINITY ? null : Rational.add(r, Rational.of(successor)).shiftRight(1); return new Interval(lower, upper); } public static @NotNull Interval roundingPreimage(double d) { if (Double.isNaN(d)) throw new ArithmeticException("cannot find preimage of NaN"); if (Double.isInfinite(d)) { if (d > 0) { return new Interval(Rational.LARGEST_DOUBLE, null); } else { return new Interval(null, Rational.LARGEST_DOUBLE.negate()); } } Rational r = Rational.of(d); double predecessor = Numbers.predecessor(d); Rational lower = predecessor == Double.NEGATIVE_INFINITY ? null : Rational.add(r, Rational.of(predecessor)).shiftRight(1); double successor = Numbers.successor(d); Rational upper = predecessor == Double.POSITIVE_INFINITY ? null : Rational.add(r, Rational.of(successor)).shiftRight(1); return new Interval(lower, upper); } //todo finish fixing JavaDoc public static @NotNull Interval roundingPreimage(@NotNull BigDecimal bd) { Rational center = Rational.of(bd); Rational maxAbsoluteError = Rational.of(10).pow(-bd.scale()).shiftRight(1); return new Interval(Rational.subtract(center, maxAbsoluteError), Rational.add(center, maxAbsoluteError)); } /** * Returns a pair of {@code float}s x, y such that [x, y] is the smallest interval with {@code float} bounds * which contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in * magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result cannot be null, and neither can either of its elements be null.</li> * </ul> * * @return the smallest {@code float} interval containing {@code this}. */ public @NotNull Pair<Float, Float> floatRange() { float fLower = lower == null ? Float.NEGATIVE_INFINITY : lower.toFloat(RoundingMode.FLOOR); float fUpper = upper == null ? Float.POSITIVE_INFINITY : upper.toFloat(RoundingMode.CEILING); return new Pair<>(fLower, fUpper); } /** * Returns a pair of {@code double}s x, y such that [x, y] is the smallest interval with {@code double} bounds * which contains {@code this}. x or y may be infinite if {@code this}'s bounds are infinite or very large in * magnitude. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result cannot be null, and neither can either of its elements be null.</li> * </ul> * * @return the smallest {@code double} interval containing {@code this}. */ public @NotNull Pair<Double, Double> doubleRange() { double dLower = lower == null ? Double.NEGATIVE_INFINITY : lower.toDouble(RoundingMode.FLOOR); double dUpper = upper == null ? Double.POSITIVE_INFINITY : upper.toDouble(RoundingMode.CEILING); return new Pair<>(dLower, dUpper); } /** * Returns a pair of {@code BigDecimal}s x, y such that [x, y] is the smallest interval with {@code BigDecimal} * bounds (where the {@code BigDecimal}s have a number of significant figures at least as large as * {@code precision}) which contains {@code this}. * * <ul> * <li>{@code this} must be a finitely-bounded {@code Interval}.</li> * <li>{@code precision} must be non-negative.</li> * <li>If {@code precision} is 0, both bounds of {@code this} must have a terminating decimal expansion.</li> * <li>The result is either a pair in which at least one {@code BigDecimal} x has minimal scale (that is, the * scale is the smallest non-negative n such that x&#x00D7;10<sup>n</sup> is an integer), or a pair in which each * {@code BigDecimal} has the same number of significant figures.</li> * </ul> * * @param precision the maximum number of significant digits in the elements of the result; or 0, if both elements * must have full precision * @return the smallest {@code BigDecimal} interval containing {@code this}, such that the precision of the * {@code BigDecimal}s is at least {@code precision}. */ public @NotNull Pair<BigDecimal, BigDecimal> bigDecimalRange(int precision) { if (lower == null || upper == null) throw new ArithmeticException("cannot represent infinities with BigDecimal"); BigDecimal bdLower = lower.toBigDecimal(precision, RoundingMode.FLOOR); BigDecimal bdUpper = upper.toBigDecimal(precision, RoundingMode.CEILING); return new Pair<>(bdLower, bdUpper); } public @NotNull Interval negate() { if (lower == null && upper == null) return this; if (lower == null) return new Interval(upper.negate(), null); if (upper == null) return new Interval(null, lower.negate()); return new Interval(upper.negate(), lower.negate()); } /** * Returns the smallest interval z such that if a&#x2208;{@code x} and b&#x2208;{@code y}, a+b&#x2208;z. * * <ul> * <li>{@code x} cannot be null.</li> * <li>{@code y} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param x the first {@code Interval} * @param y the second {@code Interval} * @return {@code x}+{@code y} */ public static @NotNull Interval add(@NotNull Interval x, @NotNull Interval y) { Rational sLower = x.lower == null || y.lower == null ? null : Rational.add(x.lower, y.lower); Rational sUpper = x.upper == null || y.upper == null ? null : Rational.add(x.upper, y.upper); return new Interval(sLower, sUpper); } public static @NotNull Interval subtract(@NotNull Interval x, @NotNull Interval y) { return add(x, y.negate()); } /** * Returns the smallest interval z such that if a&#x2208;{@code x} and b&#x2208;{@code y}, a&#x00D7;b&#x2208;z. * * <ul> * <li>{@code x} cannot be null.</li> * <li>{@code y} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param x the first {@code Interval} * @param y the second {@code Interval} * @return {@code x}&#x00D7;{@code y} */ public static @NotNull Interval multiply(@NotNull Interval x, @NotNull Interval y) { if ((x.lower == Rational.ZERO && x.upper == Rational.ZERO) || ((y.lower == Rational.ZERO) && y.upper == Rational.ZERO)) { return ZERO; } int xls = x.lower == null ? 2 : x.lower.signum(); int xus = x.upper == null ? 2 : x.upper.signum(); int yls = y.lower == null ? 2 : y.lower.signum(); int yus = y.upper == null ? 2 : y.upper.signum(); boolean containsNegInf = (xls == 2 && yls == 2) || (xls == 2 && yus == 1) || (yls == 2 && xus == 1) || (xus == 2 && yls == -1) || (yus == 2 && xls == -1); boolean containsInf = (xus == 2 && yus == 2) || (xls == 2 && yls == -1) || (yls == 2 && xls == -1) || (xus == 2 && yus == 1) || (yus == 2 && xus == 1); if (containsNegInf && containsInf) return ALL; Rational xlyl = xls == 2 || yls == 2 ? null : Rational.multiply(x.lower, y.lower); Rational xlyu = xls == 2 || yus == 2 ? null : Rational.multiply(x.lower, y.upper); Rational xuyl = xus == 2 || yls == 2 ? null : Rational.multiply(x.upper, y.lower); Rational xuyu = xus == 2 || yus == 2 ? null : Rational.multiply(x.upper, y.upper); Rational min = xlyl; Rational max = xlyl; if (xlyu != null) { if (min == null || lt(xlyu, min)) min = xlyu; if (max == null || gt(xlyu, max)) max = xlyu; } if (xuyl != null) { if (min == null || lt(xuyl, min)) min = xuyl; if (max == null || gt(xuyl, max)) max = xuyl; } if (xuyu != null) { if (min == null || lt(xuyu, min)) min = xuyu; if (max == null || gt(xuyu, max)) max = xuyu; } if (containsNegInf) return new Interval(null, max); if (containsInf) return new Interval(min, null); return new Interval(min, max); } public @NotNull Interval shiftLeft(int bits) { return new Interval( lower == null ? null : lower.shiftLeft(bits), upper == null ? null : upper.shiftLeft(bits) ); } public @NotNull Interval shiftRight(int bits) { return new Interval( lower == null ? null : lower.shiftRight(bits), upper == null ? null : upper.shiftRight(bits) ); } public Interval invert() { if ((lower == null && upper == null) || (lower == null && upper.signum() == 1) || (upper == null && lower.signum() == -1)) return ALL; if (lower == null) return new Interval(upper.invert(), Rational.ZERO); if (upper == null) return new Interval(Rational.ZERO, lower.invert()); if (lower.equals(Rational.ZERO) && upper.equals(Rational.ZERO)) throw new ArithmeticException("division by zero"); if (lower.equals(Rational.ZERO)) return new Interval(upper.invert(), null); if (upper.equals(Rational.ZERO)) return new Interval(null, lower.invert()); if (lower.signum() != upper.signum()) return ALL; return new Interval(upper.invert(), lower.invert()); } public static Interval divide(Interval x, Interval y) { return multiply(x, y.invert()); } public Interval pow(int p) { if (p == 0) return new Interval(Rational.ONE, Rational.ONE); if (p == 1) return this; if (p < 0) return pow(-p).invert(); if (p % 2 == 0) { int ls = lower == null ? -1 : lower.signum(); int us = upper == null ? 1 : upper.signum(); if (ls != -1 && us != -1) { return new Interval(lower.pow(p), upper == null ? null : upper.pow(p)); } if (ls != 1 && us != 1) { return new Interval(upper.pow(p), lower == null ? null : lower.pow(p)); } Rational a = lower == null ? null : lower.pow(p); Rational b = upper == null ? null : upper.pow(p); Rational max = a == null || b == null ? null : max(a, b); return new Interval(Rational.ZERO, max); } else { return new Interval(lower == null ? null : lower.pow(p), upper == null ? null : upper.pow(p)); } } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either boolean.</li> * </ul> * * @param that The {@code Interval} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; Interval interval = (Interval) that; return (lower == null ? interval.lower == null : lower.equals(interval.lower)) && (upper == null ? interval.upper == null : upper.equals(interval.upper)); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { int result = lower != null ? lower.hashCode() : 0; result = 31 * result + (upper != null ? upper.hashCode() : 0); return result; } @Override public int compareTo(@NotNull Interval that) { if (lower == null && that.lower != null) return -1; if (lower != null && that.lower == null) return 1; int lowerCompare = lower == null ? 0 : lower.compareTo(that.lower); if (lowerCompare != 0) return lowerCompare; if (upper == null && that.upper != null) return 1; if (upper != null && that.upper == null) return -1; return upper == null ? 0 : upper.compareTo(that.upper); } /** * Creates an {@code Interval} from a {@code String}. Valid strings are in one of these four forms: * {@code "(-Infinity, Infinity)"}, {@code "(-Infinity, " + q.toString() + "]"}, * {@code "[" + p.toString() + ", Infinity)"}, or {@code "[" + p.toString() + ", " + q.toString() + "]"}, where * {@code p} and {@code q} are {@code Rational}s. * * <ul> * <li>{@code s} cannot be null and cannot be of the form * {@code "[" + p.toString() + ", " + q.toString() + "]"}, where {@code p} and {@code q} are {@code Rational}s * such that {@code a} is greater than {@code b}.</li> <li>The result may be any {@code Interval}, or * null.</li> * </ul> * * @param s a string representation of a {@code Rational}. * @return the {@code Rational} represented by {@code s}, or null if {@code s} is invalid. */ public static @NotNull Optional<Interval> read(@NotNull String s) { if (s.isEmpty()) return Optional.empty(); char left = s.charAt(0); if (left != '[' && left != '(') return Optional.empty(); char right = s.charAt(s.length() - 1); if (right != ']' && right != ')') return Optional.empty(); int commaIndex = s.indexOf(", "); if (commaIndex == -1) return Optional.empty(); String leftString = s.substring(1, commaIndex); String rightString = s.substring(commaIndex + 2, s.length() - 1); Rational lower = null; if (left == '(') { if (!leftString.equals("-Infinity")) return Optional.empty(); } else { Optional<Rational> optLower = Rational.read(leftString); if (!optLower.isPresent()) return Optional.empty(); lower = optLower.get(); } Rational upper = null; if (right == ')') { if (!rightString.equals("Infinity")) return Optional.empty(); } else { Optional<Rational> optUpper = Rational.read(rightString); if (!optUpper.isPresent()) return Optional.empty(); upper = optUpper.get(); } if (lower == null && upper == null) return Optional.of(ALL); if (lower == null) return Optional.of(lessThanOrEqualTo(upper)); if (upper == null) return Optional.of(greaterThanOrEqualTo(lower)); return Optional.of(of(lower, upper)); } /** * Creates a string representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code Interval}.</li> * <li>The result is a string in on of four forms: {@code "(-Infinity, Infinity)"}, * {@code "(-Infinity, " + q.toString() + "]"}, {@code "[" + p.toString() + ", Infinity)"}, or * {@code "[" + p.toString() + ", " + q.toString() + "]"}, where {@code p} and {@code q} are {@code Rational}s * such that {@code p} is less than or equal to {@code q}.</li> * </ul> * * @return a string representation of {@code this}. */ public @NotNull String toString() { return (lower == null ? "(-Infinity" : "[" + lower) + ", " + (upper == null ? "Infinity)" : upper + "]"); } // public Generator<Rational> rationals() { // if (lower == null && upper == null) { // return Rational.rationals(); // if (lower == null) { // return Rational.nonnegativeRationals().map( // r -> Rational.subtract(upper, r), // r -> Rational.subtract(upper, r), // this::contains // if (upper == null) { // return Rational.nonnegativeRationals().map( // r -> Rational.add(r, upper), // r -> Rational.subtract(r, upper), // this::contains // if (lower.equals(upper)) { // return Generator.single(lower); // return Generator.cat(Generator.single(upper), Rational.nonnegativeRationalsLessThanOne().map( // r -> Rational.add(Rational.multiply(r, diameter()), lower), // r -> Rational.divide(Rational.subtract(r, lower), diameter()), // this::contains }
package org.slf4j; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import org.slf4j.helpers.SubstituteLoggerFactory; import org.slf4j.helpers.Util; import org.slf4j.impl.StaticLoggerBinder; /** * The <code>LoggerFactory</code> is a utility class producing Loggers for * various logging APIs, most notably for log4j, logback and JDK 1.4 logging. * Other implementations such as {@link org.slf4j.impl.NOPLogger NOPLogger} and * {@link org.slf4j.impl.SimpleLogger SimpleLogger} are also supported. * * <p> * <code>LoggerFactory</code> is essentially a wrapper around an * {@link ILoggerFactory} instance bound with <code>LoggerFactory</code> at * compile time. * * <p> * Please note that all methods in <code>LoggerFactory</code> are static. * * @author Ceki G&uuml;lc&uuml; * @author Robert Elliot */ public final class LoggerFactory { static final String NO_STATICLOGGERBINDER_URL = "http://www.slf4j.org/codes.html#StaticLoggerBinder"; static final String MULTIPLE_BINDINGS_URL = "http://www.slf4j.org/codes.html#multiple_bindings"; static final String NULL_LF_URL = "http://www.slf4j.org/codes.html#null_LF"; static final String VERSION_MISMATCH = "http://www.slf4j.org/codes.html#version_mismatch"; static final String SUBSTITUTE_LOGGER_URL = "http://www.slf4j.org/codes.html#substituteLogger"; static final String UNSUCCESSFUL_INIT_URL = "http://www.slf4j.org/codes.html#unsuccessfulInit"; static final String UNSUCCESSFUL_INIT_MSG = "org.slf4j.LoggerFactory could not be successfully initialized. See also " + UNSUCCESSFUL_INIT_URL; static final int UNINITIALIZED = 0; static final int ONGOING_INITILIZATION = 1; static final int FAILED_INITILIZATION = 2; static final int SUCCESSFUL_INITILIZATION = 3; static final int GET_SINGLETON_INEXISTENT = 1; static final int GET_SINGLETON_EXISTS = 2; static int INITIALIZATION_STATE = UNINITIALIZED; static int GET_SINGLETON_METHOD = UNINITIALIZED; static SubstituteLoggerFactory TEMP_FACTORY = new SubstituteLoggerFactory(); /** * It is LoggerFactory's responsibility to track version changes and manage * the compatibility list. * * <p> * It is assumed that qualifiers after the 3rd digit have no impact on * compatibility. Thus, 1.5.7-SNAPSHOT, 1.5.7.RC0 are compatible with 1.5.7. */ static private final String[] API_COMPATIBILITY_LIST = new String[] { "1.5.5", "1.5.6", "1.5.7", "1.5.8", "1.5.9", "1.5.10" }; // private constructor prevents instantiation private LoggerFactory() { } /** * Force LoggerFactory to consider itself uninitialized. * * <p> * This method is intended to be called by classes (in the same package) for * testing purposes. This method is internal. It can be modified, renamed or * removed at any time without notice. * * <p> * You are strongly discouraged from calling this method in production code. */ static void reset() { INITIALIZATION_STATE = UNINITIALIZED; GET_SINGLETON_METHOD = UNINITIALIZED; TEMP_FACTORY = new SubstituteLoggerFactory(); } private final static void performInitialization() { bind(); versionSanityCheck(); singleImplementationSanityCheck(); } private final static void bind() { try { // the next line does the binding getSingleton(); INITIALIZATION_STATE = SUCCESSFUL_INITILIZATION; emitSubstituteLoggerWarning(); } catch (NoClassDefFoundError ncde) { INITIALIZATION_STATE = FAILED_INITILIZATION; String msg = ncde.getMessage(); if (msg != null && msg.indexOf("org/slf4j/impl/StaticLoggerBinder") != -1) { Util .reportFailure("Failed to load class \"org.slf4j.impl.StaticLoggerBinder\"."); Util.reportFailure("See " + NO_STATICLOGGERBINDER_URL + " for further details."); } throw ncde; } catch (Exception e) { INITIALIZATION_STATE = FAILED_INITILIZATION; // we should never get here Util.reportFailure("Failed to instantiate logger [" + getSingleton().getLoggerFactoryClassStr() + "]", e); } } private final static void emitSubstituteLoggerWarning() { List loggerNameList = TEMP_FACTORY.getLoggerNameList(); if (loggerNameList.size() == 0) { return; } Util .reportFailure("The following loggers will not work becasue they were created"); Util .reportFailure("during the default configuration phase of the underlying logging system."); Util.reportFailure("See also " + SUBSTITUTE_LOGGER_URL); for (int i = 0; i < loggerNameList.size(); i++) { String loggerName = (String) loggerNameList.get(i); Util.reportFailure(loggerName); } } private final static void versionSanityCheck() { try { String requested = StaticLoggerBinder.REQUESTED_API_VERSION; boolean match = false; for (int i = 0; i < API_COMPATIBILITY_LIST.length; i++) { if (requested.startsWith(API_COMPATIBILITY_LIST[i])) { match = true; } } if (!match) { Util.reportFailure("The requested version " + requested + " by your slf4j binding is not compatible with " + Arrays.asList(API_COMPATIBILITY_LIST).toString()); Util.reportFailure("See " + VERSION_MISMATCH + " for further details."); } } catch (java.lang.NoSuchFieldError nsfe) { // given our large user base and SLF4J's commitment to backward // compatibility, we cannot cry here. Only for implementations // which willingly declare a REQUESTED_API_VERSION field do we // emit compatibility warnings. } catch (Throwable e) { // we should never reach here Util.reportFailure( "Unexpected problem occured during version sanity check", e); } } // We need to use the name of the StaticLoggerBinder class, we can't reference // the class itseld. private static String STATIC_LOGGER_BINDER_PATH = "org/slf4j/impl/StaticLoggerBinder.class"; private static void singleImplementationSanityCheck() { try { ClassLoader loggerFactoryClassLoader = LoggerFactory.class .getClassLoader(); if (loggerFactoryClassLoader == null) { return; // better than a null pointer exception } Enumeration paths = loggerFactoryClassLoader .getResources(STATIC_LOGGER_BINDER_PATH); List implementationList = new ArrayList(); while (paths.hasMoreElements()) { URL path = (URL) paths.nextElement(); implementationList.add(path); } if (implementationList.size() > 1) { Util.reportFailure("Class path contains multiple SLF4J bindings."); for (int i = 0; i < implementationList.size(); i++) { Util.reportFailure("Found binding in [" + implementationList.get(i) + "]"); } Util.reportFailure("See " + MULTIPLE_BINDINGS_URL + " for an explanation."); } } catch (IOException ioe) { Util.reportFailure("Error getting resources from path", ioe); } } private final static StaticLoggerBinder getSingleton() { if (GET_SINGLETON_METHOD == GET_SINGLETON_INEXISTENT) { return StaticLoggerBinder.SINGLETON; } if (GET_SINGLETON_METHOD == GET_SINGLETON_EXISTS) { return StaticLoggerBinder.getSingleton(); } try { StaticLoggerBinder singleton = StaticLoggerBinder.getSingleton(); GET_SINGLETON_METHOD = GET_SINGLETON_EXISTS; return singleton; } catch (NoSuchMethodError nsme) { GET_SINGLETON_METHOD = GET_SINGLETON_INEXISTENT; return StaticLoggerBinder.SINGLETON; } } /** * Return a logger named according to the name parameter using the statically * bound {@link ILoggerFactory} instance. * * @param name * The name of the logger. * @return logger */ public static Logger getLogger(String name) { ILoggerFactory iLoggerFactory = getILoggerFactory(); return iLoggerFactory.getLogger(name); } /** * Return a logger named corresponding to the class passed as parameter, using * the statically bound {@link ILoggerFactory} instance. * * @param clazz * the returned logger will be named after clazz * @return logger */ public static Logger getLogger(Class clazz) { return getLogger(clazz.getName()); } /** * Return the {@link ILoggerFactory} instance in use. * * <p> * ILoggerFactory instance is bound with this class at compile time. * * @return the ILoggerFactory instance in use */ public static ILoggerFactory getILoggerFactory() { if (INITIALIZATION_STATE == UNINITIALIZED) { INITIALIZATION_STATE = ONGOING_INITILIZATION; performInitialization(); } switch (INITIALIZATION_STATE) { case SUCCESSFUL_INITILIZATION: return getSingleton().getLoggerFactory(); case FAILED_INITILIZATION: throw new IllegalStateException(UNSUCCESSFUL_INIT_MSG); case ONGOING_INITILIZATION: // support re-entrant behavior. return TEMP_FACTORY; } throw new IllegalStateException("Unreachable code"); } }
package mho.qbar.objects; import mho.wheels.math.MathUtils; import mho.wheels.misc.BigDecimalUtils; import mho.wheels.misc.FloatingPointUtils; import mho.wheels.misc.Readers; import mho.wheels.ordering.Ordering; import mho.wheels.structures.Pair; import mho.wheels.structures.Triple; import org.jetbrains.annotations.NotNull; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; import java.util.function.Function; import static mho.wheels.iterables.IterableUtils.*; import static mho.wheels.ordering.Ordering.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public final class Rational implements Comparable<Rational> { public static final @NotNull Rational ZERO = new Rational(BigInteger.ZERO, BigInteger.ONE); public static final @NotNull Rational ONE = new Rational(BigInteger.ONE, BigInteger.ONE); public static final @NotNull Rational SMALLEST_FLOAT = ofExact(Float.MIN_VALUE).get(); public static final @NotNull Rational LARGEST_SUBNORMAL_FLOAT = ofExact(FloatingPointUtils.predecessor(Float.MIN_NORMAL)).get(); public static final @NotNull Rational SMALLEST_NORMAL_FLOAT = ofExact(Float.MIN_NORMAL).get(); public static final @NotNull Rational LARGEST_FLOAT = ofExact(Float.MAX_VALUE).get(); public static final @NotNull Rational SMALLEST_DOUBLE = ofExact(Double.MIN_VALUE).get(); public static final @NotNull Rational LARGEST_SUBNORMAL_DOUBLE = ofExact(FloatingPointUtils.predecessor(Double.MIN_NORMAL)).get(); public static final @NotNull Rational SMALLEST_NORMAL_DOUBLE = ofExact(Double.MIN_NORMAL).get(); public static final @NotNull Rational LARGEST_DOUBLE = ofExact(Double.MAX_VALUE).get(); /** * an {@code Iterable} that contains every harmonic number. Does not support removal. * * Length is infinite */ public static final @NotNull Iterable<Rational> HARMONIC_NUMBERS = scanl(Rational::add, ONE, map(i -> new Rational(BigInteger.ONE, BigInteger.valueOf(i)), rangeUp(2))); /** * {@code this} times {@code denominator} */ private final @NotNull BigInteger numerator; private final @NotNull BigInteger denominator; /** * Private constructor from {@link BigInteger}s; assumes arguments are valid. * * <ul> * <li>{@code numerator} cannot be null.</li> * <li>{@code denominator} cannot be null or equal to 0.</li> * <li>{@code numerator} and {@code denominator} cannot have a positive common factor greater than 1.</li> * <li>Any {@code Rational} may be constructed with this constructor.</li> * </ul> * * @param numerator the numerator * @param denominator the denominator */ private Rational(@NotNull BigInteger numerator, @NotNull BigInteger denominator) { this.numerator = numerator; this.denominator = denominator; } /** * Returns this {@code Rational}'s numerator. * * <ul> * <li>The result is non-null.</li> * </ul> * * @return the numerator */ public @NotNull BigInteger getNumerator() { return numerator; } /** * Returns this {@code Rational}'s denominator. * * <ul> * <li>The result is positive.</li> * </ul> * * @return the denominator */ public @NotNull BigInteger getDenominator() { return denominator; } /** * Creates a {@code Rational} from {@code BigInteger}s. Throws an exception if {@code denominator} is zero. Reduces * arguments and negates denominator if necessary. * * <ul> * <li>{@code numerator} cannot be null.</li> * <li>{@code denominator} cannot be null or equal to 0.</li> * <li>The result is non-null.</li> * </ul> * * @param numerator the numerator * @param denominator the denominator * @return the {@code Rational} corresponding to {@code numerator}/{@code denominator} */ public static @NotNull Rational of(@NotNull BigInteger numerator, @NotNull BigInteger denominator) { if (denominator.equals(BigInteger.ZERO)) throw new ArithmeticException("division by zero"); if (numerator.equals(BigInteger.ZERO)) return ZERO; if (numerator.equals(denominator)) return ONE; BigInteger gcd = numerator.gcd(denominator); if (denominator.signum() < 0) gcd = gcd.negate(); return new Rational(numerator.divide(gcd), denominator.divide(gcd)); } public static @NotNull Rational of(long numerator, long denominator) { if (denominator == 0) throw new ArithmeticException("division by zero"); if (numerator == 0) return ZERO; if (numerator == denominator) return ONE; long gcd = MathUtils.gcd(numerator, denominator); if (denominator < 0) gcd = -gcd; return new Rational(BigInteger.valueOf(numerator / gcd), BigInteger.valueOf(denominator / gcd)); } public static @NotNull Rational of(int numerator, int denominator) { if (denominator == 0) throw new ArithmeticException("division by zero"); if (numerator == 0) return ZERO; if (numerator == denominator) return ONE; int gcd = MathUtils.gcd(numerator, denominator); if (denominator < 0) gcd = -gcd; return new Rational(BigInteger.valueOf(numerator / gcd), BigInteger.valueOf(denominator / gcd)); } /** * Creates a {@code Rational} from a {@code BigInteger}. * * <ul> * <li>{@code n} cannot be null.</li> * <li>The result is an integral {@code Rational}.</li> * </ul> * * @param n the {@code BigInteger} * @return the {@code Rational} equal to {@code n} */ public static @NotNull Rational of(@NotNull BigInteger n) { if (n.equals(BigInteger.ZERO)) return ZERO; if (n.equals(BigInteger.ONE)) return ONE; return new Rational(n, BigInteger.ONE); } public static @NotNull Rational of(long n) { if (n == 0) return ZERO; if (n == 1) return ONE; return new Rational(BigInteger.valueOf(n), BigInteger.ONE); } public static @NotNull Rational of(int n) { if (n == 0) return ZERO; if (n == 1) return ONE; return new Rational(BigInteger.valueOf(n), BigInteger.ONE); } public static @NotNull Optional<Rational> of(float f) { if (f == 0.0) return Optional.of(ZERO); if (f == 1.0) return Optional.of(ONE); if (Float.isInfinite(f) || Float.isNaN(f)) return Optional.empty(); return Optional.of(of(new BigDecimal(Float.toString(f)))); } public static @NotNull Optional<Rational> of(double d) { if (d == 0.0) return Optional.of(ZERO); if (d == 1.0) return Optional.of(ONE); if (Double.isInfinite(d) || Double.isNaN(d)) return Optional.empty(); return Optional.of(of(BigDecimal.valueOf(d))); } @SuppressWarnings("JavaDoc") public static @NotNull Optional<Rational> ofExact(float f) { if (f == 0.0f) return Optional.of(ZERO); if (f == 1.0f) return Optional.of(ONE); Optional<Pair<Integer, Integer>> ome = FloatingPointUtils.toMantissaAndExponent(f); if (!ome.isPresent()) return Optional.empty(); Pair<Integer, Integer> me = ome.get(); return Optional.of(of(me.a).shiftLeft(me.b)); } @SuppressWarnings("JavaDoc") public static @NotNull Optional<Rational> ofExact(double d) { if (d == 0.0) return Optional.of(ZERO); if (d == 1.0) return Optional.of(ONE); Optional<Pair<Long, Integer>> ome = FloatingPointUtils.toMantissaAndExponent(d); if (!ome.isPresent()) return Optional.empty(); Pair<Long, Integer> me = ome.get(); return Optional.of(of(me.a).shiftLeft(me.b)); } public static @NotNull Rational of(@NotNull BigDecimal d) { return of(d.unscaledValue()).divide(of(10).pow(d.scale())); } /** * Determines whether {@code this} is integral. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @return whether this is an integer */ public boolean isInteger() { return denominator.equals(BigInteger.ONE); } /** * Rounds {@code this} to an integer according to {@code roundingMode}; see {@link java.math.RoundingMode} for * details. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code roundingMode} may be any {@code RoundingMode}.</li> * <li>If {@code roundingMode} is {@link java.math.RoundingMode#UNNECESSARY}, {@code this} must be an * integer.</li> * <li>The result is not null.</li> * </ul> * * @param roundingMode determines the way in which {@code this} is rounded. Options are * {@link java.math.RoundingMode#UP}, {@link java.math.RoundingMode#DOWN}, {@link java.math.RoundingMode#CEILING}, * {@link java.math.RoundingMode#FLOOR}, {@link java.math.RoundingMode#HALF_UP}, * {@link java.math.RoundingMode#HALF_DOWN}, {@link java.math.RoundingMode#HALF_EVEN}, and * {@link java.math.RoundingMode#UNNECESSARY}. * @return {@code this}, rounded */ public @NotNull BigInteger bigIntegerValue(@NotNull RoundingMode roundingMode) { Ordering halfCompare = compare(fractionalPart(), of(1, 2)); if (signum() == -1) halfCompare = halfCompare.invert(); switch (roundingMode) { case UNNECESSARY: if (denominator.equals(BigInteger.ONE)) { return numerator; } else { throw new ArithmeticException("Rational not an integer. Use a different rounding mode"); } case FLOOR: return floor(); case CEILING: return ceiling(); case DOWN: return numerator.divide(denominator); case UP: BigInteger down = numerator.divide(denominator); if (numerator.mod(denominator).equals(BigInteger.ZERO)) { return down; } else { if (numerator.signum() == 1) { return down.add(BigInteger.ONE); } else { return down.subtract(BigInteger.ONE); } } case HALF_DOWN: if (halfCompare == GT) { return bigIntegerValue(RoundingMode.UP); } else { return bigIntegerValue(RoundingMode.DOWN); } case HALF_UP: if (halfCompare == LT) { return bigIntegerValue(RoundingMode.DOWN); } else { return bigIntegerValue(RoundingMode.UP); } case HALF_EVEN: if (halfCompare == LT) return bigIntegerValue(RoundingMode.DOWN); if (halfCompare == GT) return bigIntegerValue(RoundingMode.UP); BigInteger floor = floor(); return floor.testBit(0) ? floor.add(BigInteger.ONE) : floor; } return null; //never happens } /** * Rounds {@code this} to the nearest {@code BigInteger}, breaking ties with the half-even rule (see * {@link java.math.RoundingMode#HALF_EVEN}). * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is not null.</li> * </ul> * * @return {@code this}, rounded */ public @NotNull BigInteger bigIntegerValue() { return bigIntegerValue(RoundingMode.HALF_EVEN); } /** * Converts {@code this} to a {@code BigInteger}. Throws an {@link java.lang.ArithmeticException} if {@code this} * is not integral. * * <ul> * <li>{@code this} must be an integer.</li> * <li>The result is not null.</li> * </ul> * * @return the {@code BigInteger} value of {@code this} */ public @NotNull BigInteger bigIntegerValueExact() { if (denominator.equals(BigInteger.ONE)) { return numerator; } else { throw new ArithmeticException("Rational not an integer. Use a different rounding mode"); } } /** * Converts {@code this} to a {@code byte}. Throws an {@link java.lang.ArithmeticException} if {@code this} is not * integral or outside of a {@code byte}'s range. * * <ul> * <li>{@code this} must be an integer within a {@code byte}'s range.</li> * <li>The result can be any {@code byte}.</li> * </ul> * * @return the {@code byte} value of {@code this} */ public byte byteValueExact() { return bigIntegerValueExact().byteValueExact(); } /** * Converts {@code this} to a {@code short}. Throws an {@link java.lang.ArithmeticException} if {@code this} is not * integral or outside of a {@code short}'s range. * * <ul> * <li>{@code this} must be an integer within a {@code short}'s range.</li> * <li>The result can be any {@code short}.</li> * </ul> * * @return the {@code short} value of {@code this} */ public short shortValueExact() { return bigIntegerValueExact().shortValueExact(); } /** * Converts {@code this} to an {@code int}. Throws an {@link java.lang.ArithmeticException} if {@code this} is not * integral or outside of an {@code int}'s range. * * <ul> * <li>{@code this} must be an integer within an {@code int}'s range.</li> * <li>The result can be any {@code int}.</li> * </ul> * * @return the {@code int} value of {@code this} */ public int intValueExact() { return bigIntegerValueExact().intValueExact(); } /** * Converts {@code this} to a {@code long}. Throws an {@link java.lang.ArithmeticException} if {@code this} is not * integral or outside of a {@code long}'s range. * * <ul> * <li>{@code this} must be an integer within a {@code long}'s range.</li> * <li>The result can be any {@code long}.</li> * </ul> * * @return the {@code long} value of {@code this} */ public long longValueExact() { return bigIntegerValueExact().longValueExact(); } /** * Determines whether {@code this} has a terminating digit expansion in a particular base. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code base} must be at least 2.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param base the base in which we are interesting in expanding {@code this} * @return whether {@code this} has a terminating base expansion in base-{@code base} */ public boolean hasTerminatingBaseExpansion(@NotNull BigInteger base) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (isInteger()) return true; BigInteger remainder = denominator; for (BigInteger baseFactor : nub(MathUtils.primeFactors(base))) { while (remainder.mod(baseFactor).equals(BigInteger.ZERO)) { remainder = remainder.divide(baseFactor); } } return remainder.equals(BigInteger.ONE); } /** * Rounds {@code this} to a {@link java.math.BigDecimal} with a specified rounding mode (see documentation for * {@code java.math.RoundingMode} for details) and with a specified precision (number of significant digits), or * to full precision if {@code precision} is 0. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code precision} cannot be negative.</li> * <li>{@code roundingMode} may be any {@code RoundingMode}.</li> * <li>If {@code precision} is 0, then {@code this} must be a {@code Rational} whose decimal expansion is * terminating; that is, its denominator must only have 2 or 5 as prime factors.</li> * <li>If {@code roundingMode} is {@code RoundingMode.UNNECESSARY}, then {@code precision} must be at least as * large as the number of digits in {@code this}'s decimal expansion.</li> * <li>The result is non-null.</li> * </ul> * * @param precision the precision with which to round {@code this}. 0 indicates full precision. * @param roundingMode specifies the details of how to round {@code this}. * @return {@code this}, in {@code BigDecimal} form */ public @NotNull BigDecimal bigDecimalValue(int precision, @NotNull RoundingMode roundingMode) { MathContext context = new MathContext(precision, roundingMode); BigDecimal result = new BigDecimal(numerator).divide(new BigDecimal(denominator), context); if (precision != 0) { result = BigDecimalUtils.setPrecision(result, precision); } return result; } public @NotNull BigDecimal bigDecimalValue(int precision) { return bigDecimalValue(precision, RoundingMode.HALF_EVEN); } public @NotNull BigDecimal bigDecimalValueExact() { //noinspection BigDecimalMethodWithoutRoundingCalled return new BigDecimal(numerator).divide(new BigDecimal(denominator)); } public int binaryExponent() { if (this == ONE) return 0; if (this == ZERO || this.signum() != 1) throw new IllegalArgumentException("Rational must be positive"); Rational adjusted = this; int exponent = 0; if (lt(numerator, denominator)) { while (lt(adjusted.numerator, adjusted.denominator)) { adjusted = adjusted.shiftLeft(1); exponent } } else { while (ge(adjusted.numerator, adjusted.denominator)) { adjusted = adjusted.shiftRight(1); exponent++; } exponent } return exponent; } /** * Every {@code Rational} has a <i>left-neighboring {@code float}</i>, or the largest {@code float} that is less * than or equal to the {@code Rational}; this {@code float} may be -Infinity. Likewise, every {@code Rational} * has a <i>right-neighboring {@code float}</i>: the smallest {@code float} greater than or equal to the * {@code Rational}. This {@code float} may be Infinity. If {@code this} is exactly equal to some {@code float}, * the left- and right-neighboring {@code float}s will both be equal to that {@code float} and to each other. This * method returns the pair made up of the left- and right-neighboring {@code float}s. If the left-neighboring * {@code float} is a zero, it is a positive zero; if the right-neighboring {@code float} is a zero, it is a * negative zero. The exception is when {@code this} is equal to zero; then both neighbors are positive zeroes. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is a pair of {@code float}s that are either equal, or the second is the next-largest * {@code float} after the first. Negative zero may not appear in the first slot of the pair, and positive zero * may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a * {@code NaN}.</li> * </ul> * * @return The pair of left- and right-neighboring {@code float}s. */ private @NotNull Pair<Float, Float> floatRange() { if (this == ZERO) return new Pair<>(0.0f, 0.0f); if (numerator.signum() == -1) { Pair<Float, Float> negativeRange = negate().floatRange(); return new Pair<>(-negativeRange.b, -negativeRange.a); } int exponent = binaryExponent(); if (exponent > 127 || exponent == 127 && gt(this, LARGEST_FLOAT)) { return new Pair<>(Float.MAX_VALUE, Float.POSITIVE_INFINITY); } Rational fraction; int adjustedExponent; if (exponent < -126) { fraction = shiftLeft(149); adjustedExponent = 0; } else { fraction = shiftRight(exponent).subtract(ONE).shiftLeft(23); adjustedExponent = exponent + 127; } float loFloat = Float.intBitsToFloat((adjustedExponent << 23) + fraction.floor().intValueExact()); float hiFloat = fraction.denominator.equals(BigInteger.ONE) ? loFloat : FloatingPointUtils.successor(loFloat); return new Pair<>(loFloat, hiFloat); } /** * Every {@code Rational} has a <i>left-neighboring {@code double}</i>, or the largest {@code double} that is less * than or equal to the {@code Rational}; this {@code double} may be {@code -Infinity}. Likewise, every * {@code Rational} has a <i>right-neighboring {@code double}</i>: the smallest {@code double} greater than or * equal to the {@code Rational}. This {@code double} may be {@code Infinity}. If {@code this} is exactly equal to * some {@code double}, the left- and right-neighboring {@code double}s will both be equal to that {@code double} * and to each other. This method returns the pair made up of the left- and right-neighboring {@code double}s. If * the left-neighboring {@code double} is a zero, it is a positive zero; if the right-neighboring {@code double} is * a zero, it is a negative zero. The exception is when {@code this} is equal to zero; then both neighbors are * positive zeroes. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is a pair of {@code double}s that are either equal, or the second is the next-largest * {@code double} after the first. Negative zero may not appear in the first slot of the pair, and positive zero * may only appear in the second slot if the first slot also contains a positive zero. Neither slot may contain a * {@code NaN}.</li> * </ul> * * @return The pair of left- and right-neighboring {@code double}s. */ private @NotNull Pair<Double, Double> doubleRange() { if (this == ZERO) return new Pair<>(0.0, 0.0); if (numerator.signum() == -1) { Pair<Double, Double> negativeRange = negate().doubleRange(); return new Pair<>(-negativeRange.b, -negativeRange.a); } int exponent = binaryExponent(); if (exponent > 1023 || exponent == 1023 && gt(this, LARGEST_DOUBLE)) { return new Pair<>(Double.MAX_VALUE, Double.POSITIVE_INFINITY); } Rational fraction; int adjustedExponent; if (exponent < -1022) { fraction = shiftLeft(1074); adjustedExponent = 0; } else { fraction = shiftRight(exponent).subtract(ONE).shiftLeft(52); adjustedExponent = exponent + 1023; } double loDouble = Double.longBitsToDouble(((long) adjustedExponent << 52) + fraction.floor().longValueExact()); double hiDouble = fraction.denominator.equals(BigInteger.ONE) ? loDouble : FloatingPointUtils.successor(loDouble); return new Pair<>(loDouble, hiDouble); } public float floatValue(@NotNull RoundingMode roundingMode) { Pair<Float, Float> floatRange = floatRange(); if (floatRange.a.equals(floatRange.b)) return floatRange.a; Optional<Rational> loFloat = ofExact(floatRange.a); Optional<Rational> hiFloat = ofExact(floatRange.b); if (!(loFloat.isPresent() && hiFloat.isPresent()) && roundingMode == RoundingMode.UNNECESSARY) { throw new ArithmeticException("Rational not exactly equal to a float. Use a different rounding mode"); } if (!loFloat.isPresent()) { if (roundingMode == RoundingMode.FLOOR || roundingMode == RoundingMode.UP || roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) { return Float.NEGATIVE_INFINITY; } else { return -Float.MAX_VALUE; } } if (!hiFloat.isPresent()) { if (roundingMode == RoundingMode.CEILING || roundingMode == RoundingMode.UP || roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) { return Float.POSITIVE_INFINITY; } else { return Float.MAX_VALUE; } } Rational midway = loFloat.get().add(hiFloat.get()).shiftRight(1); Ordering midwayCompare = compare(this, midway); switch (roundingMode) { case UNNECESSARY: throw new ArithmeticException("Rational not exactly equal to a float. Use a different rounding mode"); case FLOOR: return floatRange.a; case CEILING: return floatRange.b; case DOWN: return floatRange.a < 0 ? floatRange.b : floatRange.a; case UP: return floatRange.a < 0 ? floatRange.a : floatRange.b; case HALF_DOWN: if (midwayCompare == EQ) return signum() == 1 ? floatRange.a : floatRange.b; return midwayCompare == LT ? floatRange.a : floatRange.b; case HALF_UP: if (midwayCompare == EQ) return signum() == 1 ? floatRange.b : floatRange.a; return midwayCompare == LT ? floatRange.a : floatRange.b; case HALF_EVEN: if (midwayCompare == LT) return floatRange.a; if (midwayCompare == GT) return floatRange.b; return (Float.floatToIntBits(floatRange.a) & 1) == 0 ? floatRange.a : floatRange.b; } return 0; //never happens } public float floatValue() { return floatValue(RoundingMode.HALF_EVEN); } /** * Returns a {@code float} exactly equal to {@code this}. Throws an {@code ArithmeticException} if {@code this} is * not exactly equal to a {@code float}. * * <ul> * <li>{@code this} must be a {@code Rational} equal to a {@code float}.</li> * <li>The result is not {@code NaN}, infinite, or negative 0.</li> * </ul> * * @return {@code this}, in {@code float} form */ public float floatValueExact() { return floatValue(RoundingMode.UNNECESSARY); } public double doubleValue(@NotNull RoundingMode roundingMode) { Pair<Double, Double> doubleRange = doubleRange(); if (doubleRange.a.equals(doubleRange.b)) return doubleRange.a; Optional<Rational> loDouble = ofExact(doubleRange.a); Optional<Rational> hiDouble = ofExact(doubleRange.b); if (!(loDouble.isPresent() && hiDouble.isPresent()) && roundingMode == RoundingMode.UNNECESSARY) { throw new ArithmeticException("Rational not exactly equal to a double. Use a different rounding mode"); } if (!loDouble.isPresent()) { if (roundingMode == RoundingMode.FLOOR || roundingMode == RoundingMode.UP || roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) { return Double.NEGATIVE_INFINITY; } else { return -Double.MAX_VALUE; } } if (!hiDouble.isPresent()) { if (roundingMode == RoundingMode.CEILING || roundingMode == RoundingMode.UP || roundingMode == RoundingMode.HALF_UP || roundingMode == RoundingMode.HALF_EVEN) { return Double.POSITIVE_INFINITY; } else { return Double.MAX_VALUE; } } Rational midway = loDouble.get().add(hiDouble.get()).shiftRight(1); Ordering midwayCompare = compare(this, midway); switch (roundingMode) { case UNNECESSARY: throw new ArithmeticException("Rational not exactly equal to a double. Use a different rounding mode"); case FLOOR: return doubleRange.a; case CEILING: return doubleRange.b; case DOWN: return doubleRange.a < 0 ? doubleRange.b : doubleRange.a; case UP: return doubleRange.a < 0 ? doubleRange.a : doubleRange.b; case HALF_DOWN: if (midwayCompare == EQ) return signum() == 1 ? doubleRange.a : doubleRange.b; return midwayCompare == LT ? doubleRange.a : doubleRange.b; case HALF_UP: if (midwayCompare == EQ) return signum() == 1 ? doubleRange.b : doubleRange.a; return midwayCompare == LT ? doubleRange.a : doubleRange.b; case HALF_EVEN: if (midwayCompare == LT) return doubleRange.a; if (midwayCompare == GT) return doubleRange.b; return (Double.doubleToLongBits(doubleRange.a) & 1) == 0 ? doubleRange.a : doubleRange.b; } return 0; //never happens } public double doubleValue() { return doubleValue(RoundingMode.HALF_EVEN); } /** * Returns a {@code double} exactly equal to {@code this}. Throws an {@code ArithmeticException} if {@code this} is * not exactly equal to a {@code double}. * * <ul> * <li>{@code this} must be a {@code Rational} equal to a {@code double}.</li> * <li>The result is not {@code NaN}, infinite, or negative 0.</li> * </ul> * * @return {@code this}, in {@code double} form */ public double doubleValueExact() { return doubleValue(RoundingMode.UNNECESSARY); } /** * Returns the sum of {@code this} and {@code that}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code that} cannot be null.</li> * <li>The result is not null.</li> * </ul> * * @param that the {@code Rational} added to {@code this} * @return {@code this}+{@code that} */ public @NotNull Rational add(@NotNull Rational that) { if (this == ZERO) return that; if (that == ZERO) return this; BigInteger d1 = denominator.gcd(that.denominator); if (d1.equals(BigInteger.ONE)) { BigInteger sn = numerator.multiply(that.denominator).add(denominator.multiply(that.numerator)); if (sn.equals(BigInteger.ZERO)) return ZERO; BigInteger sd = denominator.multiply(that.denominator); if (sn.equals(sd)) return ONE; return new Rational(sn, sd); } else { BigInteger t = numerator.multiply(that.denominator.divide(d1)) .add(that.numerator.multiply(denominator.divide(d1))); if (t.equals(BigInteger.ZERO)) return ZERO; BigInteger d2 = t.gcd(d1); BigInteger sn = t.divide(d2); BigInteger sd = denominator.divide(d1).multiply(that.denominator.divide(d2)); if (sn.equals(sd)) return ONE; return new Rational(sn, sd); } } public @NotNull Rational negate() { if (this == ZERO) return ZERO; BigInteger negativeNumerator = numerator.negate(); if (negativeNumerator.equals(denominator)) return ONE; return new Rational(negativeNumerator, denominator); } /** * Returns the absolute value of {@code this}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is a non-negative {@code Rational}.</li> * </ul> * * @return |{@code this}| */ public @NotNull Rational abs() { if (this == ZERO || this == ONE) return this; if (numerator.equals(BigInteger.valueOf(-1)) && denominator.equals(BigInteger.ONE)) return ONE; return new Rational(numerator.abs(), denominator); } @SuppressWarnings("JavaDoc") public int signum() { return numerator.signum(); } public @NotNull Rational subtract(@NotNull Rational that) { if (this == ZERO) return that.negate(); if (that == ZERO) return this; if (this == that) return ZERO; BigInteger d1 = denominator.gcd(that.denominator); if (d1.equals(BigInteger.ONE)) { BigInteger sn = numerator.multiply(that.denominator).subtract(denominator.multiply(that.numerator)); if (sn.equals(BigInteger.ZERO)) return ZERO; BigInteger sd = denominator.multiply(that.denominator); if (sn.equals(sd)) return ONE; return new Rational(sn, sd); } else { BigInteger t = numerator.multiply(that.denominator.divide(d1)) .subtract(that.numerator.multiply(denominator.divide(d1))); if (t.equals(BigInteger.ZERO)) return ZERO; BigInteger d2 = t.gcd(d1); BigInteger sn = t.divide(d2); BigInteger sd = denominator.divide(d1).multiply(that.denominator.divide(d2)); if (sn.equals(sd)) return ONE; return new Rational(sn, sd); } } public @NotNull Rational multiply(@NotNull Rational that) { if (this == ZERO || that == ZERO) return ZERO; if (this == ONE) return that; if (that == ONE) return this; return of(numerator.multiply(that.getNumerator()), denominator.multiply(that.getDenominator())); } public @NotNull Rational multiply(@NotNull BigInteger that) { if (this == ZERO || that.equals(BigInteger.ZERO)) return ZERO; if (numerator.equals(BigInteger.ONE) && denominator.equals(that) || numerator.equals(BigInteger.valueOf(-1)) && denominator.equals(that.negate())) return ONE; BigInteger g = denominator.gcd(that); return new Rational(numerator.multiply(that.divide(g)), denominator.divide(g)); } public @NotNull Rational multiply(int that) { if (this == ZERO || that == 0) return ZERO; if (numerator.equals(BigInteger.ONE) && denominator.equals(BigInteger.valueOf(that))) return ONE; if (numerator.equals(BigInteger.valueOf(-1)) && denominator.equals(BigInteger.valueOf(that).negate())) return ONE; BigInteger g = denominator.gcd(BigInteger.valueOf(that)); return new Rational(numerator.multiply(BigInteger.valueOf(that).divide(g)), denominator.divide(g)); } /** * Returns the multiplicative inverse of {@code this}. * * <ul> * <li>{@code this} may be any non-zero {@code Rational}.</li> * <li>The result is a non-zero {@code Rational}.</li> * </ul> * * @return 1/{@code this} */ public @NotNull Rational invert() { if (this == ZERO) throw new ArithmeticException("division by zero"); if (this == ONE) return ONE; if (numerator.signum() == -1) { return new Rational(denominator.negate(), numerator.negate()); } else { return new Rational(denominator, numerator); } } /** * Returns the quotient of {@code a} and {@code b}. * * <ul> * <li>{@code this} can be any {@code Rational}.</li> * <li>{@code that} cannot be null or zero.</li> * <li>The result is not null.</li> * </ul> * * @param that {@code Rational} that {@code this} is divide by * @return {@code this}/{@code that} */ public @NotNull Rational divide(@NotNull Rational that) { return multiply(that.invert()); } /** * Returns the quotient of {@code this} and {@code that}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code that} cannot be null or zero.</li> * <li>The result is not null.</li> * </ul> * * @param that the divisor * @return {@code this}/{@code that} */ public @NotNull Rational divide(@NotNull BigInteger that) { if (that.equals(BigInteger.ZERO)) throw new ArithmeticException("division by zero"); if (this == ZERO) return ZERO; if (denominator.equals(BigInteger.ONE) && numerator.equals(that)) return ONE; BigInteger g = numerator.gcd(that); if (that.signum() == -1) g = g.negate(); return new Rational(numerator.divide(g), denominator.multiply(that.divide(g))); } /** * Returns the quotient of {@code this} and {@code that}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code that} cannot be zero.</li> * <li>The result is not null.</li> * </ul> * * @param that the divisor * @return {@code this}/{@code that} */ public @NotNull Rational divide(int that) { if (that == 0) throw new ArithmeticException("division by zero"); if (this == ZERO) return ZERO; if (denominator.equals(BigInteger.ONE) && numerator.equals(BigInteger.valueOf(that))) return ONE; BigInteger g = numerator.gcd(BigInteger.valueOf(that)); if (that < 0) g = g.negate(); return new Rational(numerator.divide(g), denominator.multiply(BigInteger.valueOf(that).divide(g))); } public @NotNull Rational shiftLeft(int bits) { if (this == ZERO) return ZERO; if (bits == 0) return this; if (bits < 0) return shiftRight(-bits); int denominatorTwos = denominator.getLowestSetBit(); if (bits <= denominatorTwos) { BigInteger shifted = denominator.shiftRight(bits); if (numerator.equals(shifted)) return ONE; return new Rational(numerator, shifted); } else { BigInteger shiftedNumerator = numerator.shiftLeft(bits - denominatorTwos); BigInteger shiftedDenominator = denominator.shiftRight(denominatorTwos); if (shiftedNumerator.equals(shiftedDenominator)) return ONE; return new Rational(shiftedNumerator, shiftedDenominator); } } public @NotNull Rational shiftRight(int bits) { if (this == ZERO) return ZERO; if (bits == 0) return this; if (bits < 0) return shiftLeft(-bits); int numeratorTwos = numerator.getLowestSetBit(); if (bits <= numeratorTwos) { BigInteger shifted = numerator.shiftRight(bits); if (shifted.equals(denominator)) return ONE; return new Rational(shifted, denominator); } else { BigInteger shiftedNumerator = numerator.shiftRight(numeratorTwos); BigInteger shiftedDenominator = denominator.shiftLeft(bits - numeratorTwos); if (shiftedNumerator.equals(shiftedDenominator)) return ONE; return new Rational(shiftedNumerator, shiftedDenominator); } } public static @NotNull Rational sum(@NotNull Iterable<Rational> xs) { if (any(x -> x == null, xs)) throw new NullPointerException(); return foldl(Rational::add, ZERO, xs); } public static @NotNull Rational product(@NotNull Iterable<Rational> xs) { if (any(x -> x == null, xs)) throw new NullPointerException(); List<Rational> denominatorSorted = sort( (x, y) -> { Ordering o = compare(x.getDenominator(), y.getDenominator()); if (o == EQ) { o = compare(x.getNumerator().abs(), y.getNumerator().abs()); } if (o == EQ) { o = compare(x.getNumerator().signum(), y.getNumerator().signum()); } return o.toInt(); }, xs ); return foldl(Rational::multiply, ONE, denominatorSorted); } public static @NotNull Iterable<Rational> delta(@NotNull Iterable<Rational> xs) { if (isEmpty(xs)) throw new IllegalArgumentException("cannot get delta of empty Iterable"); if (head(xs) == null) throw new NullPointerException(); return adjacentPairsWith((x, y) -> y.subtract(x), xs); } /** * The {@code n}th harmonic number, or the sum of the first {@code n} reciprocals. * * <ul> * <li>{@code n} must be positive.</li> * <li>The result is a harmonic number.</li> * </ul> * * @param n the index of a harmonic number * @return H<sub>{@code n}</sub> */ public static @NotNull Rational harmonicNumber(int n) { if (n < 1) throw new ArithmeticException("harmonic number must have positive index"); return sum(map(i -> i == 1 ? ONE : new Rational(BigInteger.ONE, BigInteger.valueOf(i)), range(1, n))); } /** * Returns {@code this} raised to the power of {@code p}. 0<sup>0</sup> yields 1. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code p} may be any {@code int}.</li> * <li>If {@code p}{@literal <}0, {@code this} cannot be 0.</li> * <li>The result is not null.</li> * </ul> * * @param p the power that {@code this} is raised to * @return {@code this}<sup>{@code p}</sup> */ public @NotNull Rational pow(int p) { if (p == 0) return ONE; if (p == 1) return this; if (p < 0) { return invert().pow(-p); } if (this == ZERO || this == ONE) return this; if (this.equals(ONE.negate()) && p % 2 == 0) return ONE; BigInteger pNumerator = numerator.pow(p); BigInteger pDenominator = denominator.pow(p); if (pDenominator.signum() == -1) { pNumerator = pNumerator.negate(); pDenominator = pDenominator.negate(); } return new Rational(pNumerator, pDenominator); } public @NotNull BigInteger floor() { if (numerator.signum() < 0) { return isInteger() ? bigIntegerValueExact() : numerator.divide(denominator).subtract(BigInteger.ONE); } else { return numerator.divide(denominator); } } public @NotNull BigInteger ceiling() { return isInteger() ? bigIntegerValueExact() : floor().add(BigInteger.ONE); } public @NotNull Rational fractionalPart() { if (denominator.equals(BigInteger.ONE)) return ZERO; return subtract(of(floor())); } /** * Rounds {@code this} a rational number that is an integer multiple of 1/{@code denominator} according to * {@code roundingMode}; see documentation for {@link java.math.RoundingMode} for details. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code denominator} must be positive.</li> * <li>If {@code roundingMode} is {@code RoundingMode.UNNECESSARY}, {@code this}'s denominator must divide * {@code denominator}.</li> * <li>The result is not null.</li> * </ul> * * @param denominator the denominator which represents the precision that {@code this} is rounded to. * @param roundingMode determines the way in which {@code this} is rounded. Options are {@code RoundingMode.UP}, * {@code RoundingMode.DOWN}, {@code RoundingMode.CEILING}, {@code RoundingMode.FLOOR}, * {@code RoundingMode.HALF_UP}, {@code RoundingMode.HALF_DOWN}, * {@code RoundingMode.HALF_EVEN}, and {@code RoundingMode.UNNECESSARY}. * @return {@code this}, rounded to an integer multiple of 1/{@code denominator} */ public @NotNull Rational roundToDenominator(@NotNull BigInteger denominator, @NotNull RoundingMode roundingMode) { if (denominator.signum() != 1) throw new ArithmeticException("must round to a positive denominator"); return of(multiply(denominator).bigIntegerValue(roundingMode)).divide(denominator); } /** * Finds the continued fraction of {@code this}. If we pretend that the result is an array called a of length n, * then {@code this}=a[0]+1/(a[1]+1/(a[2]+...+1/a[n-1])...). Every rational number has two such representations; * this method returns the shortest one. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is non-null and non-empty. None of its elements are null. The first element may be any * {@code BigInteger}; the remaining elements, if any, are all positive. If the result has more than one element, * the last element is greater than 1.</li> * </ul> * * Length is O(log({@code denominator})) * * @return the continued-fraction-representation of {@code this} */ public @NotNull List<BigInteger> continuedFraction() { List<BigInteger> continuedFraction = new ArrayList<>(); Rational remainder = this; while (true) { BigInteger floor = remainder.floor(); continuedFraction.add(floor); remainder = remainder.subtract(of(floor)); if (remainder == ZERO) break; remainder = remainder.invert(); } return continuedFraction; } /** * Returns the {@code Rational} corresponding to a continued fraction. Every rational number has two continued- * fraction representations; either is accepted. * * <ul> * <li>{@code continuedFraction} must be non-null and non-empty. All elements but the first must be positive.</li> * <li>The result is not null.</li> * </ul> * * @param continuedFraction a continued fraction * @return a[0]+1/(a[1]+1/(a[2]+...+1/a[n-1])...) */ public static @NotNull Rational fromContinuedFraction(@NotNull List<BigInteger> continuedFraction) { if (continuedFraction.isEmpty()) throw new IllegalArgumentException("continued fraction may not be empty"); BigInteger lastElement = continuedFraction.get(continuedFraction.size() - 1); if (continuedFraction.size() > 1 && lastElement.signum() != 1) throw new IllegalArgumentException("all continued fraction elements but the first must be positive"); Rational x = of(lastElement); for (int i = continuedFraction.size() - 2; i >= 0; i if (i != 0 && continuedFraction.get(i).signum() != 1) throw new IllegalArgumentException("all continued fraction elements but the first must be positive"); x = x.invert().add(of(continuedFraction.get(i))); } return x; } /** * Returns the convergents, or rational approximations of {@code this} formed by truncating its continued fraction * at various points. The first element of the result is the floor of {@code this}, and the last element is * {@code this}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is a non-null, finite, non-empty {@code Iterable} that consists of the convergents of its last * element.</li> * </ul> * * Length is O(log({@code denominator})) * * @return the convergents of {@code this}. */ public @NotNull Iterable<Rational> convergents() { return map(cf -> fromContinuedFraction(toList(cf)), tail(inits(continuedFraction()))); } public @NotNull Triple<List<BigInteger>, List<BigInteger>, List<BigInteger>> positionalNotation( @NotNull BigInteger base ) { if (signum() == -1) throw new IllegalArgumentException("this cannot be negative"); BigInteger floor = floor(); List<BigInteger> beforeDecimal = MathUtils.bigEndianDigits(base, floor); Rational fractionalPart = subtract(of(floor)); BigInteger numerator = fractionalPart.numerator; BigInteger denominator = fractionalPart.denominator; BigInteger remainder = numerator.multiply(base); int index = 0; Integer repeatingIndex; List<BigInteger> afterDecimal = new ArrayList<>(); Map<BigInteger, Integer> remainders = new HashMap<>(); while (true) { remainders.put(remainder, index); BigInteger digit = remainder.divide(denominator); afterDecimal.add(digit); remainder = remainder.subtract(denominator.multiply(digit)).multiply(base); repeatingIndex = remainders.get(remainder); if (repeatingIndex != null) break; index++; } List<BigInteger> nonrepeating = new ArrayList<>(); List<BigInteger> repeating = new ArrayList<>(); for (int i = 0; i < repeatingIndex; i++) { nonrepeating.add(afterDecimal.get(i)); } for (int i = repeatingIndex; i < afterDecimal.size(); i++) { repeating.add(afterDecimal.get(i)); } return new Triple<>(beforeDecimal, nonrepeating, repeating); } /** * Creates a {@code Rational} from a base expansion. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code beforeDecimalPoint} must only contain elements greater than or equal to zero and less than * {@code base}.</li> * <li>{@code nonRepeating} must only contain elements greater than or equal to zero and less than * {@code base}.</li> * <li>{@code repeating} must only contain elements greater than or equal to zero and less than * {@code base}. It must also be non-empty; to input a terminating expansion, use one (or more) zeros.</li> * <li>The result is non-negative.</li> * </ul> * * @param base the base of the positional expansion * @param beforeDecimalPoint the digits before the decimal point * @param nonRepeating the non-repeating portion of the digits after the decimal point * @param repeating the repeating portion of the digits after the decimal point * @return (beforeDecimalPoint).(nonRepeating)(repeating)(repeating)(repeating)..._(base) */ public static @NotNull Rational fromPositionalNotation( @NotNull BigInteger base, @NotNull List<BigInteger> beforeDecimalPoint, @NotNull List<BigInteger> nonRepeating, @NotNull List<BigInteger> repeating ) { if (repeating.isEmpty()) throw new IllegalArgumentException("repeating must be nonempty"); BigInteger floor = MathUtils.fromBigEndianDigits(base, beforeDecimalPoint); BigInteger nonRepeatingInteger = MathUtils.fromBigEndianDigits(base, nonRepeating); BigInteger repeatingInteger = MathUtils.fromBigEndianDigits(base, repeating); Rational nonRepeatingPart = of(nonRepeatingInteger, base.pow(nonRepeating.size())); Rational repeatingPart = of(repeatingInteger, base.pow(repeating.size()).subtract(BigInteger.ONE)) .divide(base.pow(nonRepeating.size())); return of(floor).add(nonRepeatingPart).add(repeatingPart); } public @NotNull Pair<List<BigInteger>, Iterable<BigInteger>> digits(@NotNull BigInteger base) { if (signum() == -1) throw new IllegalArgumentException("this cannot be negative"); BigInteger floor = floor(); List<BigInteger> beforeDecimal = MathUtils.bigEndianDigits(base, floor); Rational fractionalPart = subtract(of(floor)); BigInteger numerator = fractionalPart.numerator; BigInteger denominator = fractionalPart.denominator; final BigInteger firstRemainder = numerator.multiply(base); Iterable<BigInteger> afterDecimal = () -> new Iterator<BigInteger>() { private boolean knownRepeating; private int index; private Integer repeatingIndex; private BigInteger remainder; private Map<BigInteger, Integer> remainders; { knownRepeating = false; index = 0; repeatingIndex = null; remainder = firstRemainder; remainders = new HashMap<>(); } @Override public boolean hasNext() { return knownRepeating || repeatingIndex == null; } @Override public BigInteger next() { if (!knownRepeating) { remainders.put(remainder, index); } BigInteger digit = remainder.divide(denominator); remainder = remainder.subtract(denominator.multiply(digit)).multiply(base); if (!knownRepeating) { repeatingIndex = remainders.get(remainder); if (repeatingIndex != null && !remainder.equals(BigInteger.ZERO)) { knownRepeating = true; remainders = null; } else { index++; } } return digit; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove from this iterator"); } }; return new Pair<>(beforeDecimal, skipLastIf(i -> i.equals(BigInteger.ZERO), afterDecimal)); } /** * Converts {@code this} to a {@code String} in any base greater than 1. {@code this} must have a terminating * expansion in the base. If the base is 36 or less, the digits are '0' through '9' followed by 'A' through 'Z'. If * the base is greater than 36, the digits are written in decimal and each digit is surrounded by parentheses. If * {@code this} has a fractional part, a decimal point is used. Zero is represented by "0" if the base is 36 or * less, or "(0)" otherwise. There are no leading zeroes before the decimal point (unless {@code this} is less than * 1, in which case there is exactly one zero) and no trailing zeroes after. Scientific notation is not used. If * {@code this} is negative, the result will contain a leading '-'. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code this} must have a terminating base-{@code base} expansion.</li> * <li>The result is a {@code String} representing a {@code Rational} in the manner previously described. See the * unit test and demo for further reference.</li> * </ul> * * @param base the base of the output digits * @return a {@code String} representation of {@code this} in base {@code base} */ public @NotNull String toStringBase(@NotNull BigInteger base) { if (!hasTerminatingBaseExpansion(base)) throw new ArithmeticException(this + " has a non-terminating base-" + base + " expansion"); boolean smallBase = le(base, BigInteger.valueOf(36)); Pair<List<BigInteger>, Iterable<BigInteger>> digits = abs().digits(base); Function<BigInteger, String> digitFunction; if (smallBase) { digitFunction = i -> Character.toString(MathUtils.toDigit(i.intValueExact())); } else { digitFunction = i -> "(" + i + ")"; } String beforeDecimal; if (digits.a.isEmpty()) { beforeDecimal = smallBase ? "0" : "(0)"; } else { beforeDecimal = concatStrings(map(digitFunction, digits.a)); } String result; if (isEmpty(digits.b)) { result = beforeDecimal; } else { String afterDecimal = concatStrings(map(digitFunction, digits.b)); result = beforeDecimal + "." + afterDecimal; } return signum() == -1 ? "-" + result : result; } /** * Converts {@code this} to a {@code String} in any base greater than 1, rounding to {@code scale} digits after the * decimal point. A scale of 0 indicates rounding to an integer, and a negative scale indicates rounding to a * positive power of {@code base}. All rounding is done towards 0 (truncation), so that the displayed digits are * unaltered. If the result is an approximation (that is, not all digits are displayed) and the scale is positive, * an ellipsis ("...") is appended. If the base is 36 or less, the digits are '0' through '9' followed by 'A' * through 'Z'. If the base is greater than 36, the digits are written in decimal and each digit is surrounded by * parentheses. If {@code this} has a fractional part, a decimal point is used. Zero is represented by "0" if the * base is 36 or less, or "(0)" otherwise. There are no leading zeroes before the decimal point (unless * {@code this} is less than 1, in which case there is exactly one zero) and no trailing zeroes after (unless an * ellipsis is present, in which case there may be any number of trailing zeroes). Scientific notation is not used. * If {@code this} is negative, the result will contain a leading '-'. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code base} must be at least 2.</li> * <li>{@code scale} may be any {@code int}.</li> * <li>The result is a {@code String} representing a {@code Rational} in the manner previously described. See the * unit test and demo for further reference.</li> * </ul> * * @param base the base of the output digits * @param scale the maximum number of digits after the decimal point in the result. If {@code this} has a * terminating base-{@code base} expansion, the actual number of digits after the decimal point may be * less. * @return a {@code String} representation of {@code this} in base {@code base} */ public @NotNull String toStringBase(@NotNull BigInteger base, int scale) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); BigInteger power = scale >= 0 ? base.pow(scale) : base.pow(-scale); Rational scaled = scale >= 0 ? multiply(power) : divide(power); boolean ellipsis = scale > 0 && !scaled.isInteger(); Rational rounded = of(scaled.bigIntegerValue(RoundingMode.DOWN)); rounded = scale >= 0 ? rounded.divide(power) : rounded.multiply(power); String result = rounded.toStringBase(base); if (ellipsis) { //pad with trailing zeroes if necessary int dotIndex = result.indexOf('.'); if (dotIndex == -1) { dotIndex = result.length(); result = result + "."; } if (le(base, BigInteger.valueOf(36))) { int missingZeroes = scale - result.length() + dotIndex + 1; result += replicate(missingZeroes, '0'); } else { int missingZeroes = scale; for (int i = dotIndex + 1; i < result.length(); i++) { if (result.charAt(i) == '(') missingZeroes } result += concatStrings(replicate(missingZeroes, "(0)")); } result += "..."; } return result; } /** * Converts a {@code String} written in some base to a {@code Rational}. If the base is 36 or less, the digits are * '0' through '9' followed by 'A' through 'Z'. If the base is greater than 36, the digits are written in decimal * and each digit is surrounded by parentheses (in this case, the {@code String} representing the digit cannot be * empty and no leading zeroes are allowed unless the digit is 0). The empty {@code String} represents 0. Leading * zeroes are permitted. If the {@code String} is invalid, an exception is thrown. * * <ul> * <li>{@code base} must be at least 2.</li> * <li>{@code s} must either be composed of the digits '0' through '9' and 'A' through 'Z', or a sequence of * non-negative decimal integers, each surrounded by parentheses. {@code s} may contain a single decimal point '.' * anywhere outside of parentheses. In any case there may be an optional leading '-'. {@code s} may also be empty, * but "-" is not permitted. Scientific notation is not accepted.</li> * <li>If {@code base} is between 2 and 36, {@code s} may only include the corresponding characters, the optional * '.', and the optional leading '-'. If {@code base} is greater than 36, {@code s} must be composed of decimal * integers surrounded by parentheses (with the optional leading '-'), each integer being non-negative and less * than {@code base}.</li> * <li>The result is non-null.</li> * </ul> * * @param base the base that the {@code s} is written in * @param s the input {@code String} * @return the {@code Rational} represented by {@code s} */ public static @NotNull Rational fromStringBase(@NotNull BigInteger base, @NotNull String s) { if (lt(base, BigInteger.valueOf(2))) throw new IllegalArgumentException("base must be at least 2"); if (s.isEmpty()) return ZERO; try { if (s.equals("-") || s.equals(".") || s.equals("-.")) throw new IllegalArgumentException("invalid String"); boolean negative = head(s) == '-'; if (negative) s = tail(s); boolean smallBase = le(base, BigInteger.valueOf(36)); Function<String, List<BigInteger>> undigitFunction; if (smallBase) { undigitFunction = t -> toList(map(c -> BigInteger.valueOf(MathUtils.fromDigit(c)), fromString(t))); } else { undigitFunction = t -> { if (t.isEmpty()) return Collections.emptyList(); if (head(t) != '(' || last(t) != ')' || t.contains("()")) throw new IllegalArgumentException("invalid String"); t = tail(init(t)); return toList( map( u -> { Optional<BigInteger> oi = Readers.readBigInteger(u); if (!oi.isPresent()) throw new IllegalArgumentException("improperly-formatted digit"); return oi.get(); }, Arrays.asList(t.split("\\)\\(")) ) ); }; } Rational result; int dotIndex = s.indexOf("."); if (dotIndex == -1) { result = of(MathUtils.fromBigEndianDigits(base, undigitFunction.apply(s))); } else { List<BigInteger> beforeDecimal = undigitFunction.apply(take(dotIndex, s)); List<BigInteger> afterDecimal = undigitFunction.apply(drop(dotIndex + 1, s)); result = fromPositionalNotation( base, beforeDecimal, afterDecimal, Collections.singletonList(BigInteger.ZERO) ); } return negative ? result.negate() : result; } catch (StringIndexOutOfBoundsException e) { throw new IllegalArgumentException(e); } } /** * Multiplies a {@code List} of {@code Rational}s by some positive constant to yield a {@code List} of * {@code BigInteger}s with no common factor. This gives a canonical representation of {@code Rational} lists * considered equivalent under multiplication by positive {@code Rational}s. * * <ul> * <li>{@code xs} cannot contain any nulls.</li> * <li>The result is a {@code List} of {@code BigInteger}s whose GCD is 0 or 1.</li> * </ul> * * @param xs the {@code List} of {@code Rational}s * @return a canonical representation of {@code xs} as a {@code List} of {@code BigInteger}s */ @SuppressWarnings("ConstantConditions") public static @NotNull List<BigInteger> cancelDenominators(@NotNull List<Rational> xs) { BigInteger lcm = foldl(MathUtils::lcm, BigInteger.ONE, map(Rational::getDenominator, xs)); Iterable<BigInteger> canceled = map(x -> x.multiply(lcm).getNumerator(), xs); BigInteger gcd = foldl(BigInteger::gcd, BigInteger.ZERO, canceled); return toList(gcd.equals(BigInteger.ZERO) ? canceled : map(x -> x.divide(gcd), canceled)); } /** * Determines whether {@code this} is equal to {@code that}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>{@code that} may be any {@code Object}.</li> * <li>The result may be either {@code boolean}.</li> * </ul> * * @param that The {@code Object} to be compared with {@code this} * @return {@code this}={@code that} */ @Override public boolean equals(Object that) { if (this == that) return true; if (that == null || Rational.class != that.getClass()) return false; Rational r = (Rational) that; return denominator.equals(r.denominator) && numerator.equals(r.numerator); } /** * Calculates the hash code of {@code this}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>(conjecture) The result may be any {@code int}.</li> * </ul> * * @return {@code this}'s hash code. */ @Override public int hashCode() { return 31 * numerator.hashCode() + denominator.hashCode(); } @Override public int compareTo(@NotNull Rational that) { if (this == that) return 0; int thisSign = signum(); int thatSign = that.signum(); if (thisSign > thatSign) return 1; if (thisSign < thatSign) return -1; return numerator.multiply(that.denominator).compareTo(that.numerator.multiply(denominator)); } /** * Creates a {@code Rational} from a {@code String}. Valid {@code String}s are of the form {@code a.toString()} or * {@code a.toString() + "/" + b.toString()}, where {@code a} and {@code b} are some {@code BigInteger}s, * {@code b}{@literal >}0, and {@code a} and {@code b} are coprime. If the {@code String} is invalid, the method * returns {@code Optional.empty()} without throwing an exception; this aids composability. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result may contain any {@code Rational}, or be empty.</li> * </ul> * * @param s a {@code String} representation of a {@code Rational} * @return the {@code Rational} represented by {@code s}, or an empty {@code Optional} if {@code s} is invalid */ public static @NotNull Optional<Rational> read(@NotNull String s) { if (s.isEmpty()) return Optional.empty(); int slashIndex = s.indexOf("/"); if (slashIndex == -1) { Optional<BigInteger> n = Readers.readBigInteger(s); return n.map(Rational::of); } else { Optional<BigInteger> numerator = Readers.readBigInteger(s.substring(0, slashIndex)); if (!numerator.isPresent()) return Optional.empty(); Optional<BigInteger> denominator = Readers.readBigInteger(s.substring(slashIndex + 1)); if (!denominator.isPresent() || denominator.get().equals(BigInteger.ZERO)) return Optional.empty(); Rational candidate = of(numerator.get(), denominator.get()); return candidate.toString().equals(s) ? Optional.of(candidate) : Optional.<Rational>empty(); } } /** * Finds the first occurrence of a {@code Rational} in a {@code String}. Returns the {@code Rational} and the index * at which it was found. Returns an empty {@code Optional} if no {@code Rational} is found. Only {@code String}s * which could have been emitted by {@link Rational#toString} are recognized. The longest possible {@code Rational} * is parsed. * * <ul> * <li>{@code s} must be non-null.</li> * <li>The result is non-null. If it is non-empty, then neither of the {@code Pair}'s components is null, and the * second component is non-negative.</li> * </ul> * * @param s the input {@code String} * @return the first {@code Rational} found in {@code s}, and the index at which it was found */ public static @NotNull Optional<Pair<Rational, Integer>> findIn(@NotNull String s) { return Readers.genericFindIn(Rational::read, "-/0123456789").apply(s); } /** * Creates a {@code String} representation of {@code this}. * * <ul> * <li>{@code this} may be any {@code Rational}.</li> * <li>The result is a {@code String} in one of two forms: {@code a.toString()} or {@code a.toString() + "/" + * b.toString()}, where {@code a} and {@code b} are some {@code BigInteger}s such that {@code b} is positive and * {@code a} and {@code b} have no positive common factors greater than 1.</li> * </ul> * * @return a {@code String} representation of {@code this} */ public @NotNull String toString() { if (denominator.equals(BigInteger.ONE)) { return numerator.toString(); } else { return numerator.toString() + "/" + denominator.toString(); } } /** * Ensures that {@code this} is valid. Must return true for any {@code Rational} used outside this class. */ public void validate() { assertEquals(toString(), numerator.gcd(denominator), BigInteger.ONE); assertEquals(toString(), denominator.signum(), 1); if (equals(ZERO)) assertTrue(toString(), this == ZERO); if (equals(ONE)) assertTrue(toString(), this == ONE); } }
package org.subethamail.smtp.server; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.subethamail.smtp.i.MessageListener; /** * Main SMTPServer class. This class starts opens a ServerSocket and * when a new connection comes in, it attaches that to a new * instance of the ConnectionHandler class. * * The ConnectionHandler then parses the incoming SMTP stream and * hands off the processing to the CommandHandler which will execute * the appropriate SMTP command class. * * This class also manages a watchdog thread which will timeout * stale connections. * * In order to instantiate a new server, one must pass in a Set of * MessageListeners. These listener classes are executed during the * RCPT TO: (MessageListener.accept()) phase and after the CRLF.CRLF * data phase (MessageListener.deliver()). This way, the server itself * is not responsible for dealing with the actual SMTP data and that * aspect is essentially handed off to other tools to deal with. * This is unlike every other Java SMTP server on the net. * * @author Jon Stevens * @author Ian McFarland &lt;ian@neo.com&gt; */ @SuppressWarnings("serial") public class SMTPServer implements Runnable { private static Log log = LogFactory.getLog(SMTPServer.class); private String hostName; private InetAddress bindAddress; private int port; private Collection<MessageListener> listeners; private CommandHandler commandHandler; private ServerSocket serverSocket; private boolean go = false; private Thread serverThread; private Thread watchdogThread; private ThreadGroup connectionHanderGroup; /** * set a hard limit on the maximum number of connections this server will accept * once we reach this limit, the server will gracefully reject new connections. * Default is 1000. */ private int maxConnections = 1000; /** * The timeout for waiting for data on a connection is one minute: 1000 * 60 * 1 */ private int connectionTimeout = 1000 * 60 * 1; /** * The maximal number of recipients that this server accepts per message delivery request. */ private int maxRecipients = 1000; /** * The main SMTPServer constructor. * * @param hostname * @param bindAddress * @param port * @param listeners * @throws UnknownHostException */ public SMTPServer(String hostname, InetAddress bindAddress, int port, Collection<MessageListener> listeners) throws UnknownHostException { this.hostName = hostname; this.bindAddress = bindAddress; this.port = port; this.listeners = listeners; this.commandHandler = new CommandHandler(); this.connectionHanderGroup = new ThreadGroup(SMTPServer.class.getName() + " ConnectionHandler Group"); } /** * Call this method to get things rolling after instantiating * the SMTPServer. */ public void start() { if (this.serverThread != null) throw new IllegalStateException("SMTPServer already started"); this.serverThread = new Thread(this, SMTPServer.class.getName()); this.serverThread.start(); this.watchdogThread = new Watchdog(this); this.watchdogThread.start(); } /** * Shut things down gracefully. */ public void stop() { this.go = false; this.serverThread = null; this.watchdogThread = null; // force a socket close for good measure try { if (this.serverSocket != null && this.serverSocket.isBound() && !this.serverSocket.isClosed()) this.serverSocket.close(); } catch (IOException e) { } } /** * This method is called by this thread when it starts up. */ public void run() { try { if (this.bindAddress == null) this.serverSocket = new ServerSocket(this.port, 50); else this.serverSocket = new ServerSocket(this.port, 50, this.bindAddress); } catch (Exception e) { throw new RuntimeException(e); } this.go = true; while (this.go) { try { ConnectionHandler connectionHandler = new ConnectionHandler(this, serverSocket.accept()); connectionHandler.start(); } catch (IOException ioe) { // Avoid this exception when shutting down. // 20:34:50,624 ERROR [STDERR] at java.net.PlainSocketImpl.socketAccept(Native Method) // 20:34:50,624 ERROR [STDERR] at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:384) // 20:34:50,624 ERROR [STDERR] at java.net.ServerSocket.implAccept(ServerSocket.java:450) // 20:34:50,624 ERROR [STDERR] at java.net.ServerSocket.accept(ServerSocket.java:421) // 20:34:50,624 ERROR [STDERR] at org.subethamail.smtp2.SMTPServer.run(SMTPServer.java:92) // 20:34:50,624 ERROR [STDERR] at java.lang.Thread.run(Thread.java:613) if (this.go) { log.error(ioe.toString()); } } } try { if (this.serverSocket != null && this.serverSocket.isBound() && !this.serverSocket.isClosed()) this.serverSocket.close(); log.info("SMTP Server socket shut down."); } catch (IOException e) { log.error("Failed to close server socket.", e); } } public String getHostName() { return this.hostName; } public String getVersion() { return "1.0"; } public String getName() { return "SubEthaMail Server"; } public String getNameVersion() { return getName() + " v" + getVersion(); } /** * The Listeners are what the SMTPServer delivers to. */ public Collection<MessageListener> getListeners() { return this.listeners; } /** * The CommandHandler manages handling the SMTP commands * such as QUIT, MAIL, RCPT, DATA, etc. * * @return An instance of CommandHandler */ public CommandHandler getCommandHandler() { return this.commandHandler; } protected ThreadGroup getConnectionGroup() { return this.connectionHanderGroup; } public int getNumberOfConnections() { return this.connectionHanderGroup.activeCount(); } public boolean hasTooManyConnections() { return (getNumberOfConnections() >= maxConnections); } public int getMaxConnections() { return this.maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } public int getConnectionTimeout() { return this.connectionTimeout; } public void setConnectionTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; } public int getMaxRecipients() { return this.maxRecipients; } public void setMaxRecipients(int maxRecipients) { this.maxRecipients = maxRecipients; } /** * A watchdog thread that makes sure that * connections don't go stale. It prevents * someone from opening up MAX_CONNECTIONS to * the server and holding onto them for more than * 1 minute. */ private class Watchdog extends Thread { private SMTPServer server; private Thread[] groupThreads = new Thread[maxConnections]; private boolean run = true; public Watchdog(SMTPServer server) { super(Watchdog.class.getName()); this.server = server; setPriority(Thread.MAX_PRIORITY / 3); } public void quit() { this.run = false; } public void run() { while (this.run) { ThreadGroup connectionGroup = this.server.getConnectionGroup(); connectionGroup.enumerate(this.groupThreads); for (int i=0; i<connectionGroup.activeCount(); i++) { ConnectionHandler aThread = ((ConnectionHandler)this.groupThreads[i]); if (aThread != null) { // one minute timeout long lastActiveTime = aThread.getLastActiveTime() + (this.server.connectionTimeout); if (lastActiveTime < System.currentTimeMillis()) { try { aThread.timeout(); } catch (IOException ioe) { log.debug("Lost connection to client during timeout"); } } } } try { // go to sleep for 10 seconds. sleep(1000 * 10); } catch (InterruptedException e) { // ignore } } } } }
package net.darkhax.ess; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; public class ESSHelper { /** * The current version of the library. Follows a Major-Release-Build structure. The major * number points to the current iteration of the project. The release number points to the * current release of the project. The build number refers to the current build of the * project and is handled by the build server. */ public static final String VERSION = "1.0.0"; /** * Attempts to read a DataCompound from the passed filepath string. See * {@link #readCompound(File)} for more information. * * @param file A string representation of the filepath to read from. * @return DataCompound The data that was read from the file. */ public static DataCompound readCompound (String file) { return readCompound(new File(file)); } /** * Attempts to read a DataCompound from the passed file. This will use an * InflaterInputStream to read the compressed data from * {@link #writeCompound(DataCompound, File)}. * * @param file The file to read data from. * @return DataCompound The data that was read from the file. */ public static DataCompound readCompound (File file) { try (FileInputStream fileStream = new FileInputStream(file); ObjectInputStream objectStream = new ObjectInputStream(new InflaterInputStream(fileStream));) { return (DataCompound) objectStream.readObject(); } catch (IOException | ClassNotFoundException exception) { exception.printStackTrace(); } return null; } /** * Writes the passed DataCompound to the specified file location. See * {@link #writeCompound(DataCompound, File)} for more specifics. * * @param data The DataCompound to write to the file. * @param file A String representation of the filepath to safe the file at. */ public static void writeCompound (DataCompound data, String file) { writeCompound(data, new File(file)); } /** * Writes the passed DataCompound to the specified file location. Makes use of * DeflaterOutputStream to compress the data. All data is forcefully compressed. * * @param data the DataCompound to write to the file. * @param file The File to write the data to. */ public static void writeCompound (DataCompound data, File file) { try (FileOutputStream fileStream = new FileOutputStream(file); ObjectOutputStream objectStream = new ObjectOutputStream(new DeflaterOutputStream(fileStream))) { objectStream.writeObject(data); } catch (final IOException exception) { exception.printStackTrace(); } } }
package net.woogie.demomod; import java.awt.Color; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.EnumCreatureType; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionAbsorption; import net.minecraft.potion.PotionAttackDamage; import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionHealth; import net.minecraft.potion.PotionHealthBoost; import net.minecraft.util.ResourceLocation; import net.minecraft.world.biome.BiomeGenBase.SpawnListEntry; import net.minecraftforge.common.BiomeManager.BiomeType; import net.woogie.demomod.entity.hostile.DemoEntityHostile; import net.woogie.demomod.entity.tameable.DemoEntityTameable; public class Config { // Don't change these unless you know what you are doing public static final String MODID = "demomod"; public static final String MODNAME = "Demo Mod"; public static final String VERSION = "1.0"; // Changing the name can have unintended consequences public static final String toolMaterialName = "demoToolMaterial"; // Level of the tool needed to harvest the material (0-3). Higher is harder // Examples: // wood: 0 // stone: 1 // iron: 2 // diamond: 3 // gold: 0 public static final int toolMaterialHarvestLevel = 3; // Durability of the material. Higher is more durable // Examples: // wood: 59 // stone: 131 // iron: 250 // diamond: 1561 // gold: 32 public static final int toolMaterialDurability = 1000; // Mining speed (how much faster is it to use a tool of this material than // to use your hands // Examples: // wood: 2.0F // stone: 4.0F // iron: 6.0F // diamond: 8.0F // gold: 12.0F public static final float toolMaterialMiningSpeed = 15.0F; // DamageVsEntitis is used to calculate the damage an entity takes if you // hit it with a tool/sword of this material. This value defines the basic // damage to which different values are added, depending on the type of // tool. For example, a sword causes 4 more damage this. If you want to // create a sword which adds 10 damage to your normal damage, the value in // the ToolMaterial needs to be 6.0F. The value can be below zero. // Examples: // wood: 0.0F // stone: 1.0F // iron: 2.0F // diamond: 3.0F // gold: 0.0F public static final float toolMaterialDamageVsEnitities = 4.0F; // Enchantablity of the material. This is complicated so // Wood: 15 // Stone: 5 // Iron: 14 // Diamond: 10 // Gold: 22 public static final int toolMaterialEnchantability = 30; // Changing the name can have unintended consequences public static final String armorMaterialName = "demoArmorMaterial"; public static final String armorMaterialTextureName = MODID + ":" + armorMaterialName; // Durability (See comment for toolMaterialDurability) public static final int armorMaterialDurability = 1000; // Enchantability (See comment for toolMaterialEnchantability) public static final int armorMaterialEnchantability = 30; // Damage reduction for each piece of armor public static final int armorMaterialDamageReductionHelmet = 3; public static final int armorMaterialDamageReductionChestplate = 8; public static final int armorMaterialDamageReductionLeggings = 6; public static final int armorMaterialDamageReductionBoots = 3; // Don't change this public static final int[] armorMaterialDamageReduction = new int[] { armorMaterialDamageReductionHelmet, armorMaterialDamageReductionChestplate, armorMaterialDamageReductionLeggings, armorMaterialDamageReductionBoots }; // Changing the name can have unintended consequences public static final String itemName = "demoItem"; // Max stack size in inventory public static final int itemMaxStackSize = 64; // Don't change this. Recipes are defined below public static Object[] itemRecipe = null; // Experience gained for this item public static final float itemExperience = 1.0F; // Changing the name can have unintended consequences public static final String blockName = "demoBlock"; // The block's base material public static final Material blockParentMaterial = Material.rock; // The amount of light the block emits. If it is 0.0F, the block will not // emit any light public static final float blockLightLevel = 1.0F; // The blocks hardness. // Examples: // stone: 1.5F // obsidian: 50.0F public static final float blockHardness = 10.0F; // The blocks resistance to explosions // Examples // stone:10.0F // obsidian:2000.0F public static final float blockResistance = 15.0F; // you probably don't want to change this public static final String blockMineTool = Config.MODID + "." + Config.pickaxeName; // Level needed to harvest the block // Examples: // wood: 0 // stone: 1 // iron: 2 // diamond: 3 // gold: 0 public static final int blockMineLevel = 1; // Maximum number of Demo Items the block will drop when mined public static final int blockDropMax = 7; // Minimum number of Demo Items the block will drop when mined public static final int blockDropMin = 2; // If the block is the multi-ore, the extra type of item it will drop public static final Item blockMultiDropItem = Items.gold_nugget; // Maximum number of extra items the block will drop when mined public static final int blockMultiDropMax = 7; // Minimum number of extra items the block will drop when mined public static final int blockMultiDropMin = 2; // Rarely, the multi ore will drop a bonus item // What is the bonus item? public static final Item blockMultiDropBonusItem = Items.diamond; // What is the chance it will drop the bonus item? public static final float blockMultiDropBonusChance = 0.1F; // Changing the name can have unintended consequences public static final String blockOreName = "demoBlockOre"; public static final int blockOreChancesToSpawn = 20; public static final int blockOreMinHeight = 0; public static final int blockOreMaxHeight = 64; // Changing the name can have unintended consequences public static final String blockMultiOreName = "demoBlockMultiOre"; public static final int blockMultiOreChancesToSpawn = 10; public static final int blockMultiOreMinHeight = 0; public static final int blockMultiOreMaxHeight = 16; // Changing the name can have unintended consequences public static final String swordName = "demoSword"; // Max stack size in inventory public static final int swordMaxStackSize = 1; // If this is true, the sword will summon lightning when it hits an entity // or player public static final boolean swordSummonsLightning = true; // Add potion effects to the sword. When hit by the sword, the opponent will // also have the potion applied. Add as many potions as you want, but they // must be comma separated. // PotionEffect(potionId, effectDuration, effectAmplifier) // These are the valid potion IDs: // Potion.moveSpeed.id // Potion.moveSlowdown.id // Potion.digSpeed.id // Potion.digSlowdown.id // Potion.damageBoost.id // Potion.heal.id // Potion.harm.id // Potion.jump.id // Potion.confusion.id // Potion.regeneration.id // Potion.resistance.id // Potion.fireResistance.id // Potion.waterBreathing.id // Potion.invisibility.id // Potion.blindness.id // Potion.nightVision.id // Potion.hunger.id // Potion.weakness.id // Potion.poison.id // Potion.wither.id // Potion.healthBoost.id // Potion.absorption.id // Potion.saturation.id // Effect duration is the time, in seconds that the effect lasts // Effect amplifier is the level of the effect // More documentation about effect can be found here: public static final PotionEffect[] swordEffects = { new PotionEffect(Potion.blindness.id, 1200, 1), new PotionEffect(Potion.poison.jump.id, 600, 0), new PotionEffect(Potion.weakness.id, 200, 1) }; // Add enchantments to the sword // Enchantment.fireProtection // Enchantment.featherFalling // Enchantment.blastProtection // Enchantment.projectileProtection // Enchantment.respiration // Enchantment.aquaAffinity // Enchantment.thorns // Enchantment.depthStrider // Enchantment.sharpness // Enchantment.smite // Enchantment.baneOfArthropods // Enchantment.knockback // Enchantment.fireAspect // Enchantment.looting // Enchantment.efficiency // Enchantment.silkTouch // Enchantment.unbreaking // Enchantment.fortune // Enchantment.power // Enchantment.punch // Enchantment.flame // Enchantment.infinity // Enchantment.luckOfTheSea // Enchantment.lure // Note that not all enchantments are appropriate for all item types, so // some might not have the desired effect. // More documentation about enchantments can be found here: // http://minecraft.gamepedia.com/Enchanting#Enchantments public static final Enchantment[] swordEnchantments = { Enchantment.sharpness, Enchantment.fireAspect }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] swordEnchantmentLevels = { 3, 3 }; // Don't change this. Recipes are defined below public static Object[] swordRecipe = null; // Changing the name can have unintended consequences public static final String giantSwordName = "demoGiantSword"; // Max stack size in inventory public static final int giantSwordMaxStackSize = 1; // If this is true, the sword will summon lightning when it hits an entity // or player public static final boolean giantSwordSummonsLightning = true; // Add effects to your sword. See swordEffects above for options public static final PotionEffect[] giantSwordEffects = { new PotionEffect(Potion.blindness.id, 1200, 1), new PotionEffect(Potion.poison.jump.id, 600, 0), new PotionEffect(Potion.weakness.id, 200, 1) }; // Add enchantments to your sword. See swordEnchantments above for options public static final Enchantment[] giantSwordEnchantments = { Enchantment.sharpness, Enchantment.fireAspect }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] giantSwordEnchantmentLevels = { 3, 3 }; // Changing the name can have unintended consequences public static final String pickaxeName = "demoPickaxe"; // Max stack size in inventory public static final int pickaxeMaxStackSize = 1; // If this is true, the pickaxe will summon lightning when it hits an entity // or player public static final boolean pickaxeSummonsLightning = true; // Add effects to your pickaxe. See swordEffects above for options public static final PotionEffect[] pickaxeEffects = { new PotionEffect(Potion.blindness.id, 1200, 1), new PotionEffect(Potion.poison.jump.id, 600, 0), new PotionEffect(Potion.weakness.id, 200, 1) }; // Add enchantments to your pickaxe. See swordEnchantments above for options public static final Enchantment[] pickaxeEnchantments = { Enchantment.efficiency, Enchantment.fortune }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] pickaxeEnchantmentLevels = { 3, 3 }; // Don't change this. Recipes are defined below public static Object[] pickaxeRecipe = null; // Changing the name can have unintended consequences public static final String hoeName = "demoHoe"; // Max stack size in inventory public static final int hoeMaxStackSize = 1; // Add enchantments to your hoe. See swordEnchantments above for options public static final Enchantment[] hoeEnchantments = { Enchantment.unbreaking }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] hoeEnchantmentLevels = { 3 }; public static Object[] hoeRecipe = null; // Changing the name can have unintended consequences public static final String shovelName = "demoShovel"; // Max stack size in inventory public static final int shovelMaxStackSize = 1; // Add enchantments to your shovel. See swordEnchantments above for options public static final Enchantment[] shovelEnchantments = { Enchantment.efficiency, Enchantment.silkTouch }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] shovelEnchantmentLevels = { 3, 3 }; // Don't change this. Recipes are defined below public static Object[] shovelRecipe = null; // Changing the name can have unintended consequences public static final String axeName = "demoAxe"; // Max stack size in inventory public static final int axeMaxStackSize = 1; // Add enchantments to your axe. See swordEnchantments above for options public static final Enchantment[] axeEnchantments = { Enchantment.efficiency, Enchantment.silkTouch }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] axeEnchantmentLevels = { 3, 3 }; // Don't change this. Recipes are defined below public static Object[] axeRecipe = null; // Changing the name can have unintended consequences public static final String bowName = "demoBow"; // Max stack size in inventory public static final int bowMaxStackSize = 1; // Add enchantments to your bow. See swordEnchantments above for options public static final Enchantment[] bowEnchantments = { Enchantment.flame, Enchantment.infinity }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] bowEnchantmentLevels = { 3, 3 }; // Don't change this. Recipes are defined below public static Object[] bowRecipe = null; // Changing the name can have unintended consequences public static final String armorName = "demoArmor"; // Changing the name can have unintended consequences public static final String helmetName = "demoHelmet"; // Max stack size in inventory public static final int helmetMaxStackSize = 1; // Add enchantments to your helmet. See swordEnchantments above for options public static final Enchantment[] helmetEnchantments = { Enchantment.thorns }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] helmetEnchantmentLevels = { 3 }; // Add effects to your helmet. See swordEffects above for options public static final PotionEffect[] helmetEffects = { new PotionEffect(Potion.waterBreathing.id, 200, 0) }; // Don't change this. Recipes are defined below public static Object[] helmetRecipe = null; // Changing the name can have unintended consequences public static final String chestplateName = "demoChestplate"; // Max stack size in inventory public static final int chestplateMaxStackSize = 1; // Add enchantments to your chestplate. See swordEnchantments above for // options public static final Enchantment[] chestplateEnchantments = { Enchantment.thorns }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] chestplateEnchantmentLevels = { 3 }; // Add effects to your chestplate. See swordEffects above for options public static final PotionEffect[] chestplateEffects = { new PotionEffect(Potion.regeneration.id, 200, 0) }; // Don't change this. Recipes are defined below public static Object[] chestplateRecipe = null; // Changing the name can have unintended consequences public static final String leggingsName = "demoLeggings"; // Max stack size in inventory public static final int leggingsMaxStackSize = 1; // Add enchantments to your leggings. See swordEnchantments above for // options public static final Enchantment[] leggingsEnchantments = { Enchantment.thorns }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] leggingsEnchantmentLevels = { 3 }; // Add effects to your leggings. See swordEffects above for options public static final PotionEffect[] leggingsEffects = { new PotionEffect(Potion.moveSpeed.id, 1200, 0) }; // Don't change this. Recipes are defined below public static Object[] leggingsRecipe = null; // Changing the name can have unintended consequences public static final String bootsName = "demoBoots"; // Max stack size in inventory public static final int bootsMaxStackSize = 1; // Add enchantments to your boots. See swordEnchantments above for options public static final Enchantment[] bootsEnchantments = { Enchantment.thorns }; // For each enchantment listed above, give the enchantment level. Make sure // you have the same number of enchantment // levels as enchantments, or your mod could crash public static final int[] bootsEnchantmentLevels = { 3 }; // Add effects to your boots. See swordEffects above for options public static final PotionEffect[] bootsEffects = { new PotionEffect(Potion.jump.id, 600, 0) }; // Don't change this. Recipes are defined below public static Object[] bootsRecipe = null; // Changing the name can have unintended consequences public static final String foodName = "demoFood"; // Max stack size in inventory public static final int foodMaxStackSize = 64; public static final int foodHealAmount = 10; public static final float foodSaturationModifier = 2F; public static final boolean foodWolvesFavorite = false; public static final PotionEffect[] foodEffects = { new PotionEffect(Potion.moveSpeed.id, 1200, 1), new PotionEffect(Potion.jump.id, 600, 0), new PotionEffect(Potion.regeneration.id, 200, 1) }; // Changing the name can have unintended consequences public static final String seedName = "demoSeed"; // Changing the name can have unintended consequences public static final String blockCropName = "demoBlockCrop"; public static final String blockBushName = "demoBlockBush"; // Changing the name can have unintended consequences public static final String biomeIdConfigName = "demo_biome_id"; // Don't change any of these public static final int defaultBiomeId = -1; public static final int minBiomeId = 10; public static final int maxBiomeId = 1000; public static int biomeId = defaultBiomeId; // Set the Biome name public static final String biomeName = "Demo Biome"; // Set the top block for your biome public static final Block biomeTopBlock = Blocks.grass; // The weight given to the biome. The higher the number, the more the biome // will appear in your world. The default is 10, but you probably want it // much higher so you don't have to spend too much time searching for it public static final int biomeWeight = 1000; // Set the biome type. Valid values are // BiomeType.DESERT // BiomeType.WARM // BiomeType.COOL // BiomeType.ICY public static final BiomeType biomeType = BiomeType.COOL; // Weight of you world generator. Smaller number is better. You probably // want to keep this as 0 public static final int biomeWorldGenerationWeight = 0; // How many of the different decorations do you want in your biome? (A chunk // is 16x16 blocks) public static final int biomeDemoBushesPerChunk = 50; public static final int biomeWaterlilyPerChunk = 0; public static final int biomeTreesPerChunk = 10; public static final int biomeFlowersPerChunk = 0; public static final int biomeGrassPerChunk = 0; public static final int biomeDeadBushPerChunk = 0; public static final int biomeMushroomsPerChunk = 0; public static final int biomeReedsPerChunk = 0; public static final int biomeCactiPerChunk = 0; public static final int biomeSandPerChunk = 0; public static final int biomeSandPerChunk2 = 0; public static final int biomeClayPerChunk = 0; public static final int biomeBigMushroomsPerChunk = 15; // Set to true if you want to generate lakes, false if you do not public static final boolean biomeGenerateLakes = true; // default biomeMinHeight = 0.1 public static final float biomeMinHeight = 0.1F; // default biomeMaxHeight = 0.2F public static final float biomeMaxHeight = 0.2F; // set the temperature for your biome // less than 0.15F will have snow // 1.5F to 0.95F will have rain // greater than 0.95F will have neither public static final float biomeTemperature = 1.5F; // set how often it rains in your biome // 0.0F to 1.0F // 0.0F = no rain // 1.0F = frequent rain public static final float biomeRainfall = 0.2F; // Changing the name can have unintended consequences public static final String entityHostileName = "demoHostile"; public static final int entityHostileId = 1; public static final EnumCreatureType entityHostileType = EnumCreatureType.MONSTER; public static final float entityHostileShadowSize = 0.6F; public static final int entityHostileSpawnColorBase = (new Color(0, 0, 0)).getRGB(); public static final int entityHostileSpawnColorSpots = (new Color(255, 0, 0)).getRGB(); public static final int entityHostileExperience = 5; public static final double entityHostileMaxHealth = 35.0D; public static final double entityHostileFollowRange = 32.0D; public static final double entityHostileKnockbackResistance = 0.0D; public static final double entityHostileMovementSpeed = 0.5D; public static final double entityHostileAttackDamage = 7.0D; public static final boolean entityHostileCanSwim = true; public static final boolean entityHostileAvoidDemoEntityTameable = true; public static final float entityHostileAvoidDemoEntityTameableRange = 6.0F; public static final double entityHostileAvoidDemoEntityTameableFarSpeed = 1.0D; public static final double entityHostileAvoidDemoEntityTameableNearSpeed = 1.2D; public static final double entityHostileAIAttackOnCollideSpeed = 1.0D; public static final double entityHostileAIWanderSpeed = 0.8D; public static final float entityHostileAIWatchClosestDistance = 8.0F; public static final int entityHostileBaseDrops = 3; public static final int entityHostileDropBonus = 2; public static final int entityHostileSpawnChance = 50; public static final int entityHostileSpawnMin = 4; public static final int entityHostileSpawnMax = 8; // Changing the name can have unintended consequences public static final String entityTameableName = "demoTameable"; public static final int entityTameableId = 2; public static final EnumCreatureType entityTameableType = EnumCreatureType.CREATURE; public static final float entityTameableShadowSize = 0.3F; public static final int entityTameableSpawnColorBase = (new Color(255, 255, 255)).getRGB(); public static final int entityTameableSpawnColorSpots = (new Color(0, 0, 0)).getRGB(); public static final double entityTameableMovementSpeed = 0.5D; public static final double entityTameableAttackDamage = 7.0D; public static final int entityTameableExperience = 5; public static final double entityTameableMaxWildHealth = 9.0D; public static final double entityTameableMaxTamedHealth = 35.0D; public static final double entityTameableAIAttackOnCollideSpeed = 1.0D; public static final float entityTameableAILeapAtTargetHeight = 0.4F; public static final double entityTameableAIFollowOwnerSpeed = 1.0D; public static final float entityTameableAIFollowOwnerMaxDistance = 10.0F; public static final float entityTameableAIFollowOwnerMinDistance = 2.0F; public static final double entityTameableAIMateMoveSpeed = 1.0D; public static final double entityTameableAIWanderSpeed = 1.0D; public static final float entityTameableAIBegDistance = 8.0F; public static final float entityTameableAIWatchClosestDistance = 8.0F; public static final int entityTameableSpawnChance = 100; public static final int entityTameableSpawnMin = 4; public static final int entityTameableSpawnMax = 8; // Changing the name can have unintended consequences public static final String entityBossName = "demoBoss"; public static final int entityBossId = 3; public static final EnumCreatureType entityBossType = EnumCreatureType.MONSTER; public static final float entityBossShadowSize = 0.6F; public static final int entityBossSpawnColorBase = (new Color(255, 0, 0)).getRGB(); public static final int entityBossSpawnColorSpots = (new Color(0, 0, 0)).getRGB(); public static final int entityBossExperience = 5; public static final double entityBossMaxHealth = 350.0D; public static final double entityBossFollowRange = 32.0D; public static final double entityBossKnockbackResistance = 1.0D; public static final double entityBossMovementSpeed = 0.5D; public static final double entityBossAttackDamage = 40.0D; public static final boolean entityBossCanSwim = true; public static final boolean entityBossAvoidDemoEntityTameable = true; public static final float entityBossAvoidDemoEntityTameableRange = 6.0F; public static final double entityBossAvoidDemoEntityTameableFarSpeed = 1.0D; public static final double entityBossAvoidDemoEntityTameableNearSpeed = 1.2D; public static final double entityBossAIAttackOnCollideSpeed = 1.0D; public static final double entityBossAIWanderSpeed = 0.8D; public static final float entityBossAIWatchClosestDistance = 8.0F; public static final int entityBossSpawnChance = 20; public static final int entityBossSpawnMin = 1; public static final int entityBossSpawnMax = 1; // All the recipes are defined here public static void initRecipes() { swordRecipe = new Object[] { " X ", " X ", " S ", 'S', Items.stick, 'X', DemoMod.demoItem }; pickaxeRecipe = new Object[] { "XXX", " S ", " S ", 'S', Items.stick, 'X', DemoMod.demoItem }; hoeRecipe = new Object[] { "XX ", " S ", " S ", 'S', Items.stick, 'X', DemoMod.demoItem }; shovelRecipe = new Object[] { " X ", " S ", " S ", 'S', Items.stick, 'X', DemoMod.demoItem }; axeRecipe = new Object[] { "XX ", "XS ", " S ", 'S', Items.stick, 'X', DemoMod.demoItem }; bowRecipe = new Object[] { " XS", "X S", " XS", 'S', Items.string, 'X', DemoMod.demoItem }; helmetRecipe = new Object[] { "XXX", "X X", 'X', DemoMod.demoItem }; chestplateRecipe = new Object[] { "X X", "XXX", "XXX", 'X', DemoMod.demoItem }; leggingsRecipe = new Object[] { "XXX", "X X", "X X", 'X', DemoMod.demoItem }; bootsRecipe = new Object[] { "X X", "X X", 'X', DemoMod.demoItem }; } }
package org.dada.core; import java.util.ArrayList; import java.util.Collection; import org.dada.slf4j.Logger; import org.dada.slf4j.LoggerFactory; /** * A Connector that performs a one-for-one pluggable transformation on Updates flowing through it. * @author jules * * @param <IV> * @param <OV> */ public class Transformer<IV, OV> extends Connector<IV, OV> { private static final Logger LOGGER = LoggerFactory.getLogger(Transformer.class); public interface Transform<IV, OV> { OV transform(IV value); } public interface Strategy<IV, OV> { Update<OV> insert(Update<IV> insertion); Update<OV> update(Update<IV> alteration); Update<OV> delete(Update<IV> deletion); } private final Strategy<IV, OV> strategy; public Transformer(Collection<View<OV>> views, Strategy<IV, OV> strategy) { super(views); this.strategy = strategy; } public Transformer(Collection<View<OV>> views, final Transform<IV, OV> transform) { super(views); this.strategy = new Strategy<IV, OV>() { @Override public Update<OV> insert(Update<IV> insertion) { return new Update<OV>(null, transform.transform(insertion.getNewValue())); } @Override public Update<OV> update(Update<IV> alteration) { return new Update<OV>( transform.transform(alteration.getOldValue()), transform.transform(alteration.getNewValue())); } @Override public Update<OV> delete(Update<IV> deletion) { return new Update<OV>(transform.transform(deletion.getOldValue()), null); } }; } @Override public void update(Collection<Update<IV>> insertions, Collection<Update<IV>> alterations, Collection<Update<IV>> deletions) { Collection<Update<OV>> i = new ArrayList<Update<OV>>(insertions.size()); for (Update<IV> insertion : insertions) i.add(strategy.insert(insertion)); Collection<Update<OV>> a = new ArrayList<Update<OV>>(alterations.size()); for (Update<IV> alteration : alterations) a.add(strategy.update(alteration)); Collection<Update<OV>> d = new ArrayList<Update<OV>>(deletions.size()); for (Update<IV> deletion : deletions) a.add(strategy.update(deletion)); for (View<OV> view : getViews()) { try { view.update(i, a, d); } catch (Throwable t) { LOGGER.error("problem updating View", t); } } } }
package org.jpmml.rexp; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.zip.GZIPInputStream; import com.google.common.io.ByteStreams; public class RExpParser { private RDataInput input = null; private List<RExp> referenceTable = new ArrayList<>(); public RExpParser(InputStream is) throws IOException { this.input = new XDRInput(init(new PushbackInputStream(is, 2))); } public RExp parse() throws IOException { int version = readInt(); if(version != 2){ throw new IllegalArgumentException(String.valueOf(version)); } int writerVersion = readInt(); int releaseVersion = readInt(); RExp result = readRExp(); try { readInt(); throw new IllegalStateException(); } catch(EOFException ee){ // Ignored } return result; } private RExp readRExp() throws IOException { int flags = readInt(); int type = SerializationUtil.decodeType(flags); switch(type){ case SExpTypes.SYMSXP: return readSymbol(); case SExpTypes.LISTSXP: return readPairList(flags); case SExpTypes.CLOSXP: return readClosure(flags); case SExpTypes.ENVSXP: return readEnvironment(flags); case SExpTypes.PROMSXP: return readPromise(flags); case SExpTypes.LANGSXP: return readFunctionCall(flags); case SExpTypes.CHARSXP: return readString(flags); case SExpTypes.LGLSXP: return readLogicalVector(flags); case SExpTypes.INTSXP: return readIntVector(flags); case SExpTypes.REALSXP: return readRealVector(flags); case SExpTypes.STRSXP: return readStringVector(flags); case SExpTypes.VECSXP: case SExpTypes.EXPRSXP: return readVector(flags); case SExpTypes.BCODESXP: return readBytecode(flags); case SExpTypes.EXTPTRSXP: return readExternalPointer(flags); case SExpTypes.RAWSXP: return readRaw(flags); case SExpTypes.S4SXP: return readS4Object(flags); case SerializationTypes.BASEENVSXP: return null; // XXX case SerializationTypes.EMPTYENVSXP: return null; // XXX case SerializationTypes.NAMESPACESXP: return readNamespace(); case SerializationTypes.BASENAMESPACESXP: return null; // XXX case SerializationTypes.MISSINGARGSXP: return null; // XXX case SerializationTypes.UNBOUNDVALUESXP: return null; // XXX case SerializationTypes.GLOBALENVSXP: return null; // XXX case SerializationTypes.NILVALUESXP: return null; case SerializationTypes.REFSXP: return readReference(flags); default: throw new UnsupportedOperationException(String.valueOf(type)); } } private RString readSymbol() throws IOException { RString symbol = (RString)readRExp(); if(symbol.getValue() == null){ symbol = RString.NA; } this.referenceTable.add(symbol); return symbol; } private RPair readPairList(int flags) throws IOException { RPair first = null; RPair last = null; while(true){ int type = SerializationUtil.decodeType(flags); if(type == SerializationTypes.NILVALUESXP){ break; } RPair attributes = readAttributes(flags); RExp tag = readTag(flags); RExp value = readRExp(); RPair pair = new RPair(tag, value, attributes); if(first == null){ first = pair; last = pair; } else { last.setNext(pair); last = pair; } flags = readInt(); } return first; } private RExp readClosure(int flags) throws IOException { RPair attributes = readAttributes(flags); RExp environment = readTag(flags); RPair parameters = (RPair)readRExp(); RExp body = readRExp(); return null; } private RExp readEnvironment(int flags) throws IOException { RExp rexp = null; readInt(); // "MUST register before filling in" this.referenceTable.add(rexp); // "Now fill it in" RExp parent = readRExp(); RPair frame = (RPair)readRExp(); RExp hashtab = readRExp(); RPair attributes = (RPair)readRExp(); return rexp; } private RExp readPromise(int flags) throws IOException { RPair attributes = readAttributes(flags); RExp environment = readTag(flags); RExp value = readRExp(); RExp expression = readRExp(); return null; } private RFunctionCall readFunctionCall(int flags) throws IOException { RPair attributes = readAttributes(flags); RExp tag = readTag(flags); RExp function = readRExp(); RPair arguments = (RPair)readRExp(); return new RFunctionCall(tag, function, arguments, attributes); } private RString readString(int flags) throws IOException { int length = readInt(); if(length == -1){ return new RString(null); } byte[] buffer = readByteArray(length); String value; if(SerializationUtil.isBytesCharset(flags)){ value = new String(buffer, StandardCharsets.US_ASCII); } else if(SerializationUtil.isLatin1Charset(flags)){ value = new String(buffer, StandardCharsets.ISO_8859_1); } else if(SerializationUtil.isUTF8Charset(flags)){ value = new String(buffer, StandardCharsets.UTF_8); } else { value = new String(buffer); } return new RString(value); } private RBooleanVector readLogicalVector(int flags) throws IOException { int length = readInt(); boolean[] values = new boolean[length]; for(int i = 0; i < length; i++){ int value = readInt(); values[i] = (value == 1); } return new RBooleanVector(values, readAttributes(flags)); } private RIntegerVector readIntVector(int flags) throws IOException { int length = readInt(); int[] values = new int[length]; for(int i = 0; i < length; i++){ int value = readInt(); values[i] = value; } return new RIntegerVector(values, readAttributes(flags)); } private RDoubleVector readRealVector(int flags) throws IOException { int length = readInt(); double[] values = new double[length]; for(int i = 0; i < length; i++){ double value = readDouble(); values[i] = value; } return new RDoubleVector(values, readAttributes(flags)); } private RStringVector readStringVector(int flags) throws IOException { int length = readInt(); List<String> values = new ArrayList<>(length); for(int i = 0; i < length; i++){ RString string = (RString)readRExp(); values.add(string.getValue()); } return new RStringVector(values, readAttributes(flags)); } private RGenericVector readVector(int flags) throws IOException { int length = readInt(); List<RExp> values = new ArrayList<>(length); for(int i = 0; i < length; i++){ RExp rexp = readRExp(); values.add(rexp); } return new RGenericVector(values, readAttributes(flags)); } private RExp readBytecode(int flags) throws IOException { int length = readInt(); readBC1(); return null; } private RExp readExternalPointer(int flags) throws IOException { RExp rexp = null; this.referenceTable.add(rexp); RExp protected_ = readRExp(); RExp tag = readRExp(); readAttributes(flags); return rexp; } private RRaw readRaw(int flags) throws IOException { int length = readInt(); byte[] value = readByteArray(length); return new RRaw(value, readAttributes(flags)); } private void readBC1() throws IOException { RExp code = readRExp(); readBCConsts(); } private void readBCConsts() throws IOException { int n = readInt(); for(int i = 0; i < n; i++){ int type = readInt(); switch(type){ case SExpTypes.LISTSXP: case SExpTypes.LANGSXP: readBCLang(type); break; case SExpTypes.BCODESXP: readBC1(); break; case SerializationTypes.ATTRLISTSXP: case SerializationTypes.ATTRLANGSXP: case SerializationTypes.BCREPREF: case SerializationTypes.BCREPDEF: readBCLang(type); break; default: readRExp(); break; } } } private void readBCLang(int type) throws IOException { switch(type){ case SExpTypes.LISTSXP: case SExpTypes.LANGSXP: case SerializationTypes.ATTRLISTSXP: case SerializationTypes.ATTRLANGSXP: case SerializationTypes.BCREPDEF: int pos = -1; if(type == SerializationTypes.BCREPDEF){ pos = readInt(); type = readInt(); } switch(type){ case SerializationTypes.ATTRLISTSXP: case SerializationTypes.ATTRLANGSXP: readAttributes(); break; default: break; } RExp tag = readRExp(); readBCLang(readInt()); readBCLang(readInt()); break; case SerializationTypes.BCREPREF: readInt(); break; default: readRExp(); break; } } private S4Object readS4Object(int flags) throws IOException { return new S4Object(readAttributes(flags)); } private RExp readNamespace() throws IOException { int flags = readInt(); if(flags != 0){ throw new UnsupportedOperationException(); } readStringVector(flags); this.referenceTable.add(null); return null; } private RExp readReference(int flags) throws IOException { int refIndex = SerializationUtil.unpackRefIndex(flags); if(refIndex == 0){ refIndex = readInt(); } return this.referenceTable.get(refIndex - 1); } private RExp readTag(int flags) throws IOException { if(SerializationUtil.hasTag(flags)){ return readRExp(); } return null; } private RPair readAttributes(int flags) throws IOException { if(SerializationUtil.hasAttributes(flags)){ return readAttributes(); } return null; } private RPair readAttributes() throws IOException { return (RPair)readRExp(); } private int readInt() throws IOException { return this.input.readInt(); } private double readDouble() throws IOException { return this.input.readDouble(); } private byte[] readByteArray(int length) throws IOException { return this.input.readByteArray(length); } static private InputStream init(PushbackInputStream is) throws IOException { byte[] gzipMagic = new byte[2]; ByteStreams.readFully(is, gzipMagic); is.unread(gzipMagic); if(Arrays.equals(RExpParser.GZIP_MAGIC, gzipMagic)){ return new GZIPInputStream(is); } return is; } private static final byte[] GZIP_MAGIC = {(byte)0x1f, (byte)0x8b}; }
package example; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE_NAMES; import static org.junit.jupiter.params.provider.EnumSource.Mode.MATCHES_ALL; import static org.junit.jupiter.params.provider.ObjectArrayArguments.arguments; import java.time.LocalDate; import java.util.EnumSet; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.TestReporter; import org.junit.jupiter.api.extension.ContainerExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.converter.ConvertWith; import org.junit.jupiter.params.converter.JavaTimeConversionPattern; import org.junit.jupiter.params.converter.SimpleArgumentConverter; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import org.junit.jupiter.params.provider.CsvFileSource; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ObjectArrayArguments; import org.junit.jupiter.params.provider.ValueSource; class ParameterizedTestDemo { // tag::first_example[] @ParameterizedTest @ValueSource(strings = { "Hello", "World" }) void testWithStringParameter(String argument) { assertNotNull(argument); } // end::first_example[] // tag::ValueSource_example[] @ParameterizedTest @ValueSource(ints = { 1, 2, 3 }) void testWithValueSource(int argument) { assertNotNull(argument); } // end::ValueSource_example[] // tag::EnumSource_example[] @ParameterizedTest @EnumSource(TimeUnit.class) void testWithEnumSource(TimeUnit timeUnit) { assertNotNull(timeUnit.name()); } // end::EnumSource_example[] // tag::EnumSource_include_example[] @ParameterizedTest @EnumSource(value = TimeUnit.class, names = { "DAYS", "HOURS" }) void testWithEnumSourceInclude(TimeUnit timeUnit) { assertTrue(EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS).contains(timeUnit)); } // end::EnumSource_include_example[] // tag::EnumSource_exclude_example[] @ParameterizedTest @EnumSource(value = TimeUnit.class, mode = EXCLUDE_NAMES, names = { "DAYS", "HOURS" }) void testWithEnumSourceExclude(TimeUnit timeUnit) { assertFalse(EnumSet.of(TimeUnit.DAYS, TimeUnit.HOURS).contains(timeUnit)); assertTrue(timeUnit.name().length() > 5); } // end::EnumSource_exclude_example[] // tag::EnumSource_regex_example[] @ParameterizedTest @EnumSource(value = TimeUnit.class, mode = MATCHES_ALL, names = "[M|N].+SECONDS") void testWithEnumSourceRegex(TimeUnit timeUnit) { assertTrue(timeUnit.name().startsWith("M") || timeUnit.name().startsWith("N")); assertTrue(timeUnit.name().endsWith("SECONDS")); } // end::EnumSource_regex_example[] // tag::simple_MethodSource_example[] @ParameterizedTest @MethodSource("stringProvider") void testWithSimpleMethodSource(String argument) { assertNotNull(argument); } static Stream<String> stringProvider() { return Stream.of("foo", "bar"); } // end::simple_MethodSource_example[] // tag::primitive_MethodSource_example[] @ParameterizedTest @MethodSource("range") void testWithRangeMethodSource(int argument) { assertNotEquals(9, argument); } static IntStream range() { return IntStream.range(0, 20).skip(10); } // end::primitive_MethodSource_example[] // tag::multi_arg_MethodSource_example[] @ParameterizedTest @MethodSource("stringAndIntProvider") void testWithMultiArgMethodSource(String first, int second) { assertNotNull(first); assertNotEquals(0, second); } static Stream<Arguments> stringAndIntProvider() { return Stream.of(arguments("foo", 1), arguments("bar", 2)); } // end::multi_arg_MethodSource_example[] // tag::CsvSource_example[] @ParameterizedTest @CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" }) void testWithCsvSource(String first, int second) { assertNotNull(first); assertNotEquals(0, second); } // end::CsvSource_example[] // tag::CsvFileSource_example[] @ParameterizedTest @CsvFileSource(resources = "/two-column.csv") void testWithCsvFileSource(String first, int second) { assertNotNull(first); assertNotEquals(0, second); } // end::CsvFileSource_example[] // tag::ArgumentsSource_example[] @ParameterizedTest @ArgumentsSource(MyArgumentsProvider.class) void testWithArgumentsSource(String argument) { assertNotNull(argument); } static class MyArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ContainerExtensionContext context) { return Stream.of("foo", "bar").map(ObjectArrayArguments::arguments); } } // end::ArgumentsSource_example[] // tag::ParameterResolver_example[] @ParameterizedTest @ValueSource(strings = "foo") void testWithRegularParameterResolver(String argument, TestReporter testReporter) { testReporter.publishEntry("argument", argument); } // end::ParameterResolver_example[] // tag::implicit_conversion_example[] @ParameterizedTest @ValueSource(strings = "SECONDS") void testWithImplicitArgumentConversion(TimeUnit argument) { assertNotNull(argument.name()); } // end::implicit_conversion_example[] // tag::explicit_conversion_example[] @ParameterizedTest @EnumSource(TimeUnit.class) void testWithExplicitArgumentConversion(@ConvertWith(ToStringArgumentConverter.class) String argument) { assertNotNull(TimeUnit.valueOf(argument)); } static class ToStringArgumentConverter extends SimpleArgumentConverter { @Override protected Object convert(Object source, Class<?> targetType) { assertEquals(String.class, targetType, "Can only convert to String"); return String.valueOf(source); } } // end::explicit_conversion_example[] // tag::explicit_java_time_converter[] @ParameterizedTest @ValueSource(strings = { "01.01.2017", "31.12.2017" }) void testWithExplicitJavaTimeConverter(@JavaTimeConversionPattern("dd.MM.yyyy") LocalDate argument) { assertEquals(2017, argument.getYear()); } // end::explicit_java_time_converter[] // tag::custom_display_names[] @DisplayName("Display name of container") @ParameterizedTest(name = "{index} ==> first=''{0}'', second={1}") @CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" }) void testWithCustomDisplayNames(String first, int second) { } // end::custom_display_names[] }
package org.lantern; import java.io.IOException; import java.net.MalformedURLException; import java.security.SecureRandom; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.DefaultHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.resource.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Launcher and secure path handler for Jetty. */ public class JettyLauncher { private final Logger log = LoggerFactory.getLogger(getClass()); private final SecureRandom sr = new SecureRandom(); private final String secureBase = "/"+String.valueOf(sr.nextLong()); private final int randomPort = LanternUtils.randomPort(); private final String fullBasePath = "http://localhost:"+randomPort+secureBase; private Server server = new Server(); public void start() { final SelectChannelConnector connector = new SelectChannelConnector(); connector.setHost("127.0.0.1"); connector.setPort(randomPort); server.addConnector(connector); final ResourceHandler rh = new FileServingResourceHandler(); rh.setDirectoriesListed(false); rh.setAliases(false); //rh.setWelcomeFiles(new String[]{ "lanternmap.html" }); rh.setResourceBase("viz/skel"); final HandlerList handlers = new HandlerList(); handlers.setHandlers( new Handler[] { rh, new DefaultHandler() }); server.setHandler(handlers); final Thread serve = new Thread(new Runnable() { @Override public void run() { try { server.start(); server.join(); } catch (final Exception e) { log.error("Exception on HTTP server"); } } }, "HTTP-Server-Thread"); serve.setDaemon(true); serve.start(); } private final class FileServingResourceHandler extends ResourceHandler { @Override public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (!target.startsWith(secureBase)) { // This can happen quite often, as the pages we serve // themselves don't know about the secure base. As long as // they get referred by the secure base, however, we're all // good. log.info("Got request without secure base!!"); final String referer = request.getHeader("Referer"); if (referer == null || !referer.startsWith(fullBasePath)) { log.error("Got request with bad referer: {} with target {}", referer, target); response.getOutputStream().close(); return; } } super.handle(target, baseRequest, request, response); } @Override public Resource getResource(final String path) throws MalformedURLException { if (!path.startsWith(secureBase)) { log.info("Requesting unstripped: {}", path); return super.getResource(path); } final String stripped = StringUtils.substringAfter(path, secureBase); log.info("Requesting stripped: {}", stripped); return super.getResource(stripped); } } public void openBrowserWhenReady() { while(!server.isRunning()) { try { Thread.sleep(200); } catch (final InterruptedException e) { log.info("Interrupted?"); } } final String url = fullBasePath + "/lanternmap.html"; LanternUtils.browseUrl(url); } public static void main (final String[] args) { final JettyLauncher jl = LanternHub.jettyLauncher(); System.out.println("Starting!!"); jl.start(); System.out.println("Opening browser!!"); jl.openBrowserWhenReady(); try { Thread.sleep(200000); } catch (InterruptedException e) { } } }
package uk.me.steev.java.heating.controller; import java.io.File; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.google.api.services.calendar.model.Event; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import uk.me.steev.java.heating.io.api.CalendarAdapter; import uk.me.steev.java.heating.io.api.WeatherAdapter; import uk.me.steev.java.heating.io.boiler.Boiler; import uk.me.steev.java.heating.io.boiler.Relay; import uk.me.steev.java.heating.io.boiler.RelayException; import uk.me.steev.java.heating.io.boiler.RelayTypes; import uk.me.steev.java.heating.io.http.HttpAdapter; import uk.me.steev.java.heating.io.temperature.BluetoothTemperatureSensor; import uk.me.steev.java.heating.utils.ResubmittingScheduledExecutor; public class Heating { static final Logger logger = LogManager.getLogger(Heating.class.getName()); protected HeatingConfiguration config; protected Boiler boiler; protected WeatherAdapter weather; protected CalendarAdapter calendar; protected Map<String,BluetoothTemperatureSensor> sensors; protected ScheduledThreadPoolExecutor scheduledExecutor; protected SensorScanner scanner; protected HeatingProcessor processor; protected HttpAdapter httpAdapter; protected Float desiredTemperature; public Heating(File configFile) throws HeatingException { try { //Get configuration this.config = HeatingConfiguration.getConfiguration(configFile); //Set up relays Relay heatingRelay = Relay.findRelay(RelayTypes.USB_1, config.getRelay("heating")); Relay preheatRelay = Relay.findRelay(RelayTypes.USB_1, config.getRelay("preheat")); this.boiler = new Boiler(heatingRelay, preheatRelay); //Set up weather API this.weather = new WeatherAdapter(this.config); //Set up events API this.calendar = new CalendarAdapter(this.config); //Set up an empty set of temperature sensors this.sensors = new ConcurrentHashMap<>(); //Set up a thing to run other things periodically this.scheduledExecutor = new ResubmittingScheduledExecutor(10); this.scanner = new SensorScanner(); this.processor = new HeatingProcessor(); this.httpAdapter = HttpAdapter.getHttpAdapter(this); } catch (RelayException | IOException e) { throw new HeatingException("Error creating Heating object", e); } } public Heating() throws HeatingException { this(new File("config.json")); } public void start() { //Look for new sensors every minute this.scheduledExecutor.scheduleAtFixedRate(this.scanner, 0, 1, TimeUnit.MINUTES); //Get new events every six hours this.scheduledExecutor.scheduleAtFixedRate(calendar.getEventsUpdater(), 0, 6, TimeUnit.HOURS); //Get new outside temperature every fifteen minutes this.scheduledExecutor.scheduleAtFixedRate(weather.getUpdater(), 0, 15, TimeUnit.MINUTES); //Process the whole lot every minute this.scheduledExecutor.scheduleAtFixedRate(this.processor, 0, 1, TimeUnit.MINUTES); } public HeatingConfiguration getConfig() { return config; } public void setConfig(HeatingConfiguration config) { this.config = config; } public Boiler getBoiler() { return boiler; } public void setBoiler(Boiler boiler) { this.boiler = boiler; } public WeatherAdapter getWeather() { return weather; } public void setWeather(WeatherAdapter weather) { this.weather = weather; } public CalendarAdapter getCalendar() { return calendar; } public void setCalendar(CalendarAdapter calendar) { this.calendar = calendar; } public Map<String, BluetoothTemperatureSensor> getSensors() { return sensors; } public void setSensors(Map<String, BluetoothTemperatureSensor> sensors) { this.sensors = sensors; } public ScheduledThreadPoolExecutor getScheduledExecutor() { return scheduledExecutor; } public void setScheduledExecutor(ScheduledThreadPoolExecutor scheduledExecutor) { this.scheduledExecutor = scheduledExecutor; } public SensorScanner getScanner() { return scanner; } public void setScanner(SensorScanner scanner) { this.scanner = scanner; } public HeatingProcessor getProcessor() { return processor; } public void setProcessor(HeatingProcessor processor) { this.processor = processor; } public HttpAdapter getHttpAdapter() { return httpAdapter; } public void setHttpAdapter(HttpAdapter httpAdapter) { this.httpAdapter = httpAdapter; } public Float getDesiredTemperature() { return desiredTemperature; } public void setDesiredTemperature(Float desiredTemperature) { this.desiredTemperature = desiredTemperature; } public class SensorScanner implements Runnable { public void run() { synchronized(boiler) { try { Map<String,BluetoothTemperatureSensor> newSensors = BluetoothTemperatureSensor.scanForSensors(); synchronized (sensors) { for (Entry<String, BluetoothTemperatureSensor> entry : newSensors.entrySet()) { if (!sensors.containsKey(entry.getKey())) { BluetoothTemperatureSensor sensor = newSensors.get(entry.getKey()); Runnable task = sensor.getTemperatureUpdater(); sensor.setTemperatureUpdatdaterFuture(scheduledExecutor.scheduleAtFixedRate(task, 0, 1, TimeUnit.MINUTES)); logger.info("Adding " + sensor + " to sensors list"); sensors.put(entry.getKey(), entry.getValue()); } } } } catch (Throwable t) { logger.catching(Level.ERROR, t); } } } } public class HeatingProcessor implements Runnable { public void run() { synchronized(boiler) { try { int minimumTemperature; Duration minutesPerDegree; Duration effectDelayMinutes; Duration proportionalHeatingIntervalMinutes; Duration minimumActivePeriodMinutes; double overshootDegrees; try { minimumTemperature = getConfig().getIntegerSetting("heating", "minimum_temperature"); minutesPerDegree = Duration.ofMinutes(getConfig().getIntegerSetting("heating", "minutes_per_degree")); effectDelayMinutes = Duration.ofMinutes(getConfig().getIntegerSetting("heating", "effect_delay_minutes")); proportionalHeatingIntervalMinutes = Duration.ofMinutes(getConfig().getIntegerSetting("heating", "proportional_heating_interval_minutes")); minimumActivePeriodMinutes = Duration.ofMinutes(getConfig().getIntegerSetting("heating", "minimum_active_period_minutes")); overshootDegrees = getConfig().getDoubleSetting("heating", "overshoot_degrees"); } catch (HeatingException e) { logger.catching(Level.FATAL, e); return; } setDesiredTemperature((float) minimumTemperature); //Do preheat first, it doesn't rely on temperature //Get a list of preheat events List<Event> preheatEvents = new ArrayList<>(); for (Event event : calendar.getCachedEvents()) { if ("preheat".equals(event.getSummary().toLowerCase())) preheatEvents.add(event); } //Check if any of them are now boolean shouldPreheat = false; for (Event event : preheatEvents) { LocalDateTime eventStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getStart().getDateTime().getValue()), ZoneId.systemDefault()); LocalDateTime eventEndTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getEnd().getDateTime().getValue()), ZoneId.systemDefault()); if (LocalDateTime.now().isAfter(eventStartTime) && LocalDateTime.now().isBefore(eventEndTime)) { shouldPreheat = true; logger.info("Preheat should be on"); try { if (!boiler.isPreheating()) boiler.startPreheating(); } catch (RelayException re) { logger.catching(Level.ERROR, re); } } } try { if (boiler.isPreheating() && !shouldPreheat) { logger.info("Preheat should be off"); boiler.stopPreheating(); } } catch (RelayException re) { logger.catching(Level.ERROR, re); } //Now events that are "on" List<Event> heatingOnEvents = new ArrayList<>(); for (Event event : calendar.getCachedEvents()) { if ("on".equals(event.getSummary().toLowerCase())) heatingOnEvents.add(event); } //Check if any of them are now boolean forcedOn = false; for (Event event : heatingOnEvents) { LocalDateTime eventStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getStart().getDateTime().getValue()), ZoneId.systemDefault()); LocalDateTime eventEndTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getEnd().getDateTime().getValue()), ZoneId.systemDefault()); if (LocalDateTime.now().isAfter(eventStartTime) && LocalDateTime.now().isBefore(eventEndTime)) { forcedOn = true; logger.info("Heating forced on"); try { if (!boiler.isHeating()) boiler.startHeating(); } catch (RelayException re) { logger.catching(Level.ERROR, re); } break; } } if (!forcedOn) { //Now get latest temperatures List<Float> allCurrentTemps = new ArrayList<>(); Float currentTemperature = null; for (Entry<String,BluetoothTemperatureSensor> entry : sensors.entrySet()) { BluetoothTemperatureSensor sensor = entry.getValue(); LocalDateTime lastUpdated = sensor.getTempLastUpdated(); LocalDateTime lastFailed = sensor.getTempLastFailedUpdate(); if (!(null == lastUpdated) && lastUpdated.isAfter(LocalDateTime.now().minus(3, ChronoUnit.MINUTES))) { allCurrentTemps.add(sensor.getCurrentTemperature()); } else if (null == lastUpdated && null == lastFailed) { logger.warn("Sensor time and failed time for " + sensor.toString() + " are null, ignoring (just created?)"); } else { logger.warn("Sensor time for " + sensor.toString() + " is more than three minutes old, disconnecting"); sensor.disconnect(); sensor.getTemperatureUpdatdaterFuture().cancel(false); synchronized (sensors) { sensors.remove(entry.getKey()); } } } allCurrentTemps.sort(null); logger.info("Current temperatures: " + allCurrentTemps.toString()); if (allCurrentTemps.size() > 0) currentTemperature = allCurrentTemps.get(0); if (null == currentTemperature) { logger.warn("No current temperature from sensors"); return; } logger.debug("Current temperature is " + currentTemperature); try { if (currentTemperature < minimumTemperature) { logger.info("Current temperature " + currentTemperature + " is less than minimum temperature " + minimumTemperature + ". On."); if (!(boiler.isHeating())) boiler.startHeating(); return; } } catch (RelayException re) { logger.catching(Level.ERROR, re); } List<TemperatureEvent> timesDueOn = new ArrayList<>(); for (Event event : calendar.getCachedEvents()) { try { float eventTemperature = Float.parseFloat(event.getSummary()); LocalDateTime eventStartTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getStart().getDateTime().getValue()), ZoneId.systemDefault()); LocalDateTime eventEndTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(event.getEnd().getDateTime().getValue()), ZoneId.systemDefault()); if (eventStartTime.isBefore(LocalDateTime.now()) && eventEndTime.isAfter(LocalDateTime.now())) { timesDueOn.add(new TemperatureEvent(eventStartTime, eventStartTime, eventEndTime, eventTemperature)); } else if (eventStartTime.isAfter(LocalDateTime.now())) { if (eventTemperature > currentTemperature) { LocalDateTime newEventStartTime = eventStartTime.minus(effectDelayMinutes) .minusSeconds((long) (minutesPerDegree.toMinutes() * (eventTemperature - currentTemperature) * 60)); timesDueOn.add(new TemperatureEvent(newEventStartTime, eventStartTime, eventEndTime, eventTemperature)); } } } catch (NumberFormatException nfe) { continue; } } //Put the elements in order of soonest to latest timesDueOn.sort(null); logger.debug("Times due on: " + timesDueOn.toString()); try { if (timesDueOn.size() > 0) { TemperatureEvent timeDueOn = null; //Find if we need to warm up for any future events for (TemperatureEvent event : timesDueOn) { if (event.getStartTime().isBefore(LocalDateTime.now())) continue; if (event.getTimeDueOn().isBefore(LocalDateTime.now())) timeDueOn = event; } //No events to warm up for, use first event in list if (null == timeDueOn) timeDueOn = timesDueOn.get(0); if (timeDueOn.getStartTime().isBefore(LocalDateTime.now())) setDesiredTemperature(timeDueOn.temperature); if (timeDueOn.getStartTime().isAfter(LocalDateTime.now()) && timeDueOn.getTimeDueOn().isBefore(LocalDateTime.now()) && timeDueOn.getTemperature() < (double) currentTemperature + overshootDegrees && timeDueOn.getTimeDueOn().plus(minimumActivePeriodMinutes).isBefore(LocalDateTime.now()) && boiler.isHeating()) { logger.info("Warming up, temperature will reach desired point, turn off"); boiler.stopHeating(); } else if (timeDueOn.getTemperature() > currentTemperature && timeDueOn.getTimeDueOn().isBefore(LocalDateTime.now())) { logger.debug("Current temperature " + currentTemperature + " is below desired temperature " + timeDueOn.getTemperature() + " in an event starting at " + timeDueOn.getStartTime() + " warming up from " + timeDueOn.getTimeDueOn()); Duration newProportionalTime = Duration.ofSeconds((long) ((timeDueOn.getTemperature() - currentTemperature) * proportionalHeatingIntervalMinutes.toMinutes() * 60)); if (timeDueOn.getStartTime().isAfter(LocalDateTime.now()) && timeDueOn.getTimeDueOn().isBefore(LocalDateTime.now())) { logger.debug("Warm-up period, stay on until desired temp period starts"); newProportionalTime = proportionalHeatingIntervalMinutes; } else if (newProportionalTime.compareTo(minimumActivePeriodMinutes) < 0) { newProportionalTime = minimumActivePeriodMinutes; } else if (newProportionalTime.compareTo(proportionalHeatingIntervalMinutes) > 0) { newProportionalTime = proportionalHeatingIntervalMinutes; } if (boiler.isHeating()) { LocalDateTime timeHeatingOn = boiler.getTimeHeatingOn(); logger.debug("Heating is on - came on at " + timeHeatingOn + " and proportion is " + newProportionalTime); if (timeHeatingOn.plus(newProportionalTime).compareTo(LocalDateTime.now()) < 0) { boiler.stopHeating(); //Reschedule processor for when the proportional interval ends scheduledExecutor.schedule(this, newProportionalTime.toMillis(), TimeUnit.MILLISECONDS); } } else { LocalDateTime timeHeatingOff = boiler.getTimeHeatingOff(); logger.debug("Heating is off - went off at " + timeHeatingOff + " and proportion is " + newProportionalTime); if (timeHeatingOff.plus(proportionalHeatingIntervalMinutes.minus(newProportionalTime)).compareTo(LocalDateTime.now()) < 0) { boiler.startHeating(); //Reschedule processor for when the proportional interval ends scheduledExecutor.schedule(this, newProportionalTime.toMillis(), TimeUnit.MILLISECONDS); } } } else { logger.debug("No current demand for heating"); if (boiler.isHeating()) { logger.debug("Boiler is on, turn off"); boiler.stopHeating(); } } } else { logger.debug("No events where there would be potential heating demand"); if (boiler.isHeating()) { logger.debug("Boiler is on, turn off"); boiler.stopHeating(); } } } catch (RelayException re) { logger.catching(Level.ERROR, re); } } } catch (Throwable t) { logger.catching(Level.ERROR, t); } } } } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Heating [config=").append(config).append(", boiler=").append(boiler).append(", weather=") .append(weather).append(", calendar=").append(calendar).append(", sensors=").append(sensors) .append(", scheduledExecutor=").append(scheduledExecutor).append(", scanner=").append(scanner) .append(", processor=").append(processor).append(", httpAdapter=").append(httpAdapter) .append(", desiredTemperature=").append(desiredTemperature).append("]"); return builder.toString(); } public static void main(String[] args) { try { Heating heating = new Heating(); heating.start(); } catch (HeatingException he) { he.printStackTrace(); } } }
package org.monarch.golr; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; import org.monarch.golr.beans.GolrCypherQuery; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.datatype.guava.GuavaModule; import com.google.common.base.Optional; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import edu.sdsc.scigraph.internal.EvidenceAspect; import edu.sdsc.scigraph.internal.GraphAspect; import edu.sdsc.scigraph.neo4j.Neo4jConfiguration; import edu.sdsc.scigraph.neo4j.Neo4jModule; public class Pipeline { private static final Logger logger = Logger.getLogger(Pipeline.class.getName()); private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); private static final String SOLR_JSON_URL_SUFFIX = "update/json?commit=true"; static { mapper.registerModules(new GuavaModule()); } public static Options getOptions() { Options options = new Options(); Option option = Option.builder("g").longOpt("graph").required().hasArg().desc("The Neo4j graph configuration").build(); options.addOption(option); option = Option.builder("q").longOpt("query").required().hasArg().desc("The query configuration").build(); options.addOption(option); option = Option.builder("s").longOpt("solr-server").required(false).hasArg().desc("An optional Solr server to update").build(); options.addOption(option); option = Option.builder("o").longOpt("output").required(false).hasArg().desc("An optional output file for the JSON").build(); options.addOption(option); return options; } public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException, URISyntaxException { Options options = getOptions(); CommandLineParser parser = new DefaultParser(); CommandLine cmd; Neo4jConfiguration neo4jConfig = null; GolrCypherQuery query = null; Optional<String> solrServer = Optional.absent(); Optional<String> outputFile = Optional.absent(); try { cmd = parser.parse(options, args); neo4jConfig = mapper.readValue(new File(cmd.getOptionValue("g")), Neo4jConfiguration.class); query = mapper.readValue(new File(cmd.getOptionValue("q")), GolrCypherQuery.class); if (cmd.hasOption("s")) { solrServer = Optional.of(cmd.getOptionValue("s")); } if (cmd.hasOption("o")) { outputFile = Optional.of(cmd.getOptionValue("o")); } } catch (ParseException e) { new HelpFormatter().printHelp("GolrLoad", options); System.exit(-1); } Injector i = Guice.createInjector( new GolrLoaderModule(), new Neo4jModule(neo4jConfig), new AbstractModule() { @Override protected void configure() { bind(GraphAspect.class).to(EvidenceAspect.class); } }); GolrLoader loader = i.getInstance(GolrLoader.class); File out = null; if (outputFile.isPresent()) { out = new File(outputFile.get()); } else { out = Files.createTempFile("golr-load", ".json").toFile(); out.deleteOnExit(); } logger.info("Writing JSON to: " + out.getAbsolutePath()); try (FileWriter writer = new FileWriter(out)) { long recordCount = loader.process(query, writer); logger.info("Wrote " + recordCount + " documents to: " + out.getAbsolutePath()); } logger.info("...done"); if (solrServer.isPresent()) { logger.info("Posting JSON to " + solrServer.get()); try { String result = Request .Post(new URI(solrServer.get() + (solrServer.get().endsWith("/") ? "" : "/") + SOLR_JSON_URL_SUFFIX)) .bodyFile(out, ContentType.APPLICATION_JSON) .execute().returnContent().asString(); logger.info(result); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to post JSON", e); System.exit(-1); } logger.info("...done"); } } }
package org.drools.lang; import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * Expanders are extension points for expanding * expressions in DRL at parse time. * This is just-in-time translation, or macro expansion, or * whatever you want. * * The important thing is that it happens at the last possible moment, * so any errors in expansion are included in the parsers errors. * * Just-in-time expansions may include complex pre-compilers, * or just macros, and everything in between. * * @author <a href="mailto:michael.neale@gmail.com"> Michael Neale</a> * */ public class ExpanderContext implements Serializable { private static final long serialVersionUID = 1806461802987228880L; private boolean enabled = true; private final Set expanders; /** * This indicates that at least one expander has been configured for * this parser configuration. */ public boolean isEnabled() { return enabled; } public void disable() { this.enabled = false; } public ExpanderContext(Collection initialExpanders) { this.expanders = new HashSet(initialExpanders); } public ExpanderContext() { this.expanders = new HashSet(); } public ExpanderContext addExpander(Expander exp) { expanders.add(exp); return this; } /** * The parser should call this on an expression/line that potentially needs expanding * BEFORE it parses that line (as the line may change radically as the result of expansion). * * Expands the expression Just-In-Time for the parser. * If the expression is not meant to be expanded, or if no * appropriate expander is found, it will echo back the same * expression. * * @param expression The "line" or expression to be expanded/pre-compiled. * @param context The context of the current state of parsing. This can help * the expander know if it needs to expand, what to do etc. * * If <code>isEnabled()</code> is false then it is not required to * call this method. */ public CharSequence expand(CharSequence expression, RuleParser context) { return expression; } }
package org.researchgraph.app; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import javax.xml.transform.Source; import javax.xml.transform.Templates; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import com.sun.tools.jdi.BooleanValueImpl; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.researchgraph.configuration.Properties; import org.researchgraph.crosswalk.CrosswalkRG; import org.researchgraph.graph.Graph; import org.researchgraph.neo4j.Neo4jDatabase; import com.amazonaws.auth.InstanceProfileCredentialsProvider; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.GetObjectRequest; import com.amazonaws.services.s3.model.ListObjectsRequest; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.S3Object; import com.amazonaws.services.s3.model.S3ObjectSummary; public class App { public static void main(String[] args) { try { Configuration properties = Properties.fromArgs(args); String neo4jFolder = properties.getString(Properties.PROPERTY_NEO4J_FOLDER); if (StringUtils.isEmpty(neo4jFolder)) throw new IllegalArgumentException("Neo4j Folder can not be empty"); System.out.println("Neo4J: " + neo4jFolder); String bucket = properties.getString(Properties.PROPERTY_S3_BUCKET); String prefix = properties.getString(Properties.PROPERTY_S3_PREIFX); String xmlFolder = properties.getString(Properties.PROPERTY_XML_FOLDER); String xmlType = properties.getString(Properties.PROPERTY_XML_TYPE); String source = properties.getString(Properties.PROPERTY_SOURCE); String crosswalk = properties.getString(Properties.PROPERTY_CROSSWALK); Boolean verbose = Boolean.parseBoolean(Properties.PROPERTY_VERBOSE); Templates template = null; if (!StringUtils.isEmpty(crosswalk)) { System.out.println("Crosswalk: " + crosswalk); TransformerFactory tfactory = net.sf.saxon.TransformerFactoryImpl.newInstance(); SAXTransformerFactory stfactory = (SAXTransformerFactory) tfactory; template = tfactory.newTemplates(new StreamSource(crosswalk)); } CrosswalkRG.XmlType type = CrosswalkRG.XmlType.valueOf(xmlType); if (!StringUtils.isEmpty(bucket) && !StringUtils.isEmpty(prefix)) { System.out.println("S3 Bucket: " + bucket); System.out.println("S3 Prefix: " + prefix); System.out.println("Version folder: " + properties.getString(Properties.PROPERTY_VERSIONS_FOLDER)); System.out.println("Vernbose: " + verbose.toString()); String versionFolder = properties.getString(Properties.PROPERTY_VERSIONS_FOLDER); if (StringUtils.isEmpty(versionFolder)) throw new IllegalArgumentException("Versions Folder can not be empty"); processS3Files(bucket, prefix, neo4jFolder, versionFolder, source, type, template, verbose); } else if (!StringUtils.isEmpty(xmlFolder)) { System.out.println("XML: " + xmlFolder); processFiles(xmlFolder, neo4jFolder, source, type, template,verbose); } else throw new IllegalArgumentException("Please provide either S3 Bucket and prefix OR a path to a XML Folder"); // debugFile(accessKey, secretKey, bucket, "rda/rif/class:collection/54800.xml"); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private static void processS3Files(String bucket, String prefix, String neo4jFolder, String versionFolder, String source, CrosswalkRG.XmlType type, Templates template, Boolean verbose) throws Exception { AmazonS3 s3client = new AmazonS3Client(new InstanceProfileCredentialsProvider()); CrosswalkRG crosswalk = new CrosswalkRG(); crosswalk.setSource(source); crosswalk.setType(type); crosswalk.setVerbose(verbose); Neo4jDatabase neo4j = new Neo4jDatabase(neo4jFolder); neo4j.setVerbose(verbose); ListObjectsRequest listObjectsRequest; ObjectListing objectListing; String file = prefix + "/latest.txt"; S3Object object = s3client.getObject(new GetObjectRequest(bucket, file)); String latest; try (InputStream txt = object.getObjectContent()) { latest = IOUtils.toString(txt, StandardCharsets.UTF_8).trim(); } if (StringUtils.isEmpty(latest)) throw new Exception("Unable to find latest harvest in the S3 Bucket (latest.txt file is empty or not avaliable). Please check if you have access to S3 bucket and did you have completed the harvestring."); String folder = prefix + "/" + latest + "/"; System.out.println("S3 Repository: " + latest); listObjectsRequest = new ListObjectsRequest() .withBucketName(bucket) .withPrefix(folder); do { objectListing = s3client.listObjects(listObjectsRequest); for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) { file = objectSummary.getKey(); System.out.println("Processing file: " + file); object = s3client.getObject(new GetObjectRequest(bucket, file)); if (null != template) { Source reader = new StreamSource(object.getObjectContent()); StringWriter writer = new StringWriter(); Transformer transformer = template.newTransformer(); transformer.transform(reader, new StreamResult(writer)); InputStream stream = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8)); Graph graph = crosswalk.process(stream); neo4j.importGraph(graph); } else { InputStream xml = object.getObjectContent(); Graph graph = crosswalk.process(xml); neo4j.importGraph(graph); } } listObjectsRequest.setMarker(objectListing.getNextMarker()); } while (objectListing.isTruncated()); Files.write(Paths.get(versionFolder, source), latest.getBytes()); System.out.println("Done"); crosswalk.printStatistics(System.out); neo4j.printStatistics(System.out); } private static void processFiles(String xmlFolder, String neo4jFolder, String source, CrosswalkRG.XmlType type, Templates template, Boolean verbose) throws Exception { CrosswalkRG crosswalk = new CrosswalkRG(); crosswalk.setSource(source); crosswalk.setType(type); crosswalk.setVerbose(verbose); Neo4jDatabase neo4j = new Neo4jDatabase(neo4jFolder); neo4j.setVerbose(Boolean.parseBoolean(Properties.PROPERTY_VERBOSE)); neo4j.setVerbose(verbose); //importer.setVerbose(true); File[] files = new File(xmlFolder).listFiles(); for (File file : files) if (!file.isDirectory()) try (InputStream xml = new FileInputStream(file)) { System.out.println("Processing file: " + file); if (null != template) { Source reader = new StreamSource(xml); StringWriter writer = new StringWriter(); Transformer transformer = template.newTransformer(); transformer.transform(reader, new StreamResult(writer)); InputStream stream = new ByteArrayInputStream(writer.toString().getBytes(StandardCharsets.UTF_8)); Graph graph = crosswalk.process(stream); neo4j.importGraph(graph); } else { Graph graph = crosswalk.process(xml); neo4j.importGraph(graph); } } System.out.println("Done"); crosswalk.printStatistics(System.out); neo4j.printStatistics(System.out); } }
package query; import general.Main; import org.apache.log4j.Logger; import org.openrdf.model.Value; import org.openrdf.model.impl.URIImpl; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.algebra.ArbitraryLengthPath; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.Var; import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.parser.ParsedQuery; import org.openrdf.query.parser.sparql.BaseDeclProcessor; import org.openrdf.query.parser.sparql.PrefixDeclProcessor; import org.openrdf.query.parser.sparql.StringEscapesProcessor; import org.openrdf.query.parser.sparql.ast.*; import java.util.*; /** * @author jgonsior */ public class OpenRDFQueryHandler extends QueryHandler { /** * The base URI to resolve any possible relative URIs against. */ public static String BASE_URI = "https://query.wikidata.org/bigdata/namespace/wdq/sparql"; /** * Define a static logger variable. */ protected static Logger logger = Logger.getLogger(OpenRDFQueryHandler.class); /** * The query object created from query-string. */ private ParsedQuery query; /** * {@inheritDoc} */ public final void update() { try { this.query = this.parseQuery(getQueryString()); this.setValidityStatus(1); } catch (MalformedQueryException e) { String message = e.getMessage(); if (message != null) { if (message.contains("\n")) { message = message.substring(0, message.indexOf("\n")); } if (message.contains("Not a valid (absolute) URI:")) { logger.warn("This shoud not happen anymore: " + e.getMessage()); setValidityStatus(-3); } else if (message.contains("BIND clause alias '{}' was previously used")) { logger.warn("This shoud not happen anymore: " + e.getMessage()); setValidityStatus(-5); } else if (message.contains("Multiple prefix declarations for prefix")) { setValidityStatus(-6); } else { setValidityStatus(-1); } } else { setValidityStatus(-1); } logger.debug("Invalid query: \t" + getQueryString() + "\t->\t" + e.getMessage()); logger.debug("QUE length:" + this.getLengthNoAddedPrefixes() + "\t" + message); } } /** * Parses a given SPARQL 1.1 query into an OpenRDF ParsedQuery object. * * @param queryToParse SPARQL-query as string that should be parsed to OpenRDF * @return Returns the query as an OpenRDF ParsedQuery object * @throws MalformedQueryException if the supplied query was malformed */ private ParsedQuery parseQuery(String queryToParse) throws MalformedQueryException { //the third argument is the baseURI to resolve any relative URIs that are in //the query against, but it can be NULL as well StandardizingSPARQLParser parser = new StandardizingSPARQLParser(); /* try { queryAST = SyntaxTreeBuilder.parseQuery(queryToParse); } catch (TokenMgrError | ParseException e1) { throw new MalformedQueryException(e1.getMessage()); } parser.normalize(queryAST);*/ try { ParsedQuery parsedQuery = parser.parseQuery(queryToParse, BASE_URI); return parsedQuery; } catch (Throwable e) { // kind of a dirty hack to catch an java.lang.error which occurs when trying to parse a query which contains f.e. the following string: "jul\ius" where the \ is an invalid escape charachter //because this error is kind of an MalformedQueryException we will just throw it as one throw new MalformedQueryException(e.getMessage()); } } public final Integer getStringLengthNoComments() { if (getValidityStatus() != 1) { return -1; } String sourceQuery = query.getSourceString(); String uncommented = ""; //if there is a < or a " then there can't be a comment anymore until we reach a > or another " boolean canFindComments = true; boolean commentFound = false; //ignore all # that are inside <> or "" for (int i = 0; i < sourceQuery.length(); i++) { Character character = sourceQuery.charAt(i); if (character == '#' && canFindComments) { commentFound = true; } else if (character == '\n') { // in a new line everything is possible again commentFound = false; canFindComments = true; } else if (canFindComments && (character == '<' || character == '"')) { canFindComments = false; } else if (character == '>' || character == '"') { // now we can find comments again canFindComments = true; } //finally keep only characters that are NOT inside a comment if (!commentFound) { uncommented = uncommented + character; } } try { this.parseQuery(uncommented); } catch (MalformedQueryException e) { getLogger().warn("Tried to remove formatting from a valid string " + "but broke it while doing so.\n" + e.getLocalizedMessage() + "\n\n" + e.getMessage()); return -1; } return uncommented.length(); } @Override public Integer getQuerySize() { if (getValidityStatus() != 1) { return -1; } OpenRDFQuerySizeCalculatorVisitor openRDFQueryLengthVisitor = new OpenRDFQuerySizeCalculatorVisitor(); try { this.query.getTupleExpr().visit(openRDFQueryLengthVisitor); } catch (Exception e) { logger.error("An unknown error occured while calculating the query size: ", e); } return openRDFQueryLengthVisitor.getSize(); } /** * @return Returns the number of variables in the query pattern. */ public final Integer getVariableCountPattern() { if (getValidityStatus() != 1) { return -1; } final Set<Var> variables = new HashSet<>(); TupleExpr expr = this.query.getTupleExpr(); StatementPatternCollector collector = new StatementPatternCollector(); expr.visit(collector); List<StatementPattern> statementPatterns = collector.getStatementPatterns(); for (StatementPattern statementPattern : statementPatterns) { List<Var> statementVariables = statementPattern.getVarList(); for (Var statementVariable : statementVariables) { if (!statementVariable.isConstant()) { variables.add(statementVariable); } } } return variables.size(); } /** * @return Returns the number of variables in the query head. */ public final Integer getVariableCountHead() { if (getValidityStatus() != 1) { return -1; } return this.query.getTupleExpr().getBindingNames().size(); } /** * @return Returns the number of triples in the query pattern * (including triples in SERIVCE blocks). */ public final Integer getTripleCountWithService() { if (getValidityStatus() != 1) { return -1; } TupleExpr expr = this.query.getTupleExpr(); StatementPatternCollector collector = new StatementPatternCollector(); expr.visit(collector); return collector.getStatementPatterns().size(); } /** * {@inheritDoc} */ public final void computeQueryType() throws IllegalStateException { if (this.getValidityStatus() != 1) { throw new IllegalStateException(); } ParsedQuery normalizedQuery; try { normalizedQuery = normalize(query); } catch (MalformedQueryException | VisitorException e) { logger.error("Unexpected error while normalizing " + getQueryString(), e); throw new IllegalStateException(); } synchronized (Main.queryTypes) { Iterator<ParsedQuery> iterator = Main.queryTypes.keySet().iterator(); while (iterator.hasNext()) { ParsedQuery next = iterator.next(); if (next.getTupleExpr().equals(normalizedQuery.getTupleExpr())) { this.queryType = Main.queryTypes.get(next); return; } } } Main.queryTypes.put(normalizedQuery, String.valueOf(Main.queryTypes.size())); this.queryType = Main.queryTypes.get(normalizedQuery); return; } /** * @return the represented query normalized or null if the represented query was not valid */ public final ParsedQuery getNormalizedQuery() { try { return normalize(this.query); } catch (MalformedQueryException | VisitorException e) { return null; } } /** * Normalizes a given query by: * - replacing all wikidata uris at subject and object positions with sub1, sub2 ... (obj1, obj2 ...). * * @param queryToNormalize the query to be normalized * @return the normalized query * @throws MalformedQueryException If the query was malformed (would be a bug since the input was a parsed query) * @throws VisitorException If there is an error during normalization */ private ParsedQuery normalize(ParsedQuery queryToNormalize) throws MalformedQueryException, VisitorException { ParsedQuery normalizedQuery = new StandardizingSPARQLParser().parseNormalizeQuery(queryToNormalize.getSourceString(), BASE_URI); final Map<String, Integer> strings = new HashMap<String, Integer>(); normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() { @Override public void meet(StatementPattern statementPattern) { statementPattern.setSubjectVar(normalizeHelper(statementPattern.getSubjectVar(), strings)); statementPattern.setObjectVar(normalizeHelper(statementPattern.getObjectVar(), strings)); } }); normalizedQuery.getTupleExpr().visit(new QueryModelVisitorBase<VisitorException>() { @Override public void meet(ArbitraryLengthPath arbitraryLengthPath) { arbitraryLengthPath.setSubjectVar(normalizeHelper(arbitraryLengthPath.getSubjectVar(), strings)); arbitraryLengthPath.setObjectVar(normalizeHelper(arbitraryLengthPath.getObjectVar(), strings)); } }); return normalizedQuery; } /** * A helper function to find the fitting replacement value for wikidata uri normalization. * * @param var The variable to be normalized * @param foundNames The list of already found names * @return the normalized name (if applicable) */ private Var normalizeHelper(Var var, Map<String, Integer> foundNames) { if (var != null) { Value value = var.getValue(); if (value != null) { if (value.getClass().equals(URIImpl.class)) { String subjectString = value.stringValue(); if (subjectString.startsWith("http: if (!foundNames.containsKey(subjectString)) { foundNames.put(subjectString, foundNames.size() + 1); } String uri = subjectString.substring(0, subjectString.lastIndexOf("/")) + "/QName" + foundNames.get(subjectString); String name = "-const-" + uri + "-uri"; return new Var(name, new URIImpl(uri)); } } } } return var; } /** * @return The prefixed defined in the original query represented by this handler. */ private Map<String, String> getOriginalPrefixes() { if (this.getValidityStatus() == -1) { return null; } try { ASTQueryContainer qc = SyntaxTreeBuilder.parseQuery(this.getQueryStringWithoutPrefixes()); StringEscapesProcessor.process(qc); BaseDeclProcessor.process(qc, BASE_URI); return PrefixDeclProcessor.process(qc); } catch (TokenMgrError | ParseException | MalformedQueryException e) { logger.error("Unexpected error finding prefixes in query " + this.getQueryStringWithoutPrefixes(), e); return null; } } }
package roart.search; import roart.model.Index; import roart.model.Files; import roart.model.HibernateUtil; import roart.lang.LanguageDetect; import java.io.*; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.HashSet; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; //import org.apache.lucene.search.TopDocCollector; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.MMapDirectory; import org.apache.lucene.store.LockObtainFailedException; import org.apache.lucene.store.LockFactory; import org.apache.lucene.util.Version; import org.apache.lucene.index.Term; //import org.apache.lucene.search.Hits; import org.apache.lucene.search.TopDocs; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class SearchLucene { private static Log log = LogFactory.getLog("SearchLucene"); public static int indexme(String type, String md5, InputStream inputStream) { int retsize = 0; // create some index // we could also create an index in our ram ... // Directory index = new RAMDirectory(); try { Directory index = FSDirectory.open(new File(Constants.PATH+type)); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter w = new IndexWriter(index, iwc); DataInputStream in = new DataInputStream(inputStream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = null; // index some data StringBuilder result = new StringBuilder(); while ((line = br.readLine()) != null) { result.append(line); } String strLine = result.toString(); String i = strLine; retsize = strLine.length(); log.info("indexing " + md5); String lang = null; try { lang = LanguageDetect.detect(strLine); log.info("language " + lang); log.info("language2 " + LanguageDetect.detectLangs(strLine)); } catch (Exception e) { log.error("exception", e); } Document doc = new Document(); doc.add(new TextField(Constants.TITLE, md5, Field.Store.YES)); doc.add(new TextField(Constants.LANG, lang, Field.Store.YES)); doc.add(new TextField(Constants.NAME, i, Field.Store.NO)); Term term = new Term(Constants.TITLE, md5); w.updateDocument(term, doc); //w.addDocument(doc); w.close(); log.info("index generated"); } catch (Exception e) { log.info("Error3: " + e.getMessage()); log.error("Exception", e); } return retsize; } public static void indexme(String type) { // create some index // we could also create an index in our ram ... // Directory index = new RAMDirectory(); try { Directory index = FSDirectory.open(new File(Constants.PATH+type)); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter w = new IndexWriter(index, iwc); String filename = type; FileInputStream fstream = new FileInputStream("/home/roart/data/"+type+".txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine = null; // index some data while ((strLine = br.readLine()) != null) { String i = strLine; log.info("indexing " + i); Document doc = new Document(); doc.add(new TextField(Constants.TITLE, i, Field.Store.YES)); doc.add(new TextField(Constants.NAME, i, Field.Store.YES)); w.addDocument(doc); } w.close(); log.info("index generated"); } catch (Exception e) { log.info("Error3: " + e.getMessage()); log.error("Exception", e); } } public static String [] searchme(String type, String str) { String[] strarr = new String[0]; try { Directory index = FSDirectory.open(new File(Constants.PATH+type)); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40 ); // parse query over multiple fields Query q = new MultiFieldQueryParser(Version.LUCENE_40, new String[]{Constants.TITLE, Constants.NAME}, analyzer).parse(str); // searching ... int hitsPerPage = 100; IndexReader ind = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(ind); //TopDocCollector collector = new TopDocCollector(hitsPerPage); TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; strarr = new String[hits.length]; // output results log.info("Found " + hits.length + " hits."); for (int i = 0; i < hits.length; ++i) { int docId = hits[i].doc; float score = hits[i].score; Document d = searcher.doc(docId); log.info((i + 1) + ". " + d.get(Constants.TITLE) + ": " + score); strarr[i] = "" + (i + 1) + ". " + d.get(Constants.TITLE) + ": " + score; } } catch (Exception e) { log.info("Error3: " + e.getMessage()); log.error("Exception", e); } return strarr; } public static String [] searchme(String str) { String type = "all"; String[] strarr = new String[0]; try { Directory index = FSDirectory.open(new File(Constants.PATH+type)); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40 ); // parse query over multiple fields Query q = new MultiFieldQueryParser(Version.LUCENE_40, new String[]{Constants.TITLE, Constants.NAME, Constants.LANG}, analyzer).parse(str); // searching ... int hitsPerPage = 100; IndexReader ind = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(ind); //TopDocCollector collector = new TopDocCollector(hitsPerPage); TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true); searcher.search(q, collector); ScoreDoc[] hits = collector.topDocs().scoreDocs; strarr = new String[hits.length]; // output results log.info("Found " + hits.length + " hits."); for (int i = 0; i < hits.length; ++i) { int docId = hits[i].doc; float score = hits[i].score; Document d = searcher.doc(docId); String md5 = d.get(Constants.TITLE); String lang = d.get(Constants.LANG); String filename = null; List<Files> files = Files.getByMd5(md5); if (files != null && files.size() > 0) { Files file = files.get(0); filename = file.getFilename(); } String title = md5 + " " + filename; if (lang != null) { title = title + " (" + lang + ") "; } log.info((i + 1) + ". " + title + ": " + score); strarr[i] = "" + (i + 1) + ". " + title + ": " + score; } } catch (Exception e) { log.info("Error3: " + e.getMessage()); log.error("Exception", e); } return strarr; } public static void deleteme(String str) { try { String type = "all"; Directory index = FSDirectory.open(new File(Constants.PATH+type)); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter iw = new IndexWriter(index, iwc); //IndexReader r = IndexReader.open(index, false); iw.deleteDocuments(new Term(Constants.TITLE, str)); iw.close(); } catch (Exception e) { log.info("Error3: " + e.getMessage()); log.error("Exception", e); } } public static List<String> removeDuplicate() throws Exception { List<String> retlist = new ArrayList<String>(); String type = "all"; String field = Constants.TITLE; String indexDir = Constants.PATH+type; StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40 ); int docs = 0; int dups = 0; Directory index = FSDirectory.open(new File(Constants.PATH+type)); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter iw = new IndexWriter(index, iwc); IndexReader ind = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(ind); int totalDocs = iw.numDocs(); HashSet<Document> Doc = new HashSet<Document>(); for(int m=0;m<totalDocs;m++) { Document thisDoc = null; try { thisDoc = ind.document(m); } catch (Exception e) { log.error("Exception", e); continue; } String a2[] = thisDoc.getValues(field); a2[0].trim(); if (a2[0].equals("")) { continue; } String queryExpression = "\""+a2[0]+"\""; QueryParser parser=new QueryParser(Version.LUCENE_40,field,analyzer); Query queryJ=parser.parse(queryExpression); /** * Perform duplicate check-searching */ TopDocs topdocs = searcher.search(queryJ,100000); if (topdocs.totalHits>1) { dups++; retlist.add("Duplicates found:"+topdocs.totalHits+" for "+a2[0]); ScoreDoc[] hits = topdocs.scoreDocs; //Document d = searcher.doc(docId); Doc.add(searcher.doc(hits[0].doc)); for(int i=1;i<hits.length;i++) { //Document d = searcher.doc(docId); int docId = hits[i].doc; retlist.add("Deleting document #:"+docId); // check // check iw.deleteDocument(docId);//Delete Document by its Document ID } } else { retlist.add("single " + a2[0]); } /* Index indexmd5 = Index.getByMd5(a2[0]); if (indexmd5 == null) { retlist.add("delete1 " + a2[0]); ind.deleteDocument(topdocs.scoreDocs[0].doc); } if (indexmd5 != null) { Boolean indexed = indexmd5.getIndexed(); if (indexed != null && indexed.booleanValue()) { } else { retlist.add("delete2 " + a2[0]); ind.deleteDocument(topdocs.scoreDocs[0].doc); } } */ }//end of for loop int newDocs = ind.numDocs(); iw.close();//close index Reader /** * Open indexwriter to write duplicate document */ //IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); //IndexWriter iw = new IndexWriter(index, iwc); for(Document doc : Doc) { //iw.addDocument(doc); } //iw.optimize() ; iw.close();//Close Index Writer /** * Print statistics */ retlist.add("Entries Scanned:"+totalDocs); retlist.add("Duplicates:"+dups); retlist.add("Currently Present Entries:"+(docs+newDocs)); return retlist; }//End of removeDuplicate method public static List<String> cleanup2() throws Exception { List<String> retlist = new ArrayList<String>(); List<Files> files = Files.getAll(); List<Index> indexes = Index.getAll(); Map<String, String> filesMapMd5 = new HashMap<String, String>(); Map<String, Boolean> indexMap = new HashMap<String, Boolean>(); for (Index index : indexes) { indexMap.put(index.getMd5(), index.getIndexed()); } String type = "all"; String field = Constants.TITLE; String indexDir = Constants.PATH+type; StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40 ); int docs = 0; int errors = 0; Directory index = FSDirectory.open(new File(Constants.PATH+type)); IndexReader ind = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(ind); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter iw = new IndexWriter(index, iwc); int totalDocs = ind.numDocs(); HashSet<Document> Doc = new HashSet<Document>(); for(int m=0;m<totalDocs;m++) { Document thisDoc = null; try { thisDoc = ind.document(m); } catch (Exception e) { log.error("Exception", e); continue; } String a2[] = thisDoc.getValues(field); a2[0].trim(); if (a2[0].equals("")) { continue; } if (a2[0].contains("/home/roart/")) { retlist.add("error " + a2[0]); Files file = Files.getByFilename(a2[0]); String md5 = file.getMd5(); Index indexf = Index.getByMd5(md5); boolean indexval = false; if (indexf != null) { Boolean indexed = indexf.getIndexed(); if (indexed != null) { if (indexed.booleanValue()) { indexval = true; } } } retlist.add("md5 " + md5 + " " + indexf + " " + indexval); filesMapMd5.put(md5, a2[0]); errors++; Document d = searcher.doc(m); // check // iw.deleteDocument(m); } }//end of for loop for (String md5 : filesMapMd5.keySet()) { //roart.dir.Traverse.indexsingle(retlist, md5, indexMap, filesMapMd5); } /* Index indexmd5 = Index.getByMd5(a2[0]); if (indexmd5 == null) { retlist.add("delete1 " + a2[0]); ind.deleteDocument(topdocs.scoreDocs[0].doc); } if (indexmd5 != null) { Boolean indexed = indexmd5.getIndexed(); if (indexed != null && indexed.booleanValue()) { } else { retlist.add("delete2 " + a2[0]); ind.deleteDocument(topdocs.scoreDocs[0].doc); } } */ int newDocs = ind.numDocs(); ind.close();//close index Reader /** * Open indexwriter to write duplicate document */ //IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); //IndexWriter iw = new IndexWriter(index, iwc); for(Document doc : Doc) { //iw.addDocument(doc); } //iw.optimize() ; iw.close();//Close Index Writer /** * Print statistics */ retlist.add("Entries Scanned:"+totalDocs); retlist.add("Errors:"+errors); retlist.add("Currently Present Entries:"+(docs+newDocs)); return retlist; }//End of removeDuplicate method public static List<String> removeDuplicate2() throws Exception { List<String> retlist = new ArrayList<String>(); String type = "all"; String field = Constants.TITLE; String indexDir = Constants.PATH+type; StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40 ); int docs = 0; int dups = 0; Directory index = FSDirectory.open(new File(Constants.PATH+type)); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_40, analyzer); IndexWriter iw = new IndexWriter(index, iwc); IndexReader ind = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(ind); int totalDocs = ind.numDocs(); HashSet<Document> Doc = new HashSet<Document>(); for(int m=0;m<totalDocs;m++) { Document thisDoc = null; try { thisDoc = ind.document(m); String a2[] = thisDoc.getValues(field); a2[0].trim(); if (a2[0].equals("")) { continue; } Term term = new Term(Constants.TITLE, a2[0]); iw.updateDocument(term, thisDoc); } catch (Exception e) { retlist.add("" + e); log.error("Exception", e); } } /** * Print statistics */ retlist.add("Entries Scanned:"+totalDocs); return retlist; }//End of removeDuplicate method }
package ru.technoserv.domain; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.sql.Blob; @Entity @Table(name = "CERT_PAGES") public class Page { public Page() { } @Id @GeneratedValue ( strategy = GenerationType.SEQUENCE, generator = "page_generator" ) @GenericGenerator( name = "page_generator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = { @org.hibernate.annotations.Parameter(name = "sequence_name", value = "CERT_PAGES_SEQ"), // @org.hibernate.annotations.Parameter(name = "initial_value", value = "1"), @org.hibernate.annotations.Parameter(name = "increment_size", value = "1") } ) @Column (name = "ID") Integer id; @Column(name = "CERT_NUMBER") Integer number; @Column(name = "PAGE") Integer page; @Column(name = "IMAGE") byte[] image; public Integer getNumber() { return number; } public void setNumber(Integer number) { this.number = number; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public byte[] getImage() { return image; } public void setImage(byte[] image) { this.image = image; } }
package rx.broadcast; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Consumer; public final class UdpBroadcast<A> implements Broadcast { private static final int MAX_UDP_PACKET_SIZE = 65535; private static final int BYTES_LONG = 8; private final DatagramSocket socket; private final Observable<Object> values; private final ConcurrentHashMap<Class, Observable> streams; private final KryoSerializer serializer; private final InetAddress destinationAddress; private final int destinationPort; private final BroadcastOrder<A, Object> order; public UdpBroadcast( final DatagramSocket socket, final InetAddress destinationAddress, final int destinationPort, final BroadcastOrder<A, Object> order ) { this.socket = socket; this.order = order; this.values = Observable.<Object>create(this::receive).subscribeOn(Schedulers.io()).share(); this.serializer = new KryoSerializer(); this.streams = new ConcurrentHashMap<>(); this.destinationAddress = destinationAddress; this.destinationPort = destinationPort; } @Override public Observable<Void> send(final Object value) { return Observable.defer(() -> { try { final byte[] data = serializer.serialize(order.prepare(value)); final DatagramPacket packet = new DatagramPacket( data, data.length, destinationAddress, destinationPort); socket.send(packet); return Observable.empty(); } catch (final Throwable e) { return Observable.error(e); } }); } @Override @SuppressWarnings("unchecked") public <T> Observable<T> valuesOfType(final Class<T> clazz) { return (Observable<T>) streams.computeIfAbsent(clazz, k -> values.filter(k::isInstance).cast(k).share()); } @SuppressWarnings("unchecked") private void receive(final Subscriber<Object> subscriber) { final Consumer<Object> consumer = subscriber::onNext; while (true) { if (subscriber.isUnsubscribed()) { break; } final byte[] buffer = new byte[MAX_UDP_PACKET_SIZE]; final DatagramPacket packet = new DatagramPacket(buffer, buffer.length); try { socket.receive(packet); } catch (final IOException e) { subscriber.onError(e); break; } final InetAddress address = packet.getAddress(); final int port = packet.getPort(); final long sender = ByteBuffer.allocate(BYTES_LONG).put(address.getAddress()).putInt(port).getLong(0); final byte[] data = Arrays.copyOf(buffer, packet.getLength()); order.receive(sender, consumer, (A) serializer.deserialize(data)); } } }
package seedu.address.ui; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.layout.FlowPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Region; import seedu.address.model.task.ReadOnlyTask; public class TaskCard extends UiPart<Region> { private static final String FXML = "TaskListCard.fxml"; @FXML private HBox cardPane; @FXML private Label id; @FXML private Label title; @FXML private Label dateTime; @FXML private Label content; @FXML private FlowPane tags; public TaskCard(ReadOnlyTask task, int displayedIndex) { super(FXML); title.setText(task.getTitle().fullTitle + " "); id.setText(displayedIndex + "."); dateTime.setText(task.getDateTime().toString()); content.setText(task.getContent().fullContent); if (task.getStatus().getStatus()) { title.setStyle("-fx-text-fill: green"); id.setStyle("-fx-text-fill: green"); dateTime.setStyle("-fx-text-fill: green"); content.setStyle("-fx-text-fill: green"); } initTags(task); } private void initTags(ReadOnlyTask task) { task.getTags().forEach(tag -> tags.getChildren().add(new Label(tag.tagName))); } }
package techreborn.init; import net.minecraft.block.Block; import net.minecraft.entity.EntityType; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IItemProvider; import reborncore.api.power.EnumPowerTier; import reborncore.api.tile.IUpgrade; import reborncore.common.powerSystem.TilePowerAcceptor; import reborncore.common.registration.RebornRegister; import reborncore.common.registration.config.ConfigRegistry; import techreborn.TechReborn; import techreborn.blocks.*; import techreborn.blocks.cable.BlockCable; import techreborn.blocks.generator.*; import techreborn.blocks.lighting.BlockLamp; import techreborn.blocks.storage.*; import techreborn.blocks.tier0.BlockIronAlloyFurnace; import techreborn.blocks.tier0.BlockIronFurnace; import techreborn.blocks.tier1.*; import techreborn.blocks.tier2.*; import techreborn.blocks.tier3.*; import techreborn.blocks.transformers.BlockHVTransformer; import techreborn.blocks.transformers.BlockLVTransformer; import techreborn.blocks.transformers.BlockMVTransformer; import techreborn.config.ConfigTechReborn; import techreborn.entities.EntityNukePrimed; import techreborn.items.DynamicCell; import techreborn.items.ItemUpgrade; import techreborn.utils.InitUtils; import javax.annotation.Nullable; @RebornRegister(TechReborn.MOD_ID) public class TRContent { // Misc Blocks public static Block COMPUTER_CUBE; public static Block NUKE; public static Block REFINED_IRON_FENCE; public static Block REINFORCED_GLASS; public static Block RUBBER_LEAVES; public static Block RUBBER_LOG; public static Block RUBBER_PLANK_SLAB; public static Block RUBBER_PLANK_STAIR; public static Block RUBBER_PLANKS; public static Block RUBBER_SAPLING; // Armor public static Item CLOAKING_DEVICE; public static Item LAPOTRONIC_ORBPACK; public static Item LITHIUM_ION_BATPACK; // Battery public static Item ENERGY_CRYSTAL; public static Item LAPOTRON_CRYSTAL; public static Item LAPOTRONIC_ORB; public static Item LITHIUM_ION_BATTERY; public static Item RED_CELL_BATTERY; // Tools public static Item TREE_TAP; public static Item WRENCH; public static Item BASIC_CHAINSAW; public static Item BASIC_DRILL; public static Item BASIC_JACKHAMMER; public static Item ELECTRIC_TREE_TAP; public static Item ADVANCED_CHAINSAW; public static Item ADVANCED_DRILL; public static Item ADVANCED_JACKHAMMER; public static Item ROCK_CUTTER; public static Item INDUSTRIAL_CHAINSAW; public static Item INDUSTRIAL_DRILL; public static Item INDUSTRIAL_JACKHAMMER; public static Item NANOSABER; public static Item OMNI_TOOL; public static Item DEBUG_TOOL; // Other public static Item FREQUENCY_TRANSMITTER; public static Item SCRAP_BOX; public static Item MANUAL; public static DynamicCell CELL; // Gem armor & tools @Nullable public static Item BRONZE_SWORD; @Nullable public static Item BRONZE_PICKAXE; @Nullable public static Item BRONZE_SPADE; @Nullable public static Item BRONZE_AXE; @Nullable public static Item BRONZE_HOE; @Nullable public static Item BRONZE_HELMET; @Nullable public static Item BRONZE_CHESTPLATE; @Nullable public static Item BRONZE_LEGGINGS; @Nullable public static Item BRONZE_BOOTS; @Nullable public static Item RUBY_SWORD; @Nullable public static Item RUBY_PICKAXE; @Nullable public static Item RUBY_SPADE; @Nullable public static Item RUBY_AXE; @Nullable public static Item RUBY_HOE; @Nullable public static Item RUBY_HELMET; @Nullable public static Item RUBY_CHESTPLATE; @Nullable public static Item RUBY_LEGGINGS; @Nullable public static Item RUBY_BOOTS; @Nullable public static Item SAPPHIRE_SWORD; @Nullable public static Item SAPPHIRE_PICKAXE; @Nullable public static Item SAPPHIRE_SPADE; @Nullable public static Item SAPPHIRE_AXE; @Nullable public static Item SAPPHIRE_HOE; @Nullable public static Item SAPPHIRE_HELMET; @Nullable public static Item SAPPHIRE_CHESTPLATE; @Nullable public static Item SAPPHIRE_LEGGINGS; @Nullable public static Item SAPPHIRE_BOOTS; @Nullable public static Item PERIDOT_SWORD; @Nullable public static Item PERIDOT_PICKAXE; @Nullable public static Item PERIDOT_SPADE; @Nullable public static Item PERIDOT_AXE; @Nullable public static Item PERIDOT_HOE; @Nullable public static Item PERIDOT_HELMET; @Nullable public static Item PERIDOT_CHESTPLATE; @Nullable public static Item PERIDOT_LEGGINGS; @Nullable public static Item PERIDOT_BOOTS; public static enum SolarPanels { BASIC(EnumPowerTier.MICRO, ConfigTechReborn.basicGenerationRateD, ConfigTechReborn.basicGenerationRateN), ADVANCED(EnumPowerTier.LOW, ConfigTechReborn.advancedGenerationRateD, ConfigTechReborn.advancedGenerationRateN), INDUSTRIAL(EnumPowerTier.MEDIUM, ConfigTechReborn.industrialGenerationRateD, ConfigTechReborn.industrialGenerationRateN), ULTIMATE(EnumPowerTier.HIGH, ConfigTechReborn.ultimateGenerationRateD, ConfigTechReborn.ultimateGenerationRateN), QUANTUM(EnumPowerTier.EXTREME, ConfigTechReborn.quantumGenerationRateD, ConfigTechReborn.quantumGenerationRateN), CREATIVE(EnumPowerTier.INFINITE, Integer.MAX_VALUE / 100, Integer.MAX_VALUE / 100); public final String name; public final Block block; // Generation of EU during Day public int generationRateD = 1; // Generation of EU during Night public int generationRateN = 0; // Internal EU storage of solar panel public int internalCapacity = 1000; public final EnumPowerTier powerTier; private SolarPanels(EnumPowerTier tier, int generationRateD, int generationRateN) { name = this.toString().toLowerCase(); powerTier = tier; block = new BlockSolarPanel(this); this.generationRateD = generationRateD; this.generationRateN = generationRateN; // Buffer for 2 mins of work internalCapacity = generationRateD * 2_400; InitUtils.setup(block, name + "_solar_panel"); } } public static enum Cables implements IItemProvider { COPPER(128, 12.0, true, EnumPowerTier.MEDIUM), TIN(32, 12.0, true, EnumPowerTier.LOW), GOLD(512, 12.0, true, EnumPowerTier.HIGH), HV(2048, 12.0, true, EnumPowerTier.EXTREME), GLASSFIBER(8192, 12.0, false, EnumPowerTier.INSANE), INSULATED_COPPER(128, 10.0, false, EnumPowerTier.MEDIUM), INSULATED_GOLD(512, 10.0, false, EnumPowerTier.HIGH), INSULATED_HV(2048, 10.0, false, EnumPowerTier.EXTREME), SUPERCONDUCTOR(Integer.MAX_VALUE / 4, 10.0, false, EnumPowerTier.INFINITE); public final String name; public final BlockCable block; public int transferRate; public int defaultTransferRate; public double cableThickness; public boolean canKill; public boolean defaultCanKill; public EnumPowerTier tier; Cables(int transferRate, double cableThickness, boolean canKill, EnumPowerTier tier) { name = this.toString().toLowerCase(); this.transferRate = transferRate; this.defaultTransferRate = transferRate; this.cableThickness = cableThickness / 2; this.canKill = canKill; this.defaultCanKill = canKill; this.tier = tier; this.block = new BlockCable(this); InitUtils.setup(block, name + "_cable"); } public ItemStack getStack() { return new ItemStack(block); } @Override public Item asItem() { return block.asItem(); } } public static enum Ores implements IItemProvider { BAUXITE, CINNABAR, COPPER, GALENA, IRIDIUM, LEAD, PERIDOT, PYRITE, RUBY, SAPPHIRE, SHELDONITE, SILVER, SODALITE, SPHALERITE, TIN, TUNGSTEN; public final String name; public final Block block; private Ores() { name = this.toString().toLowerCase(); block = new BlockOre(); InitUtils.setup(block, name + "_ore"); } @Override public Item asItem() { return block.asItem(); } } public static enum StorageBlocks implements IItemProvider { ALUMINUM, BRASS, BRONZE, CHROME, COPPER, ELECTRUM, INVAR, IRIDIUM, IRIDIUM_REINFORCED_STONE, IRIDIUM_REINFORCED_TUNGSTENSTEEL, LEAD, NICKEL, OSMIUM, PERIDOT, PLATINUM, RED_GARNET, REFINED_IRON, RUBY, SAPPHIRE, SILVER, STEEL, TIN, TITANIUM, TUNGSTEN, TUNGSTENSTEEL, YELLOW_GARNET, ZINC; public final String name; public final Block block; private StorageBlocks() { name = this.toString().toLowerCase(); block = new BlockStorage(); InitUtils.setup(block, name + "_storage_block"); } @Override public Item asItem() { return block.asItem(); } } public static enum MachineBlocks { BASIC(1020 / 25), ADVANCED(1700 / 25), INDUSTRIAL(2380 / 25); public final String name; public final Block frame; public final Block casing; private MachineBlocks(int casingHeatCapacity) { name = this.toString().toLowerCase(); frame = new BlockMachineFrame(); InitUtils.setup(frame, name + "_machine_frame"); casing = new BlockMachineCasing(casingHeatCapacity); InitUtils.setup(casing, name + "_machine_casing"); } public Block getFrame() { return frame; } public Block getCasing() { return casing; } } public static enum Machine implements IItemProvider { ALLOY_SMELTER(new BlockAlloySmelter()), ASSEMBLY_MACHINE(new BlockAssemblingMachine()), AUTO_CRAFTING_TABLE(new BlockAutoCraftingTable()), CHEMICAL_REACTOR(new BlockChemicalReactor()), COMPRESSOR(new BlockCompressor()), DISTILLATION_TOWER(new BlockDistillationTower()), EXTRACTOR(new BlockExtractor()), FLUID_REPLICATOR(new BlockFluidReplicator()), GRINDER(new BlockGrinder()), ELECTRIC_FURNACE(new BlockElectricFurnace()), IMPLOSION_COMPRESSOR(new BlockImplosionCompressor()), INDUSTRIAL_BLAST_FURNACE(new BlockIndustrialBlastFurnace()), INDUSTRIAL_CENTRIFUGE(new BlockIndustrialCentrifuge()), INDUSTRIAL_ELECTROLYZER(new BlockIndustrialElectrolyzer()), INDUSTRIAL_GRINDER(new BlockIndustrialGrinder()), INDUSTRIAL_SAWMILL(new BlockIndustrialSawmill()), IRON_ALLOY_FURNACE(new BlockIronAlloyFurnace()), IRON_FURNACE(new BlockIronFurnace()), MATTER_FABRICATOR(new BlockMatterFabricator()), RECYCLER(new BlockRecycler()), ROLLING_MACHINE(new BlockRollingMachine()), SCRAPBOXINATOR(new BlockScrapboxinator()), VACUUM_FREEZER(new BlockVacuumFreezer()), DIESEL_GENERATOR(new BlockDieselGenerator()), DRAGON_EGG_SYPHON(new BlockDragonEggSyphon()), FUSION_COIL(new BlockFusionCoil()), FUSION_CONTROL_COMPUTER(new BlockFusionControlComputer()), GAS_TURBINE(new BlockGasTurbine()), LIGHTNING_ROD(new BlockLightningRod()), MAGIC_ENERGY_ABSORBER (new BlockMagicEnergyAbsorber()), MAGIC_ENERGY_CONVERTER(new BlockMagicEnergyConverter()), PLASMA_GENERATOR(new BlockPlasmaGenerator()), SEMI_FLUID_GENERATOR(new BlockSemiFluidGenerator()), SOLID_FUEL_GENERATOR(new BlockSolidFuelGenerator()), THERMAL_GENERATOR(new BlockThermalGenerator()), WATER_MILL(new BlockWaterMill()), WIND_MILL(new BlockWindMill()), CREATIVE_QUANTUM_CHEST(new BlockCreativeQuantumChest()), CREATIVE_QUANTUM_TANK(new BlockCreativeQuantumTank()), DIGITAL_CHEST(new BlockDigitalChest()), QUANTUM_CHEST(new BlockQuantumChest()), QUANTUM_TANK(new BlockQuantumTank()), ADJUSTABLE_SU(new BlockAdjustableSU()), CHARGE_O_MAT(new BlockChargeOMat()), INTERDIMENSIONAL_SU(new BlockInterdimensionalSU()), LAPOTRONIC_SU(new BlockLapotronicSU()), LSU_STORAGE(new BlockLSUStorage()), LOW_VOLTAGE_SU(new BlockLowVoltageSU()), MEDIUM_VOLTAGE_SU(new BlockMediumVoltageSU()), HIGH_VOLTAGE_SU(new BlockHighVoltageSU()), LV_TRANSFORMER(new BlockLVTransformer()), MV_TRANSFORMER(new BlockMVTransformer()), HV_TRANSFORMER(new BlockHVTransformer()), ALARM(new BlockAlarm()), CHUNK_LOADER(new BlockChunkLoader()), LAMP_INCANDESCENT(new BlockLamp(14, 4, 0.625, 0.25)), LAMP_LED(new BlockLamp(15, 1, 0.0625, 0.125)), PLAYER_DETECTOR(new BlockPlayerDetector()); public final String name; public final Block block; private <B extends Block> Machine(B block) { this.name = this.toString().toLowerCase(); this.block = block; InitUtils.setup(block, name); } public ItemStack getStack() { return new ItemStack(block); } @Override public Item asItem() { return block.asItem(); } } public static enum Dusts implements IItemProvider { ALMANDINE, ALUMINUM, ANDESITE, ANDRADITE, ASHES, BASALT, BAUXITE, BRASS, BRONZE, CALCITE, CHARCOAL, CHROME, CINNABAR, CLAY, COAL, COPPER, DARK_ASHES, DIAMOND, DIORITE, ELECTRUM, EMERALD, ENDER_EYE, ENDER_PEARL, ENDSTONE, FLINT, GALENA, GOLD, GRANITE, GROSSULAR, INVAR, IRON, LAZURITE, LEAD, MAGNESIUM, MANGANESE, MARBLE, NETHERRACK, NICKEL, OBSIDIAN, OLIVINE, PERIDOT, PHOSPHOROUS, PLATINUM, PYRITE, PYROPE, RED_GARNET, RUBY, SALTPETER, SAPPHIRE, SAW, SILVER, SODALITE, SPESSARTINE, SPHALERITE, STEEL, SULFUR, TIN, TITANIUM, TUNGSTEN, UVAROVITE, YELLOW_GARNET, ZINC; public final String name; public final Item item; private Dusts() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_dust"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum SmallDusts implements IItemProvider { ALMANDINE, ALUMINUM, ANDESITE, ANDRADITE, ASHES, BASALT, BAUXITE, BRASS, BRONZE, CALCITE, CHARCOAL, CHROME, CINNABAR, CLAY, COAL, COPPER, DARK_ASHES, DIAMOND, DIORITE, ELECTRUM, EMERALD, ENDER_EYE, ENDER_PEARL, ENDSTONE, FLINT, GALENA, GLOWSTONE, GOLD, GRANITE, GROSSULAR, INVAR, IRON, LAZURITE, LEAD, MAGNESIUM, MANGANESE, MARBLE, NETHERRACK, NICKEL, OBSIDIAN, OLIVINE, PERIDOT, PHOSPHOROUS, PLATINUM, PYRITE, PYROPE, REDSTONE, RED_GARNET, RUBY, SALTPETER, SAPPHIRE, SAW, SILVER, SODALITE, SPESSARTINE, SPHALERITE, STEEL, SULFUR, TIN, TITANIUM, TUNGSTEN, UVAROVITE, YELLOW_GARNET, ZINC; public final String name; public final Item item; private SmallDusts() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_small_dust"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum Gems implements IItemProvider { PERIDOT, RED_GARNET, RUBY, SAPPHIRE, YELLOW_GARNET; public final String name; public final Item item; private Gems() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_gem"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum Ingots implements IItemProvider { ADVANCED_ALLOY, ALUMINUM, BRASS, BRONZE, CHROME, COPPER, ELECTRUM, HOT_TUNGSTENSTEEL, INVAR, IRIDIUM_ALLOY, IRIDIUM, LEAD, MIXED_METAL, NICKEL, PLATINUM, REFINED_IRON, SILVER, STEEL, TIN, TITANIUM, TUNGSTEN, TUNGSTENSTEEL, ZINC; public final String name; public final Item item; private Ingots() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_ingot"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum Nuggets implements IItemProvider { ALUMINUM, BRASS, BRONZE, CHROME, COPPER, DIAMOND, ELECTRUM, HOT_TUNGSTENSTEEL, INVAR, IRIDIUM, LEAD, NICKEL, PLATINUM, REFINED_IRON, SILVER, STEEL, TIN, TITANIUM, TUNGSTEN, TUNGSTENSTEEL, ZINC; public final String name; public final Item item; private Nuggets() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_nugget"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum Parts implements IItemProvider { CARBON_FIBER, CARBON_MESH, ELECTRONIC_CIRCUIT, ADVANCED_CIRCUIT, INDUSTRIAL_CIRCUIT, MACHINE_PARTS, DIGITAL_DISPLAY, DATA_STORAGE_CORE, DATA_STORAGE_CHIP, ENERGY_FLOW_CHIP, SUPERCONDUCTOR, DIAMOND_SAW_BLADE, DIAMOND_GRINDING_HEAD, TUNGSTEN_GRINDING_HEAD, CUPRONICKEL_HEATING_COIL, KANTHAL_HEATING_COIL, NICHROME_HEATING_COIL, NEUTRON_REFLECTOR, THICK_NEUTRON_REFLECTOR, IRIDIUM_NEUTRON_REFLECTOR //java vars can't start with numbers, so these get suffixes , WATER_COOLANT_CELL_10K, WATER_COOLANT_CELL_30K, WATER_COOLANT_CELL_60K, HELIUM_COOLANT_CELL_60K, HELIUM_COOLANT_CELL_360K, HELIUM_COOLANT_CELL_180K, NAK_COOLANT_CELL_60K, NAK_COOLANT_CELL_180K, NAK_COOLANT_CELL_360K, RUBBER, SAP, SCRAP, UU_MATTER; public final String name; public final Item item; private Parts() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } public static enum Plates implements IItemProvider { ADVANCED_ALLOY, ALUMINUM, BRASS, BRONZE, CARBON, COAL, COPPER, DIAMOND, ELECTRUM, EMERALD, GOLD, INVAR, IRIDIUM_ALLOY, IRIDIUM, IRON, LAPIS, LAZURITE, LEAD, MAGNALIUM, NICKEL, OBSIDIAN, PERIDOT, PLATINUM, RED_GARNET, REDSTONE, REFINED_IRON, RUBY, SAPPHIRE, SILICON, SILVER, STEEL, TIN, TITANIUM, TUNGSTEN, TUNGSTENSTEEL, WOOD, YELLOW_GARNET, ZINC; public final String name; public final Item item; private Plates() { name = this.toString().toLowerCase(); item = new Item(new Item.Properties().group(TechReborn.ITEMGROUP)); InitUtils.setup(item, name + "_plate"); } public ItemStack getStack() { return new ItemStack(item); } public ItemStack getStack(int amount) { return new ItemStack(item, amount); } @Override public Item asItem() { return item; } } @ConfigRegistry(config = "items", category = "upgrades", key = "overclcoker_speed", comment = "Overclocker behavior speed multipiler") public static double overclockerSpeed = 0.25; @ConfigRegistry(config = "items", category = "upgrades", key = "overclcoker_power", comment = "Overclocker behavior power multipiler") public static double overclockerPower = 0.75; @ConfigRegistry(config = "items", category = "upgrades", key = "energy_storage", comment = "Energy storage behavior extra power") public static double energyStoragePower = 40_000; public static enum Upgrades implements IItemProvider { OVERCLOCKER((tile, handler, stack) -> { TilePowerAcceptor powerAcceptor = null; if (tile instanceof TilePowerAcceptor) { powerAcceptor = (TilePowerAcceptor) tile; } handler.addSpeedMulti(overclockerSpeed); handler.addPowerMulti(overclockerPower); if (powerAcceptor != null) { powerAcceptor.extraPowerInput += powerAcceptor.getMaxInput(); powerAcceptor.extraPowerStoage += powerAcceptor.getBaseMaxPower(); } }), TRANSFORMER((tile, handler, stack) -> { TilePowerAcceptor powerAcceptor = null; if (tile instanceof TilePowerAcceptor) { powerAcceptor = (TilePowerAcceptor) tile; } if (powerAcceptor != null) { powerAcceptor.extraTier += 1; } }), ENERGY_STORAGE((tile, handler, stack) -> { TilePowerAcceptor powerAcceptor = null; if (tile instanceof TilePowerAcceptor) { powerAcceptor = (TilePowerAcceptor) tile; } if (powerAcceptor != null) { powerAcceptor.extraPowerStoage += energyStoragePower; } }); public String name; public Item item; Upgrades(IUpgrade upgrade) { name = this.toString().toLowerCase(); item = new ItemUpgrade(name, upgrade); InitUtils.setup(item, name + "_upgrade"); } @Override public Item asItem() { return item; } } public static EntityType<EntityNukePrimed> ENTITY_NUKE; }
package org.pentaho.di.core.database; import java.io.StringReader; import java.sql.BatchUpdateException; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Savepoint; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import java.util.List; import java.util.Map; import java.util.Properties; import javax.sql.DataSource; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.DBCache; import org.pentaho.di.core.DBCacheEntry; import org.pentaho.di.core.ProgressMonitorListener; import org.pentaho.di.core.Result; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.database.map.DatabaseConnectionMap; import org.pentaho.di.core.encryption.Encr; import org.pentaho.di.core.exception.KettleDatabaseBatchException; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.logging.DefaultLogLevel; import org.pentaho.di.core.logging.LogChannel; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.logging.LogLevel; import org.pentaho.di.core.logging.LogStatus; import org.pentaho.di.core.logging.LogTableField; import org.pentaho.di.core.logging.LogTableInterface; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.logging.LoggingObjectType; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.repository.ObjectRevision; import org.pentaho.di.repository.RepositoryDirectory; /** * Database handles the process of connecting to, reading from, writing to and updating databases. * The database specific parameters are defined in DatabaseInfo. * * @author Matt * @since 05-04-2003 * */ public class Database implements VariableSpace, LoggingObjectInterface { private static Class<?> PKG = Database.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private DatabaseMeta databaseMeta; private int rowlimit; private int commitsize; private Connection connection; private Statement sel_stmt; private PreparedStatement pstmt; private PreparedStatement prepStatementLookup; private PreparedStatement prepStatementUpdate; private PreparedStatement prepStatementInsert; private PreparedStatement pstmt_seq; private CallableStatement cstmt; // private ResultSetMetaData rsmd; private DatabaseMetaData dbmd; private RowMetaInterface rowMeta; private int written; private LogChannelInterface log; private LoggingObjectInterface parentLoggingObject; /** * Number of times a connection was opened using this object. * Only used in the context of a database connection map */ private int opened; /** * The copy is equal to opened at the time of creation. */ private int copy; private String connectionGroup; private String partitionId; private VariableSpace variables = new Variables(); private LogLevel logLevel = DefaultLogLevel.getLogLevel(); private String containerObjectId; /** * Construct a new Database Connection * @param databaseMeta The Database Connection Info to construct the connection with. * @deprecated Please specify the parent object so that we can see which object is initiating a database connection */ public Database(DatabaseMeta databaseMeta) { this.parentLoggingObject = null; this.databaseMeta = databaseMeta; shareVariablesWith(databaseMeta); // In this case we don't have the parent object, so we don't know which object makes the connection. // We also don't know what log level to attach to it, so we have to stick to the default // As such, this constructor is @deprecated. log=new LogChannel(this); logLevel = log.getLogLevel(); containerObjectId = log.getContainerObjectId(); pstmt = null; rowMeta = null; dbmd = null; rowlimit=0; written=0; if(log.isDetailed()) log.logDetailed("New database connection defined"); } /** * Construct a new Database Connection * @param databaseMeta The Database Connection Info to construct the connection with. */ public Database(LoggingObjectInterface parentObject, DatabaseMeta databaseMeta) { this.parentLoggingObject = parentObject; this.databaseMeta = databaseMeta; shareVariablesWith(databaseMeta); log=new LogChannel(this, parentObject); this.containerObjectId = log.getContainerObjectId(); this.logLevel = log.getLogLevel(); pstmt = null; rowMeta = null; dbmd = null; rowlimit=0; written=0; if(log.isDetailed()) log.logDetailed("New database connection defined"); } public boolean equals(Object obj) { Database other = (Database) obj; return other.databaseMeta.equals(other.databaseMeta); } /** * Allows for the injection of a "life" connection, generated by a piece of software outside of Kettle. * @param connection */ public void setConnection(Connection connection) { this.connection = connection; } /** * @return Returns the connection. */ public Connection getConnection() { return connection; } /** * Set the maximum number of records to retrieve from a query. * @param rows */ public void setQueryLimit(int rows) { rowlimit = rows; } /** * @return Returns the prepStatementInsert. */ public PreparedStatement getPrepStatementInsert() { return prepStatementInsert; } /** * @return Returns the prepStatementLookup. */ public PreparedStatement getPrepStatementLookup() { return prepStatementLookup; } /** * @return Returns the prepStatementUpdate. */ public PreparedStatement getPrepStatementUpdate() { return prepStatementUpdate; } /** * Open the database connection. * @throws KettleDatabaseException if something went wrong. */ public void connect() throws KettleDatabaseException { connect(null); } /** * Open the database connection. * @param partitionId the partition ID in the cluster to connect to. * @throws KettleDatabaseException if something went wrong. */ public void connect(String partitionId) throws KettleDatabaseException { connect(null, partitionId); } public synchronized void connect(String group, String partitionId) throws KettleDatabaseException { // Before anything else, let's see if we already have a connection defined for this group/partition! // The group is called after the thread-name of the transformation or job that is running // The name of that threadname is expected to be unique (it is in Kettle) // So the deal is that if there is another thread using that, we go for it. if (!Const.isEmpty(group)) { this.connectionGroup = group; this.partitionId = partitionId; DatabaseConnectionMap map = DatabaseConnectionMap.getInstance(); // Try to find the connection for the group Database lookup = map.getDatabase(group, partitionId, this); if (lookup==null) // We already opened this connection for the partition & database in this group { // Do a normal connect and then store this database object for later re-use. normalConnect(partitionId); opened++; copy = opened; map.storeDatabase(group, partitionId, this); } else { connection = lookup.getConnection(); lookup.setOpened(lookup.getOpened()+1); // if this counter hits 0 again, close the connection. copy = lookup.getOpened(); } } else { // Proceed with a normal connect normalConnect(partitionId); } } /** * Open the database connection. * @param partitionId the partition ID in the cluster to connect to. * @throws KettleDatabaseException if something went wrong. */ public void normalConnect(String partitionId) throws KettleDatabaseException { if (databaseMeta==null) { throw new KettleDatabaseException("No valid database connection defined!"); } try { // First see if we use connection pooling... if ( databaseMeta.isUsingConnectionPool() && // default = false for backward compatibility databaseMeta.getAccessType()!=DatabaseMeta.TYPE_ACCESS_JNDI // JNDI does pooling on it's own. ) { try { this.connection = ConnectionPoolUtil.getConnection(log, databaseMeta, partitionId); } catch (Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } else { connectUsingClass(databaseMeta.getDriverClass(), partitionId ); if(log.isDetailed()) log.logDetailed("Connected to database."); // See if we need to execute extra SQL statemtent... String sql = environmentSubstitute( databaseMeta.getConnectSQL() ); // only execute if the SQL is not empty, null and is not just a bunch of spaces, tabs, CR etc. if (!Const.isEmpty(sql) && !Const.onlySpaces(sql)) { execStatements(sql); if(log.isDetailed()) log.logDetailed("Executed connect time SQL statements:"+Const.CR+sql); } } } catch(Exception e) { throw new KettleDatabaseException("Error occured while trying to connect to the database", e); } } /** * Initialize by getting the connection from a javax.sql.DataSource. This method uses the * DataSourceProviderFactory to get the provider of DataSource objects. * @param dataSourceName * @throws KettleDatabaseException */ private void initWithNamedDataSource(String dataSourceName) throws KettleDatabaseException { connection = null; DataSource dataSource = DataSourceProviderFactory.getDataSourceProviderInterface().getNamedDataSource(dataSourceName); if (dataSource != null) { try { connection = dataSource.getConnection(); } catch (SQLException e) { throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName + " : " + e.getMessage()); //$NON-NLS-1$ } if (connection == null) { throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName); //$NON-NLS-1$ } } else { throw new KettleDatabaseException( "Invalid JNDI connection "+ dataSourceName); //$NON-NLS-1$ } } /** * Connect using the correct classname * @param classname for example "org.gjt.mm.mysql.Driver" * @return true if the connect was succesfull, false if something went wrong. */ private void connectUsingClass(String classname, String partitionId) throws KettleDatabaseException { // Install and load the jdbc Driver // first see if this is a JNDI connection if( databaseMeta.getAccessType() == DatabaseMeta.TYPE_ACCESS_JNDI ) { initWithNamedDataSource( environmentSubstitute(databaseMeta.getDatabaseName()) ); return; } try { Class.forName(classname); } catch(NoClassDefFoundError e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(ClassNotFoundException e) { throw new KettleDatabaseException("Exception while loading class", e); } catch(Exception e) { throw new KettleDatabaseException("Exception while loading class", e); } try { String url; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { url = environmentSubstitute(databaseMeta.getURL(partitionId)); } else { url = environmentSubstitute(databaseMeta.getURL()); } String clusterUsername=null; String clusterPassword=null; if (databaseMeta.isPartitioned() && !Const.isEmpty(partitionId)) { // Get the cluster information... PartitionDatabaseMeta partition = databaseMeta.getPartitionMeta(partitionId); if (partition!=null) { clusterUsername = partition.getUsername(); clusterPassword = Encr.decryptPasswordOptionallyEncrypted(partition.getPassword()); } } String username; String password; if (!Const.isEmpty(clusterUsername)) { username = clusterUsername; password = clusterPassword; } else { username = environmentSubstitute(databaseMeta.getUsername()); password = Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(databaseMeta.getPassword())); } if (databaseMeta.supportsOptionsInURL()) { if (!Const.isEmpty(username) || !Const.isEmpty(password)) { // also allow for empty username with given password, in this case username must be given with one space connection = DriverManager.getConnection(url, Const.NVL(username, " "), Const.NVL(password, "")); } else { // Perhaps the username is in the URL or no username is required... connection = DriverManager.getConnection(url); } } else { Properties properties = databaseMeta.getConnectionProperties(); if (!Const.isEmpty(username)) properties.put("user", username); if (!Const.isEmpty(password)) properties.put("password", password); connection = DriverManager.getConnection(url, properties); } } catch(SQLException e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } catch(Throwable e) { throw new KettleDatabaseException("Error connecting to database: (using class "+classname+")", e); } } /** * Disconnect from the database and close all open prepared statements. */ public synchronized void disconnect() { try { if (connection==null) { return ; // Nothing to do... } if (connection.isClosed()) { return ; // Nothing to do... } if (pstmt !=null) { pstmt.close(); pstmt=null; } if (prepStatementLookup!=null) { prepStatementLookup.close(); prepStatementLookup=null; } if (prepStatementInsert!=null) { prepStatementInsert.close(); prepStatementInsert=null; } if (prepStatementUpdate!=null) { prepStatementUpdate.close(); prepStatementUpdate=null; } if (pstmt_seq!=null) { pstmt_seq.close(); pstmt_seq=null; } // See if there are other steps using this connection in a connection group. // If so, we will hold commit & connection close until then. if (!Const.isEmpty(connectionGroup)) { return; } else { if (!isAutoCommit()) // Do we really still need this commit?? { commit(); } } closeConnectionOnly(); } catch(SQLException ex) { log.logError("Error disconnecting from database:"+Const.CR+ex.getMessage()); log.logError(Const.getStackTracker(ex)); } catch(KettleDatabaseException dbe) { log.logError("Error disconnecting from database:"+Const.CR+dbe.getMessage()); log.logError(Const.getStackTracker(dbe)); } } /** * Only for unique connections usage, typically you use disconnect() to disconnect() from the database. * @throws KettleDatabaseException in case there is an error during connection close. */ public synchronized void closeConnectionOnly() throws KettleDatabaseException { try { if (connection!=null) { connection.close(); if (!databaseMeta.isUsingConnectionPool()) { connection=null; } } if(log.isDetailed()) log.logDetailed("Connection to database closed!"); } catch(SQLException e) { throw new KettleDatabaseException("Error disconnecting from database '"+toString()+"'", e); } } /** * Cancel the open/running queries on the database connection * @throws KettleDatabaseException */ public void cancelQuery() throws KettleDatabaseException { cancelStatement(pstmt); cancelStatement(sel_stmt); } /** * Cancel an open/running SQL statement * @param statement the statement to cancel * @throws KettleDatabaseException */ public void cancelStatement(Statement statement) throws KettleDatabaseException { try { if (statement!=null) { statement.cancel(); } if(log.isDebug()) log.logDebug("Statement canceled!"); } catch(SQLException ex) { throw new KettleDatabaseException("Error cancelling statement", ex); } } /** * Specify after how many rows a commit needs to occur when inserting or updating values. * @param commsize The number of rows to wait before doing a commit on the connection. */ public void setCommit(int commsize) { commitsize=commsize; String onOff = (commitsize<=0?"on":"off"); try { connection.setAutoCommit(commitsize<=0); if(log.isDetailed()) log.logDetailed("Auto commit "+onOff); } catch(Exception e) { log.logError("Can't turn auto commit "+onOff); } } public void setAutoCommit(boolean useAutoCommit) throws KettleDatabaseException { try { connection.setAutoCommit(useAutoCommit); } catch (SQLException e) { if (useAutoCommit) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToEnableAutoCommit", toString())); } else { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToDisableAutoCommit", toString())); } } } /** * Perform a commit the connection if this is supported by the database */ public void commit() throws KettleDatabaseException { commit(false); } public void commit(boolean force) throws KettleDatabaseException { try { // Don't do the commit, wait until the end of the transformation. // When the last database copy (opened counter) is about to be closed, we do a commit // There is one catch, we need to catch the rollback // The transformation will stop everything and then we'll do the rollback. // The flag is in "performRollback", private only if (!Const.isEmpty(connectionGroup) && !force) { return; } if (getDatabaseMetaData().supportsTransactions()) { if (log.isDebug()) log.logDebug("Commit on database connection ["+toString()+"]"); connection.commit(); } else { if(log.isDetailed()) log.logDetailed("No commit possible on database connection ["+toString()+"]"); } } catch(Exception e) { if (databaseMeta.supportsEmptyTransactions()) throw new KettleDatabaseException("Error comitting connection", e); } } public void rollback() throws KettleDatabaseException { rollback(false); } public void rollback(boolean force) throws KettleDatabaseException { try { if (!Const.isEmpty(connectionGroup) && !force) { return; // Will be handled by Trans --> endProcessing() } if (getDatabaseMetaData().supportsTransactions()) { if (connection!=null) { if (log.isDebug()) log.logDebug("Rollback on database connection ["+toString()+"]"); connection.rollback(); } } else { if(log.isDetailed()) log.logDetailed("No rollback possible on database connection ["+toString()+"]"); } } catch(SQLException e) { throw new KettleDatabaseException("Error performing rollback on connection", e); } } /** * Prepare inserting values into a table, using the fields & values in a Row * @param rowMeta The row metadata to determine which values need to be inserted * @param table The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(RowMetaInterface rowMeta, String tableName) throws KettleDatabaseException { prepareInsert(rowMeta, null, tableName); } /** * Prepare inserting values into a table, using the fields & values in a Row * @param rowMeta The metadata row to determine which values need to be inserted * @param schemaName The name of the schema in which we want to insert rows * @param tableName The name of the table in which we want to insert rows * @throws KettleDatabaseException if something went wrong. */ public void prepareInsert(RowMetaInterface rowMeta, String schemaName, String tableName) throws KettleDatabaseException { if (rowMeta.size()==0) { throw new KettleDatabaseException("No fields in row, can't insert!"); } String ins = getInsertStatement(schemaName, tableName, rowMeta); if(log.isDetailed()) log.logDetailed("Preparing statement: "+Const.CR+ins); prepStatementInsert=prepareSQL(ins); } /** * Prepare a statement to be executed on the database. (does not return generated keys) * @param sql The SQL to be prepared * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql) throws KettleDatabaseException { return prepareSQL(sql, false); } /** * Prepare a statement to be executed on the database. * @param sql The SQL to be prepared * @param returnKeys set to true if you want to return generated keys from an insert statement * @return The PreparedStatement object. * @throws KettleDatabaseException */ public PreparedStatement prepareSQL(String sql, boolean returnKeys) throws KettleDatabaseException { try { if (returnKeys) { return connection.prepareStatement(databaseMeta.stripCR(sql), Statement.RETURN_GENERATED_KEYS); } else { return connection.prepareStatement(databaseMeta.stripCR(sql)); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't prepare statement:"+Const.CR+sql, ex); } } public void closeLookup() throws KettleDatabaseException { closePreparedStatement(pstmt); pstmt=null; } public void closePreparedStatement(PreparedStatement ps) throws KettleDatabaseException { if (ps!=null) { try { ps.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing prepared statement", e); } } } public void closeInsert() throws KettleDatabaseException { if (prepStatementInsert!=null) { try { prepStatementInsert.close(); prepStatementInsert = null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing insert prepared statement.", e); } } } public void closeUpdate() throws KettleDatabaseException { if (prepStatementUpdate!=null) { try { prepStatementUpdate.close(); prepStatementUpdate=null; } catch(SQLException e) { throw new KettleDatabaseException("Error closing update prepared statement.", e); } } } public void setValues(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, pstmt); } public void setValues(RowMetaAndData row) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData()); } public void setValuesInsert(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementInsert); } public void setValuesInsert(RowMetaAndData row) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData(), prepStatementInsert); } public void setValuesUpdate(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementUpdate); } public void setValuesLookup(RowMetaInterface rowMeta, Object[] data) throws KettleDatabaseException { setValues(rowMeta, data, prepStatementLookup); } public void setProcValues(RowMetaInterface rowMeta, Object[] data, int argnrs[], String argdir[], boolean result) throws KettleDatabaseException { int pos; if (result) pos=2; else pos=1; for (int i=0;i<argnrs.length;i++) { if (argdir[i].equalsIgnoreCase("IN") || argdir[i].equalsIgnoreCase("INOUT")) { ValueMetaInterface valueMeta = rowMeta.getValueMeta(argnrs[i]); Object value = data[argnrs[i]]; setValue(cstmt, valueMeta, value, pos); pos++; } else { pos++; //next parameter when OUT } } } public void setValue(PreparedStatement ps, ValueMetaInterface v, Object object, int pos) throws KettleDatabaseException { String debug = ""; try { switch(v.getType()) { case ValueMetaInterface.TYPE_NUMBER : if (!v.isNull(object)) { debug="Number, not null, getting number from value"; double num = v.getNumber(object).doubleValue(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { debug="Number, rounding to precision ["+v.getPrecision()+"]"; num = Const.round(num, v.getPrecision()); } debug="Number, setting ["+num+"] on position #"+pos+" of the prepared statement"; ps.setDouble(pos, num); } else { ps.setNull(pos, java.sql.Types.DOUBLE); } break; case ValueMetaInterface.TYPE_INTEGER: debug="Integer"; if (!v.isNull(object)) { if (databaseMeta.supportsSetLong()) { ps.setLong(pos, v.getInteger(object).longValue() ); } else { double d = v.getNumber(object).doubleValue(); if (databaseMeta.supportsFloatRoundingOnUpdate() && v.getPrecision()>=0) { ps.setDouble(pos, d ); } else { ps.setDouble(pos, Const.round( d, v.getPrecision() ) ); } } } else { ps.setNull(pos, java.sql.Types.INTEGER); } break; case ValueMetaInterface.TYPE_STRING : debug="String"; if (v.getLength()<DatabaseMeta.CLOB_LENGTH) { if (!v.isNull(object)) { ps.setString(pos, v.getString(object)); } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } else { if (!v.isNull(object)) { String string = v.getString(object); int maxlen = databaseMeta.getMaxTextFieldLength(); int len = string.length(); // Take the last maxlen characters of the string... int begin = len - maxlen; if (begin<0) begin=0; // Get the substring! String logging = string.substring(begin); if (databaseMeta.supportsSetCharacterStream()) { StringReader sr = new StringReader(logging); ps.setCharacterStream(pos, sr, logging.length()); } else { ps.setString(pos, logging); } } else { ps.setNull(pos, java.sql.Types.VARCHAR); } } break; case ValueMetaInterface.TYPE_DATE : debug="Date"; if (!v.isNull(object)) { long dat = v.getInteger(object).longValue(); // converts using Date.getTime() if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { // Convert to DATE! java.sql.Date ddate = new java.sql.Date(dat); ps.setDate(pos, ddate); } else { java.sql.Timestamp sdate = new java.sql.Timestamp(dat); ps.setTimestamp(pos, sdate); } } else { if(v.getPrecision()==1 || !databaseMeta.supportsTimeStampToDateConversion()) { ps.setNull(pos, java.sql.Types.DATE); } else { ps.setNull(pos, java.sql.Types.TIMESTAMP); } } break; case ValueMetaInterface.TYPE_BOOLEAN: debug="Boolean"; if (databaseMeta.supportsBooleanDataType()) { if (!v.isNull(object)) { ps.setBoolean(pos, v.getBoolean(object).booleanValue()); } else { ps.setNull(pos, java.sql.Types.BOOLEAN); } } else { if (!v.isNull(object)) { ps.setString(pos, v.getBoolean(object).booleanValue()?"Y":"N"); } else { ps.setNull(pos, java.sql.Types.CHAR); } } break; case ValueMetaInterface.TYPE_BIGNUMBER: debug="BigNumber"; if (!v.isNull(object)) { ps.setBigDecimal(pos, v.getBigNumber(object)); } else { ps.setNull(pos, java.sql.Types.DECIMAL); } break; case ValueMetaInterface.TYPE_BINARY: debug="Binary"; if (!v.isNull(object)) { ps.setBytes(pos, v.getBinary(object)); } else { ps.setNull(pos, java.sql.Types.BINARY); } break; default: debug="default"; // placeholder ps.setNull(pos, java.sql.Types.VARCHAR); break; } } catch(SQLException ex) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+v.toString()+"] on prepared statement ("+debug+")"+Const.CR+ex.toString(), ex); } catch(Exception e) { throw new KettleDatabaseException("Error setting value #"+pos+" ["+(v==null?"NULL":v.toString())+"] on prepared statement ("+debug+")"+Const.CR+e.toString(), e); } } public void setValues(RowMetaAndData row, PreparedStatement ps) throws KettleDatabaseException { setValues(row.getRowMeta(), row.getData(), ps); } public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps) throws KettleDatabaseException { // now set the values in the row! for (int i=0;i<rowMeta.size();i++) { ValueMetaInterface v = rowMeta.getValueMeta(i); Object object = data[i]; try { setValue(ps, v, object, i+1); } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+rowMeta, e); } } } /** * Sets the values of the preparedStatement pstmt. * @param rowMeta * @param data */ public void setValues(RowMetaInterface rowMeta, Object[] data, PreparedStatement ps, int ignoreThisValueIndex) throws KettleDatabaseException { // now set the values in the row! int index=0; for (int i=0;i<rowMeta.size();i++) { if (i!=ignoreThisValueIndex) { ValueMetaInterface v = rowMeta.getValueMeta(i); Object object = data[i]; try { setValue(ps, v, object, index+1); index++; } catch(KettleDatabaseException e) { throw new KettleDatabaseException("offending row : "+rowMeta, e); } } } } /** * @param ps The prepared insert statement to use * @return The generated keys in auto-increment fields * @throws KettleDatabaseException in case something goes wrong retrieving the keys. */ public RowMetaAndData getGeneratedKeys(PreparedStatement ps) throws KettleDatabaseException { ResultSet keys = null; try { keys=ps.getGeneratedKeys(); // 1 row of keys ResultSetMetaData resultSetMetaData = keys.getMetaData(); RowMetaInterface rowMeta = getRowInfo(resultSetMetaData, false, false); return new RowMetaAndData(rowMeta, getRow(keys, resultSetMetaData, rowMeta)); } catch(Exception ex) { throw new KettleDatabaseException("Unable to retrieve key(s) from auto-increment field(s)", ex); } finally { if (keys!=null) { try { keys.close(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset of auto-generated keys", e); } } } } public Long getNextSequenceValue(String sequenceName, String keyfield) throws KettleDatabaseException { return getNextSequenceValue(null, sequenceName, keyfield); } public Long getNextSequenceValue(String schemaName, String sequenceName, String keyfield) throws KettleDatabaseException { Long retval=null; String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); try { if (pstmt_seq==null) { pstmt_seq=connection.prepareStatement(databaseMeta.getSeqNextvalSQL(databaseMeta.stripCR(schemaSequence))); } ResultSet rs=null; try { rs = pstmt_seq.executeQuery(); if (rs.next()) { retval = Long.valueOf( rs.getLong(1) ); } } finally { if ( rs != null ) rs.close(); } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to get next value for sequence : "+schemaSequence, ex); } return retval; } public void insertRow(String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException { insertRow(null, tableName, fields, data); } public void insertRow(String schemaName, String tableName, RowMetaInterface fields, Object[] data) throws KettleDatabaseException { prepareInsert(fields, schemaName, tableName); setValuesInsert(fields, data); insertRow(); closeInsert(); } public String getInsertStatement(String tableName, RowMetaInterface fields) { return getInsertStatement(null, tableName, fields); } public String getInsertStatement(String schemaName, String tableName, RowMetaInterface fields) { StringBuffer ins=new StringBuffer(128); String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); ins.append("INSERT INTO ").append(schemaTable).append(" ("); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValueMeta(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); // Add placeholders... for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); ins.append(" ?"); } ins.append(')'); return ins.toString(); } public void insertRow() throws KettleDatabaseException { insertRow(prepStatementInsert); } public void insertRow(boolean batch) throws KettleDatabaseException { insertRow(prepStatementInsert, batch); } public void updateRow() throws KettleDatabaseException { insertRow(prepStatementUpdate); } public void insertRow(PreparedStatement ps) throws KettleDatabaseException { insertRow(ps, false); } /** * Insert a row into the database using a prepared statement that has all values set. * @param ps The prepared statement * @param batch True if you want to use batch inserts (size = commit size) * @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done. * @throws KettleDatabaseException */ public boolean insertRow(PreparedStatement ps, boolean batch) throws KettleDatabaseException { return insertRow(ps, false, true); } /** * Insert a row into the database using a prepared statement that has all values set. * @param ps The prepared statement * @param batch True if you want to use batch inserts (size = commit size) * @param handleCommit True if you want to handle the commit here after the commit size (False e.g. in case the step handles this, see TableOutput) * @return true if the rows are safe: if batch of rows was sent to the database OR if a commit was done. * @throws KettleDatabaseException */ public boolean insertRow(PreparedStatement ps, boolean batch, boolean handleCommit) throws KettleDatabaseException { String debug="insertRow start"; boolean rowsAreSafe=false; try { // Unique connections and Batch inserts don't mix when you want to roll back on certain databases. // That's why we disable the batch insert in that case. boolean useBatchInsert = batch && getDatabaseMetaData().supportsBatchUpdates() && databaseMeta.supportsBatchUpdates() && Const.isEmpty(connectionGroup); // Add support for batch inserts... if (!isAutoCommit()) { if (useBatchInsert) { debug="insertRow add batch"; ps.addBatch(); // Add the batch, but don't forget to run the batch } else { debug="insertRow exec update"; ps.executeUpdate(); } } else { ps.executeUpdate(); } written++; if (handleCommit) { // some steps handle the commit themselves (see e.g. TableOutput step) if (!isAutoCommit() && (written%commitsize)==0) { if (useBatchInsert) { debug="insertRow executeBatch commit"; ps.executeBatch(); commit(); ps.clearBatch(); } else { debug="insertRow normal commit"; commit(); } rowsAreSafe=true; } } return rowsAreSafe; } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); // 'seed' the loop with the root exception SQLException nextException = ex; do { exceptions.add(nextException); // while current exception has next exception, add to list } while ((nextException = nextException.getNextException())!=null); kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { // log.logError(Const.getStackTracker(ex)); throw new KettleDatabaseException("Error inserting/updating row", ex); } catch(Exception e) { // System.out.println("Unexpected exception in ["+debug+"] : "+e.getMessage()); throw new KettleDatabaseException("Unexpected error inserting/updating row in part ["+debug+"]", e); } } /** * Clears batch of insert prepared statement * @deprecated * @throws KettleDatabaseException */ public void clearInsertBatch() throws KettleDatabaseException { clearBatch(prepStatementInsert); } public void clearBatch(PreparedStatement preparedStatement) throws KettleDatabaseException { try { preparedStatement.clearBatch(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to clear batch for prepared statement", e); } } public void insertFinished(boolean batch) throws KettleDatabaseException { insertFinished(prepStatementInsert, batch); prepStatementInsert = null; } /** * Close the prepared statement of the insert statement. * * @param ps The prepared statement to empty and close. * @param batch true if you are using batch processing * @param psBatchCounter The number of rows on the batch queue * @throws KettleDatabaseException */ public void emptyAndCommit(PreparedStatement ps, boolean batch, int batchCounter) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { // Execute the batch or just perform a commit. if (batch && getDatabaseMetaData().supportsBatchUpdates() && batchCounter>0) { // The problem with the batch counters is that you can't just execute the current batch. // Certain databases have a problem if you execute the batch and if there are no statements in it. // You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything. // That leaves the task of keeping track of the number of rows up to our responsibility. ps.executeBatch(); commit(); } else { commit(); } } // Let's not forget to close the prepared statement. ps.close(); } } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); SQLException nextException = ex.getNextException(); SQLException oldException = null; // This construction is specifically done for some JDBC drivers, these drivers // always return the same exception on getNextException() (and thus go into an infinite loop). // So it's not "equals" but != (comments from Sven Boden). while ( (nextException != null) && (oldException != nextException) ) { exceptions.add(nextException); oldException = nextException; nextException = nextException.getNextException(); } kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to empty ps and commit connection.", ex); } } /** * Close the prepared statement of the insert statement. * * @param ps The prepared statement to empty and close. * @param batch true if you are using batch processing (typically true for this method) * @param psBatchCounter The number of rows on the batch queue * @throws KettleDatabaseException * * @deprecated use emptyAndCommit() instead (pass in the number of rows left in the batch) */ public void insertFinished(PreparedStatement ps, boolean batch) throws KettleDatabaseException { try { if (ps!=null) { if (!isAutoCommit()) { // Execute the batch or just perform a commit. if (batch && getDatabaseMetaData().supportsBatchUpdates()) { // The problem with the batch counters is that you can't just execute the current batch. // Certain databases have a problem if you execute the batch and if there are no statements in it. // You can't just catch the exception either because you would have to roll back on certain databases before you can then continue to do anything. // That leaves the task of keeping track of the number of rows up to our responsibility. ps.executeBatch(); commit(); } else { commit(); } } // Let's not forget to close the prepared statement. ps.close(); } } catch(BatchUpdateException ex) { KettleDatabaseBatchException kdbe = new KettleDatabaseBatchException("Error updating batch", ex); kdbe.setUpdateCounts(ex.getUpdateCounts()); List<Exception> exceptions = new ArrayList<Exception>(); SQLException nextException = ex.getNextException(); SQLException oldException = null; // This construction is specifically done for some JDBC drivers, these drivers // always return the same exception on getNextException() (and thus go into an infinite loop). // So it's not "equals" but != (comments from Sven Boden). while ( (nextException != null) && (oldException != nextException) ) { exceptions.add(nextException); oldException = nextException; nextException = nextException.getNextException(); } kdbe.setExceptionsList(exceptions); throw kdbe; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to commit connection after having inserted rows.", ex); } } /** * Execute an SQL statement on the database connection (has to be open) * @param sql The SQL to execute * @return a Result object indicating the number of lines read, deleted, inserted, updated, ... * @throws KettleDatabaseException in case anything goes wrong. */ public Result execStatement(String sql) throws KettleDatabaseException { return execStatement(sql, null, null); } public Result execStatement(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException { Result result = new Result(); try { boolean resultSet; int count; if (params!=null) { PreparedStatement prep_stmt = connection.prepareStatement(databaseMeta.stripCR(sql)); setValues(params, data, prep_stmt); // set the parameters! resultSet = prep_stmt.execute(); count = prep_stmt.getUpdateCount(); prep_stmt.close(); } else { String sqlStripped = databaseMeta.stripCR(sql); // log.logDetailed("Executing SQL Statement: ["+sqlStripped+"]"); Statement stmt = connection.createStatement(); resultSet = stmt.execute(sqlStripped); count = stmt.getUpdateCount(); stmt.close(); } if (resultSet) { // the result is a resultset, but we don't do anything with it! // You should have called something else! // log.logDetailed("What to do with ResultSet??? (count="+count+")"); } else { if (count > 0) { if (sql.toUpperCase().startsWith("INSERT")) result.setNrLinesOutput(count); if (sql.toUpperCase().startsWith("UPDATE")) result.setNrLinesUpdated(count); if (sql.toUpperCase().startsWith("DELETE")) result.setNrLinesDeleted(count); } } // See if a cache needs to be cleared... if (sql.toUpperCase().startsWith("ALTER TABLE") || sql.toUpperCase().startsWith("DROP TABLE") || sql.toUpperCase().startsWith("CREATE TABLE") ) { DBCache.getInstance().clear(databaseMeta.getName()); } } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't execute SQL: "+sql+Const.CR, ex); } catch(Exception e) { throw new KettleDatabaseException("Unexpected error executing SQL: "+Const.CR, e); } return result; } /** * Execute a series of SQL statements, separated by ; * * We are already connected... * Multiple statements have to be split into parts * We use the ";" to separate statements... * * We keep the results in Result object from Jobs * * @param script The SQL script to be execute * @throws KettleDatabaseException In case an error occurs * @return A result with counts of the number or records updates, inserted, deleted or read. */ public Result execStatements(String script) throws KettleDatabaseException { Result result = new Result(); String all = script; int from=0; int to=0; int length = all.length(); int nrstats = 0; while (to<length) { char c = all.charAt(to); if (c=='"') { c=' '; while (to<length && c!='"') { to++; c=all.charAt(to); } } else if (c=='\'') // skip until next ' { c=' '; while (to<length && c!='\'') { to++; c=all.charAt(to); } } else if (all.substring(to).startsWith("--")) // -- means: ignore comment until end of line... { while (to<length && c!='\n' && c!='\r') { to++; c=all.charAt(to); } } if (c==';' || to>=length-1) // end of statement { if (to>=length-1) to++; // grab last char also! String stat; if (to<=length) stat = all.substring(from, to); else stat = all.substring(from); // If it ends with a ; remove that ; // Oracle for example can't stand it when this happens... if (stat.length()>0 && stat.charAt(stat.length()-1)==';') { stat = stat.substring(0,stat.length()-1); } if (!Const.onlySpaces(stat)) { String sql=Const.trim(stat); if (sql.toUpperCase().startsWith("SELECT")) { // A Query if(log.isDetailed()) log.logDetailed("launch SELECT statement: "+Const.CR+sql); nrstats++; ResultSet rs = null; try { rs = openQuery(sql); if (rs!=null) { Object[] row = getRow(rs); while (row!=null) { result.setNrLinesRead(result.getNrLinesRead()+1); if (log.isDetailed()) log.logDetailed(rowMeta.getString(row)); row = getRow(rs); } } else { if (log.isDebug()) log.logDebug("Error executing query: "+Const.CR+sql); } } catch (KettleValueException e) { throw new KettleDatabaseException(e); // just pass the error upwards. } finally { try { if ( rs != null ) rs.close(); } catch (SQLException ex ) { if (log.isDebug()) log.logDebug("Error closing query: "+Const.CR+sql); } } } else // any kind of statement { if(log.isDetailed()) log.logDetailed("launch DDL statement: "+Const.CR+sql); // A DDL statement nrstats++; Result res = execStatement(sql); result.add(res); } } to++; from=to; } else { to++; } } if(log.isDetailed()) log.logDetailed(nrstats+" statement"+(nrstats==1?"":"s")+" executed"); return result; } public ResultSet openQuery(String sql) throws KettleDatabaseException { return openQuery(sql, null, null); } /** * Open a query on the database with a set of parameters stored in a Kettle Row * @param sql The SQL to launch with question marks (?) as placeholders for the parameters * @param params The parameters or null if no parameters are used. * @data the parameter data to open the query with * @return A JDBC ResultSet * @throws KettleDatabaseException when something goes wrong with the query. */ public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data) throws KettleDatabaseException { return openQuery(sql, params, data, ResultSet.FETCH_FORWARD); } public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode) throws KettleDatabaseException { return openQuery(sql, params, data, fetch_mode, false); } public ResultSet openQuery(String sql, RowMetaInterface params, Object[] data, int fetch_mode, boolean lazyConversion) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { if (params!=null) { debug = "P create prepared statement (con==null? "+(connection==null)+")"; pstmt = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); debug = "P Set values"; setValues(params, data); // set the dates etc! if (canWeSetFetchSize(pstmt) ) { debug = "P Set fetchsize"; int fs = Const.FETCH_SIZE<=pstmt.getMaxRows()?pstmt.getMaxRows():Const.FETCH_SIZE; // System.out.println("Setting pstmt fetchsize to : "+fs); { if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults()) { pstmt.setFetchSize(Integer.MIN_VALUE); } else pstmt.setFetchSize(fs); } debug = "P Set fetch direction"; pstmt.setFetchDirection(fetch_mode); } debug = "P Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) pstmt.setMaxRows(rowlimit); debug = "exec query"; res = pstmt.executeQuery(); } else { debug = "create statement"; sel_stmt = connection.createStatement(); if (canWeSetFetchSize(sel_stmt)) { debug = "Set fetchsize"; int fs = Const.FETCH_SIZE<=sel_stmt.getMaxRows()?sel_stmt.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults()) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(fs); } debug = "Set fetch direction"; sel_stmt.setFetchDirection(fetch_mode); } debug = "Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(rowlimit); debug = "exec query"; res=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); } debug = "openQuery : get rowinfo"; // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ingore the length of Strings in result rows. rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta, lazyConversion); } catch(SQLException ex) { // log.logError("ERROR executing ["+sql+"]"); // log.logError("ERROR in part: ["+debug+"]"); // printSQLException(ex); throw new KettleDatabaseException("An error occurred executing SQL: "+Const.CR+sql, ex); } catch(Exception e) { log.logError("ERROR executing query: "+e.toString()); log.logError("ERROR in part: "+debug); throw new KettleDatabaseException("An error occurred executing SQL in part ["+debug+"]:"+Const.CR+sql, e); } return res; } private boolean canWeSetFetchSize(Statement statement) throws SQLException { return databaseMeta.isFetchSizeSupported() && ( statement.getMaxRows()>0 || databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta || ( databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults() ) ); } public ResultSet openQuery(PreparedStatement ps, RowMetaInterface params, Object[] data) throws KettleDatabaseException { ResultSet res; String debug = "Start"; // Create a Statement try { debug = "OQ Set values"; setValues(params, data, ps); // set the parameters! if (canWeSetFetchSize(ps)) { debug = "OQ Set fetchsize"; int fs = Const.FETCH_SIZE<=ps.getMaxRows()?ps.getMaxRows():Const.FETCH_SIZE; if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta && databaseMeta.isStreamingResults()) { ps.setFetchSize(Integer.MIN_VALUE); } else { ps.setFetchSize(fs); } debug = "OQ Set fetch direction"; ps.setFetchDirection(ResultSet.FETCH_FORWARD); } debug = "OQ Set max rows"; if (rowlimit>0 && databaseMeta.supportsSetMaxRows()) ps.setMaxRows(rowlimit); debug = "OQ exec query"; res = ps.executeQuery(); debug = "OQ getRowInfo()"; // rowinfo = getRowInfo(res.getMetaData()); // MySQL Hack only. It seems too much for the cursor type of operation on MySQL, to have another cursor opened // to get the length of a String field. So, on MySQL, we ignore the length of Strings in result rows. rowMeta = getRowInfo(res.getMetaData(), databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta, false); } catch(SQLException ex) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", ex); } catch(Exception e) { throw new KettleDatabaseException("ERROR executing query in part["+debug+"]", e); } return res; } public RowMetaInterface getTableFields(String tablename) throws KettleDatabaseException { return getQueryFields(databaseMeta.getSQLQueryFields(tablename), false); } public RowMetaInterface getQueryFields(String sql, boolean param) throws KettleDatabaseException { return getQueryFields(sql, param, null, null); } /** * See if the table specified exists by reading * @param tablename The name of the table to check.<br> * This is supposed to be the properly quoted name of the table or the complete schema-table name combination. * @return true if the table exists, false if it doesn't. */ public boolean checkTableExists(String tablename) throws KettleDatabaseException { try { if(log.isDebug()) log.logDebug("Checking if table ["+tablename+"] exists!"); // Just try to read from the table. String sql = databaseMeta.getSQLTableExists(tablename); try { getOneRow(sql); return true; } catch(KettleDatabaseException e) { return false; } /* if (getDatabaseMetaData()!=null) { ResultSet alltables = getDatabaseMetaData().getTables(null, null, "%" , new String[] { "TABLE", "VIEW", "SYNONYM" } ); boolean found = false; if (alltables!=null) { while (alltables.next() && !found) { String schemaName = alltables.getString("TABLE_SCHEM"); String name = alltables.getString("TABLE_NAME"); if ( tablename.equalsIgnoreCase(name) || ( schemaName!=null && tablename.equalsIgnoreCase( databaseMeta.getSchemaTableCombination(schemaName, name)) ) ) { log.logDebug("table ["+tablename+"] was found!"); found=true; } } alltables.close(); return found; } else { throw new KettleDatabaseException("Unable to read table-names from the database meta-data."); } } else { throw new KettleDatabaseException("Unable to get database meta-data from the database."); } */ } catch(Exception e) { throw new KettleDatabaseException("Unable to check if table ["+tablename+"] exists on connection ["+databaseMeta.getName()+"]", e); } } /** * See if the column specified exists by reading * @param columnname The name of the column to check. * @param tablename The name of the table to check.<br> * This is supposed to be the properly quoted name of the table or the complete schema-table name combination. * @return true if the table exists, false if it doesn't. */ public boolean checkColumnExists(String columnname, String tablename) throws KettleDatabaseException { try { if(log.isDebug()) log.logDebug("Checking if column [" + columnname + "] exists in table ["+tablename+"] !"); // Just try to read from the table. String sql = databaseMeta.getSQLColumnExists(columnname,tablename); try { getOneRow(sql); return true; } catch(KettleDatabaseException e) { return false; } } catch(Exception e) { throw new KettleDatabaseException("Unable to check if column [" + columnname + "] exists in table ["+tablename+"] on connection ["+databaseMeta.getName()+"]", e); } } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String sequenceName) throws KettleDatabaseException { return checkSequenceExists(null, sequenceName); } /** * Check whether the sequence exists, Oracle only! * @param sequenceName The name of the sequence * @return true if the sequence exists. */ public boolean checkSequenceExists(String schemaName, String sequenceName) throws KettleDatabaseException { boolean retval=false; if (!databaseMeta.supportsSequences()) return retval; String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); try { // Get the info from the data dictionary... String sql = databaseMeta.getSQLSequenceExists(schemaSequence); ResultSet res = openQuery(sql); if (res!=null) { Object[] row = getRow(res); if (row!=null) { retval=true; } closeQuery(res); } } catch(Exception e) { throw new KettleDatabaseException("Unexpected error checking whether or not sequence ["+schemaSequence+"] exists", e); } return retval; } /** * Check if an index on certain fields in a table exists. * @param tableName The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String tableName, String idx_fields[]) throws KettleDatabaseException { return checkIndexExists(null, tableName, idx_fields); } /** * Check if an index on certain fields in a table exists. * @param tablename The table on which the index is checked * @param idx_fields The fields on which the indexe is checked * @return True if the index exists */ public boolean checkIndexExists(String schemaName, String tableName, String idx_fields[]) throws KettleDatabaseException { String tablename = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); if (!checkTableExists(tablename)) return false; if(log.isDebug()) log.logDebug("CheckIndexExists() tablename = "+tablename+" type = "+databaseMeta.getPluginId()); return databaseMeta.getDatabaseInterface().checkIndexExists(this, schemaName, tableName, idx_fields); } public String getCreateIndexStatement(String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { return getCreateIndexStatement(null, tablename, indexname, idx_fields, tk, unique, bitmap, semi_colon); } public String getCreateIndexStatement(String schemaname, String tablename, String indexname, String idx_fields[], boolean tk, boolean unique, boolean bitmap, boolean semi_colon) { String cr_index=""; cr_index += "CREATE "; if (unique || ( tk && databaseMeta.getDatabaseInterface() instanceof SybaseDatabaseMeta)) cr_index += "UNIQUE "; if (bitmap && databaseMeta.supportsBitmapIndex()) cr_index += "BITMAP "; cr_index += "INDEX "+databaseMeta.quoteField(indexname)+Const.CR+" "; cr_index += "ON "; // assume table has already been quoted (and possibly includes schema) cr_index += tablename; cr_index += Const.CR + "( "+Const.CR; for (int i=0;i<idx_fields.length;i++) { if (i>0) cr_index+=", "; else cr_index+=" "; cr_index += databaseMeta.quoteField(idx_fields[i])+Const.CR; } cr_index+=")"+Const.CR; if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { cr_index+="TABLESPACE "+databaseMeta.quoteField(databaseMeta.getIndexTablespace()); } if (semi_colon) { cr_index+=";"+Const.CR; } return cr_index; } public String getCreateSequenceStatement(String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { return getCreateSequenceStatement(null, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon); } public String getCreateSequenceStatement(String sequence, String start_at, String increment_by, String max_value, boolean semi_colon) { return getCreateSequenceStatement(null, sequence, start_at, increment_by, max_value, semi_colon); } public String getCreateSequenceStatement(String schemaName, String sequence, long start_at, long increment_by, long max_value, boolean semi_colon) { return getCreateSequenceStatement(schemaName, sequence, Long.toString(start_at), Long.toString(increment_by), Long.toString(max_value), semi_colon); } public String getCreateSequenceStatement(String schemaName, String sequenceName, String start_at, String increment_by, String max_value, boolean semi_colon) { String cr_seq=""; if (Const.isEmpty(sequenceName)) return cr_seq; if (databaseMeta.supportsSequences()) { String schemaSequence = databaseMeta.getQuotedSchemaTableCombination(schemaName, sequenceName); cr_seq += "CREATE SEQUENCE "+schemaSequence+" "+Const.CR; // Works for both Oracle and PostgreSQL :-) cr_seq += "START WITH "+start_at+" "+Const.CR; cr_seq += "INCREMENT BY "+increment_by+" "+Const.CR; if (max_value != null) { // "-1" means there is no maxvalue, must be handles different by DB2 / AS400 if (databaseMeta.supportsSequenceNoMaxValueOption() && max_value.trim().equals("-1")) { cr_seq += "NOMAXVALUE"+Const.CR; } else { // set the max value cr_seq += "MAXVALUE "+max_value+Const.CR; } } if (semi_colon) cr_seq+=";"+Const.CR; } return cr_seq; } public RowMetaInterface getQueryFields(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException { RowMetaInterface fields; DBCache dbcache = DBCache.getInstance(); DBCacheEntry entry=null; // Check the cache first! if (dbcache!=null) { entry = new DBCacheEntry(databaseMeta.getName(), sql); fields = dbcache.get(entry); if (fields!=null) { return fields; } } if (connection==null) return null; // Cache test without connect. // No cache entry found // The new method of retrieving the query fields fails on Oracle because // they failed to implement the getMetaData method on a prepared statement. (!!!) // Even recent drivers like 10.2 fail because of it. // There might be other databases that don't support it (we have no knowledge of this at the time of writing). // If we discover other RDBMSs, we will create an interface for it. // For now, we just try to get the field layout on the re-bound in the exception block below. if (databaseMeta.supportsPreparedStatementMetadataRetrieval()) { // On with the regular program. PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(databaseMeta.stripCR(sql), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ResultSetMetaData rsmd = preparedStatement.getMetaData(); fields = getRowInfo(rsmd, false, false); } catch(Exception e) { fields = getQueryFieldsFallback(sql, param, inform, data); } finally { if (preparedStatement!=null) { try { preparedStatement.close(); } catch (SQLException e) { throw new KettleDatabaseException("Unable to close prepared statement after determining SQL layout", e); } } } } else { /* databaseMeta.getDatabaseType()==DatabaseMeta.TYPE_DATABASE_SYBASEIQ ) { */ fields=getQueryFieldsFallback(sql, param, inform, data); } // Store in cache!! if (dbcache!=null && entry!=null) { if (fields!=null) { dbcache.put(entry, fields); } } return fields; } private RowMetaInterface getQueryFieldsFallback(String sql, boolean param, RowMetaInterface inform, Object[] data) throws KettleDatabaseException { RowMetaInterface fields; try { if (inform==null // Hack for MSSQL jtds 1.2 when using xxx NOT IN yyy we have to use a prepared statement (see BugID 3214) && databaseMeta.getDatabaseInterface() instanceof MSSQLServerDatabaseMeta ) { sel_stmt = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); if (databaseMeta.isFetchSizeSupported() && sel_stmt.getMaxRows()>=1) { if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) { sel_stmt.setFetchSize(Integer.MIN_VALUE); } else { sel_stmt.setFetchSize(1); } } if (databaseMeta.supportsSetMaxRows()) sel_stmt.setMaxRows(1); ResultSet r=sel_stmt.executeQuery(databaseMeta.stripCR(sql)); fields = getRowInfo(r.getMetaData(), false, false); r.close(); sel_stmt.close(); sel_stmt=null; } else { PreparedStatement ps = connection.prepareStatement(databaseMeta.stripCR(sql)); if (param) { RowMetaInterface par = inform; if (par==null || par.isEmpty()) par = getParameterMetaData(ps); if (par==null || par.isEmpty()) par = getParameterMetaData(sql, inform, data); setValues(par, data, ps); } ResultSet r = ps.executeQuery(); fields=getRowInfo(ps.getMetaData(), false, false); r.close(); ps.close(); } } catch(Exception ex) { throw new KettleDatabaseException("Couldn't get field info from ["+sql+"]"+Const.CR, ex); } return fields; } public void closeQuery(ResultSet res) throws KettleDatabaseException { // close everything involved in the query! try { if (res!=null) res.close(); if (sel_stmt!=null) { sel_stmt.close(); sel_stmt=null; } if (pstmt!=null) { pstmt.close(); pstmt=null;} } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't close query: resultset or prepared statements", ex); } } /** * Build the row using ResultSetMetaData rsmd * @param rm The resultset metadata to inquire * @param ignoreLength true if you want to ignore the length (workaround for MySQL bug/problem) * @param lazyConversion true if lazy conversion needs to be enabled where possible */ private RowMetaInterface getRowInfo(ResultSetMetaData rm, boolean ignoreLength, boolean lazyConversion) throws KettleDatabaseException { if (rm==null) { throw new KettleDatabaseException("No result set metadata available to retrieve row metadata!"); } rowMeta = new RowMeta(); try { // TODO If we do lazy conversion, we need to find out about the encoding int fieldNr = 1; int nrcols=rm.getColumnCount(); for (int i=1;i<=nrcols;i++) { String name=new String(rm.getColumnName(i)); // Check the name, sometimes it's empty. if (Const.isEmpty(name) || Const.onlySpaces(name)) { name = "Field"+fieldNr; fieldNr++; } ValueMetaInterface v = getValueFromSQLType(name, rm, i, ignoreLength, lazyConversion); rowMeta.addValueMeta(v); } return rowMeta; } catch(SQLException ex) { throw new KettleDatabaseException("Error getting row information from database: ", ex); } } private ValueMetaInterface getValueFromSQLType(String name, ResultSetMetaData rm, int index, boolean ignoreLength, boolean lazyConversion) throws SQLException { int length=-1; int precision=-1; int valtype=ValueMetaInterface.TYPE_NONE; boolean isClob = false; int type = rm.getColumnType(index); boolean signed = rm.isSigned(index); switch(type) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: case java.sql.Types.LONGVARCHAR: // Character Large Object valtype=ValueMetaInterface.TYPE_STRING; if (!ignoreLength) length=rm.getColumnDisplaySize(index); break; case java.sql.Types.CLOB: valtype=ValueMetaInterface.TYPE_STRING; length=DatabaseMeta.CLOB_LENGTH; isClob=true; break; case java.sql.Types.BIGINT: // verify Unsigned BIGINT overflow! if (signed) { valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 9.223.372.036.854.775.807 length=15; } else { valtype=ValueMetaInterface.TYPE_BIGNUMBER; precision=0; // Max 18.446.744.073.709.551.615 length=16; } break; case java.sql.Types.INTEGER: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 2.147.483.647 length=9; break; case java.sql.Types.SMALLINT: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 32.767 length=4; break; case java.sql.Types.TINYINT: valtype=ValueMetaInterface.TYPE_INTEGER; precision=0; // Max 127 length=2; break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: case java.sql.Types.NUMERIC: valtype=ValueMetaInterface.TYPE_NUMBER; length=rm.getPrecision(index); precision=rm.getScale(index); if (length >=126) length=-1; if (precision >=126) precision=-1; if (type==java.sql.Types.DOUBLE || type==java.sql.Types.FLOAT || type==java.sql.Types.REAL) { if (precision==0) { precision=-1; // precision is obviously incorrect if the type if Double/Float/Real } // If we're dealing with PostgreSQL and double precision types if (databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta && type==java.sql.Types.DOUBLE && precision==16 && length==16) { precision=-1; length=-1; } // MySQL: max resolution is double precision floating point (double) // The (12,31) that is given back is not correct if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) { if (precision >= length) { precision=-1; length=-1; } } // if the length or precision needs a BIGNUMBER if (length>15 || precision>15) valtype=ValueMetaInterface.TYPE_BIGNUMBER; } else { if (precision==0) { if (length<=18 && length>0) { // Among others Oracle is affected here. valtype=ValueMetaInterface.TYPE_INTEGER; // Long can hold up to 18 significant digits } else if (length>18) { valtype=ValueMetaInterface.TYPE_BIGNUMBER; } } else { // we have a precision: keep NUMBER or change to BIGNUMBER? if (length>15 || precision>15) valtype=ValueMetaInterface.TYPE_BIGNUMBER; } } if (databaseMeta.getDatabaseInterface() instanceof PostgreSQLDatabaseMeta || databaseMeta.getDatabaseInterface() instanceof GreenplumDatabaseMeta) { // undefined size => arbitrary precision if (type == java.sql.Types.NUMERIC && length == 0 && precision == 0) { valtype = ValueMetaInterface.TYPE_BIGNUMBER; length = -1; precision = -1; } } if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta) { if (precision == 0 && length == 38 ) { valtype=ValueMetaInterface.TYPE_INTEGER; } if (precision<=0 && length<=0) // undefined size: BIGNUMBER, precision on Oracle can be 38, too big for a Number type { valtype=ValueMetaInterface.TYPE_BIGNUMBER; length=-1; precision=-1; } } break; case java.sql.Types.DATE: if (databaseMeta.getDatabaseInterface() instanceof TeradataDatabaseMeta) { precision = 1; } case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: valtype=ValueMetaInterface.TYPE_DATE; if (databaseMeta.getDatabaseInterface() instanceof MySQLDatabaseMeta) { String property = databaseMeta.getConnectionProperties().getProperty("yearIsDateType"); if (property != null && property.equalsIgnoreCase("false") && rm.getColumnTypeName(index).equalsIgnoreCase("YEAR")) { valtype = ValueMetaInterface.TYPE_INTEGER; precision = 0; length = 4; break; } } break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: valtype=ValueMetaInterface.TYPE_BOOLEAN; break; case java.sql.Types.BINARY: case java.sql.Types.BLOB: case java.sql.Types.VARBINARY: case java.sql.Types.LONGVARBINARY: valtype=ValueMetaInterface.TYPE_BINARY; if (databaseMeta.isDisplaySizeTwiceThePrecision() && (2 * rm.getPrecision(index)) == rm.getColumnDisplaySize(index)) { // set the length for "CHAR(X) FOR BIT DATA" length = rm.getPrecision(index); } else if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta && ( type==java.sql.Types.VARBINARY || type==java.sql.Types.LONGVARBINARY ) ) { // set the length for Oracle "RAW" or "LONGRAW" data types valtype = ValueMetaInterface.TYPE_STRING; length = rm.getColumnDisplaySize(index); } else { length=-1; } precision=-1; break; default: valtype=ValueMetaInterface.TYPE_STRING; precision=rm.getScale(index); break; } // Grab the comment as a description to the field as well. String comments=rm.getColumnLabel(index); // get & store more result set meta data for later use int originalColumnType=rm.getColumnType(index); String originalColumnTypeName=rm.getColumnTypeName(index); int originalPrecision=-1; if (!ignoreLength) rm.getPrecision(index); // Throws exception on MySQL int originalScale=rm.getScale(index); // boolean originalAutoIncrement=rm.isAutoIncrement(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788 // int originalNullable=rm.isNullable(index); DISABLED FOR PERFORMANCE REASONS : PDI-1788 boolean originalSigned=rm.isSigned(index); ValueMetaInterface v=new ValueMeta(name, valtype); v.setLength(length); v.setPrecision(precision); v.setComments(comments); v.setLargeTextField(isClob); v.setOriginalColumnType(originalColumnType); v.setOriginalColumnTypeName(originalColumnTypeName); v.setOriginalPrecision(originalPrecision); v.setOriginalScale(originalScale); // v.setOriginalAutoIncrement(originalAutoIncrement); DISABLED FOR PERFORMANCE REASONS : PDI-1788 // v.setOriginalNullable(originalNullable); DISABLED FOR PERFORMANCE REASONS : PDI-1788 v.setOriginalSigned(originalSigned); // See if we need to enable lazy conversion... if (lazyConversion && valtype==ValueMetaInterface.TYPE_STRING) { v.setStorageType(ValueMetaInterface.STORAGE_TYPE_BINARY_STRING); // TODO set some encoding to go with this. // Also set the storage metadata. a copy of the parent, set to String too. ValueMetaInterface storageMetaData = v.clone(); storageMetaData.setType(ValueMetaInterface.TYPE_STRING); storageMetaData.setStorageType(ValueMetaInterface.STORAGE_TYPE_NORMAL); v.setStorageMetadata(storageMetaData); } return v; } public boolean absolute(ResultSet rs, int position) throws KettleDatabaseException { try { return rs.absolute(position); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to position "+position, e); } } public boolean relative(ResultSet rs, int rows) throws KettleDatabaseException { try { return rs.relative(rows); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move the resultset forward "+rows+" rows", e); } } public void afterLast(ResultSet rs) throws KettleDatabaseException { try { rs.afterLast(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to after the last position", e); } } public void first(ResultSet rs) throws KettleDatabaseException { try { rs.first(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to move resultset to the first position", e); } } /** * Get a row from the resultset. Do not use lazy conversion * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs) throws KettleDatabaseException { return getRow(rs, false); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @param lazyConversion set to true if strings need to have lazy conversion enabled * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs, boolean lazyConversion) throws KettleDatabaseException { if (rowMeta==null) { ResultSetMetaData rsmd = null; try { rsmd = rs.getMetaData(); } catch(SQLException e) { throw new KettleDatabaseException("Unable to retrieve metadata from resultset", e); } rowMeta = getRowInfo(rsmd, false, lazyConversion); } return getRow(rs, null, rowMeta); } /** * Get a row from the resultset. * @param rs The resultset to get the row from * @return one row or null if no row was found on the resultset or if an error occurred. */ public Object[] getRow(ResultSet rs, ResultSetMetaData dummy, RowMetaInterface rowInfo) throws KettleDatabaseException { try { int nrcols=rowInfo.size(); Object[] data = RowDataUtil.allocateRowData(nrcols); if (rs.next()) { for (int i=0;i<nrcols;i++) { ValueMetaInterface val = rowInfo.getValueMeta(i); switch(val.getType()) { case ValueMetaInterface.TYPE_BOOLEAN : data[i] = Boolean.valueOf( rs.getBoolean(i+1) ); break; case ValueMetaInterface.TYPE_NUMBER : data[i] = new Double( rs.getDouble(i+1) ); break; case ValueMetaInterface.TYPE_BIGNUMBER : data[i] = rs.getBigDecimal(i+1); break; case ValueMetaInterface.TYPE_INTEGER : data[i] = Long.valueOf( rs.getLong(i+1) ); break; case ValueMetaInterface.TYPE_STRING : { if (val.isStorageBinaryString()) { data[i] = rs.getBytes(i+1); } else { data[i] = rs.getString(i+1); } } break; case ValueMetaInterface.TYPE_BINARY : { if (databaseMeta.supportsGetBlob()) { Blob blob = rs.getBlob(i+1); if (blob!=null) { data[i] = blob.getBytes(1L, (int)blob.length()); } else { data[i] = null; } } else { data[i] = rs.getBytes(i+1); } } break; case ValueMetaInterface.TYPE_DATE : if (databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta && val.getOriginalColumnType()==java.sql.Types.TIME) { // Neoview can not handle getDate / getTimestamp for a Time column data[i] = rs.getTime(i+1); break; // Time is a subclass of java.util.Date, the default date will be 1970-01-01 } else if (val.getPrecision()!=1 && databaseMeta.supportsTimeStampToDateConversion()) { data[i] = rs.getTimestamp(i+1); break; // Timestamp extends java.util.Date } else { data[i] = rs.getDate(i+1); break; } default: break; } if (rs.wasNull()) data[i] = null; // null value, it's the default but we want it just to make sure we handle this case too. } } else { data=null; } return data; } catch(SQLException ex) { throw new KettleDatabaseException("Couldn't get row from result set", ex); } } public void printSQLException(SQLException ex) { log.logError("==> SQLException: "); while (ex != null) { log.logError("Message: " + ex.getMessage ()); log.logError("SQLState: " + ex.getSQLState ()); log.logError("ErrorCode: " + ex.getErrorCode ()); ex = ex.getNextException(); log.logError(""); } } public void setLookup(String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(table, codes, condition, gets, rename, orderby, false); } public void setLookup(String schema, String table, String codes[], String condition[], String gets[], String rename[], String orderby ) throws KettleDatabaseException { setLookup(schema, table, codes, condition, gets, rename, orderby, false); } public void setLookup(String tableName, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { setLookup(null, tableName, codes, condition, gets, rename, orderby, checkForMultipleResults); } // Lookup certain fields in a table public void setLookup(String schemaName, String tableName, String codes[], String condition[], String gets[], String rename[], String orderby, boolean checkForMultipleResults) throws KettleDatabaseException { String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); String sql = "SELECT "; for (int i=0;i<gets.length;i++) { if (i!=0) sql += ", "; sql += databaseMeta.quoteField(gets[i]); if (rename!=null && rename[i]!=null && !gets[i].equalsIgnoreCase(rename[i])) { sql+=" AS "+databaseMeta.quoteField(rename[i]); } } sql += " FROM "+table+" WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += " AND "; sql += databaseMeta.quoteField(codes[i]); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } if (orderby!=null && orderby.length()!=0) { sql += " ORDER BY "+orderby; } try { if(log.isDetailed()) log.logDetailed("Setting preparedStatement to ["+sql+"]"); prepStatementLookup=connection.prepareStatement(databaseMeta.stripCR(sql)); if (!checkForMultipleResults && databaseMeta.supportsSetMaxRows()) { prepStatementLookup.setMaxRows(1); // alywas get only 1 line back! } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare statement for update ["+sql+"]", ex); } } public boolean prepareUpdate(String table, String codes[], String condition[], String sets[]) { return prepareUpdate(null, table, codes, condition, sets); } // Lookup certain fields in a table public boolean prepareUpdate(String schemaName, String tableName, String codes[], String condition[], String sets[]) { StringBuffer sql = new StringBuffer(128); String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); sql.append("UPDATE ").append(schemaTable).append(Const.CR).append("SET "); for (int i=0;i<sets.length;i++) { if (i!=0) sql.append(", "); sql.append(databaseMeta.quoteField(sets[i])); sql.append(" = ?").append(Const.CR); } sql.append("WHERE "); for (int i=0;i<codes.length;i++) { if (i!=0) sql.append("AND "); sql.append(databaseMeta.quoteField(codes[i])); if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql.append(" BETWEEN ? AND ? "); } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql.append(' ').append(condition[i]).append(' '); } else { sql.append(' ').append(condition[i]).append(" ? "); } } try { String s = sql.toString(); if(log.isDetailed()) log.logDetailed("Setting update preparedStatement to ["+s+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(s)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param table The table-name to delete in * @param codes * @param condition * @return true when everything went OK, false when something went wrong. */ public boolean prepareDelete(String table, String codes[], String condition[]) { return prepareDelete(null, table, codes, condition); } /** * Prepare a delete statement by giving it the tablename, fields and conditions to work with. * @param schemaName the schema-name to delete in * @param tableName The table-name to delete in * @param codes * @param condition * @return true when everything went OK, false when something went wrong. */ public boolean prepareDelete(String schemaName, String tableName, String codes[], String condition[]) { String sql; String table = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); sql = "DELETE FROM "+table+Const.CR; sql+= "WHERE "; for (int i=0;i<codes.length;i++) { if (i!=0) sql += "AND "; sql += codes[i]; if ("BETWEEN".equalsIgnoreCase(condition[i])) { sql+=" BETWEEN ? AND ? "; } else if ("IS NULL".equalsIgnoreCase(condition[i]) || "IS NOT NULL".equalsIgnoreCase(condition[i])) { sql+=" "+condition[i]+" "; } else { sql+=" "+condition[i]+" ? "; } } try { if(log.isDetailed()) log.logDetailed("Setting update preparedStatement to ["+sql+"]"); prepStatementUpdate=connection.prepareStatement(databaseMeta.stripCR(sql)); } catch(SQLException ex) { printSQLException(ex); return false; } return true; } public void setProcLookup(String proc, String arg[], String argdir[], int argtype[], String returnvalue, int returntype) throws KettleDatabaseException { String sql; int pos=0; sql = "{ "; if (returnvalue!=null && returnvalue.length()!=0) { sql+="? = "; } sql+="call "+proc+" "; if (arg.length>0) sql+="("; for (int i=0;i<arg.length;i++) { if (i!=0) sql += ", "; sql += " ?"; } if (arg.length>0) sql+=")"; sql+="}"; try { if(log.isDetailed()) log.logDetailed("DBA setting callableStatement to ["+sql+"]"); cstmt=connection.prepareCall(sql); pos=1; if (!Const.isEmpty(returnvalue)) { switch(returntype) { case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DOUBLE); break; case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(pos, java.sql.Types.DECIMAL); break; case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(pos, java.sql.Types.BIGINT); break; case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(pos, java.sql.Types.VARCHAR); break; case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(pos, java.sql.Types.TIMESTAMP); break; case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(pos, java.sql.Types.BOOLEAN); break; default: break; } pos++; } for (int i=0;i<arg.length;i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { switch(argtype[i]) { case ValueMetaInterface.TYPE_NUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DOUBLE); break; case ValueMetaInterface.TYPE_BIGNUMBER : cstmt.registerOutParameter(i+pos, java.sql.Types.DECIMAL); break; case ValueMetaInterface.TYPE_INTEGER : cstmt.registerOutParameter(i+pos, java.sql.Types.BIGINT); break; case ValueMetaInterface.TYPE_STRING : cstmt.registerOutParameter(i+pos, java.sql.Types.VARCHAR); break; case ValueMetaInterface.TYPE_DATE : cstmt.registerOutParameter(i+pos, java.sql.Types.TIMESTAMP); break; case ValueMetaInterface.TYPE_BOOLEAN : cstmt.registerOutParameter(i+pos, java.sql.Types.BOOLEAN); break; default: break; } } } } catch(SQLException ex) { throw new KettleDatabaseException("Unable to prepare database procedure call", ex); } } public Object[] getLookup() throws KettleDatabaseException { return getLookup(prepStatementLookup); } public Object[] getLookup(boolean failOnMultipleResults) throws KettleDatabaseException { return getLookup(prepStatementLookup, failOnMultipleResults); } public Object[] getLookup(PreparedStatement ps) throws KettleDatabaseException { return getLookup(ps, false); } public Object[] getLookup(PreparedStatement ps, boolean failOnMultipleResults) throws KettleDatabaseException { ResultSet res = null; try { res = ps.executeQuery(); rowMeta = getRowInfo(res.getMetaData(), false, false); Object[] ret = getRow(res); if (failOnMultipleResults) { if (ret != null && res.next()) { // if the previous row was null, there's no reason to try res.next() again. // on DB2 this will even cause an exception (because of the buggy DB2 JDBC driver). throw new KettleDatabaseException("Only 1 row was expected as a result of a lookup, and at least 2 were found!"); } } return ret; } catch(SQLException ex) { throw new KettleDatabaseException("Error looking up row in database", ex); } finally { try { if (res!=null) res.close(); // close resultset! } catch(SQLException e) { throw new KettleDatabaseException("Unable to close resultset after looking up data", e); } } } public DatabaseMetaData getDatabaseMetaData() throws KettleDatabaseException { try { if (dbmd==null) dbmd = connection.getMetaData(); // Only get the metadata once! } catch(Exception e) { throw new KettleDatabaseException("Unable to get database metadata from this database connection", e); } return dbmd; } public String getDDL(String tablename, RowMetaInterface fields) throws KettleDatabaseException { return getDDL(tablename, fields, null, false, null, true); } public String getDDL(String tablename, RowMetaInterface fields, String tk, boolean use_autoinc, String pk) throws KettleDatabaseException { return getDDL(tablename, fields, tk, use_autoinc, pk, true); } public String getDDL(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); String quotedTk = tk != null ? databaseMeta.quoteField(tk) : null; if (checkTableExists(tableName)) { retval=getAlterTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon); } else { retval=getCreateTableStatement(tableName, fields, quotedTk, use_autoinc, pk, semicolon); } return retval; } /** * Generates SQL * @param tableName the table name or schema/table combination: this needs to be quoted properly in advance. * @param fields the fields * @param tk the name of the technical key field * @param use_autoinc true if we need to use auto-increment fields for a primary key * @param pk the name of the primary/technical key field * @param semicolon append semicolon to the statement * @param pkc primary key composite ( name of the key fields) * @return the SQL needed to create the specified table and fields. */ public String getCreateTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) { StringBuilder retval = new StringBuilder("CREATE TABLE "); retval.append(tableName+Const.CR); retval.append("(").append(Const.CR); for (int i=0;i<fields.size();i++) { if (i>0) retval.append(", "); else retval.append(" "); ValueMetaInterface v=fields.getValueMeta(i); retval.append(databaseMeta.getFieldDefinition(v, tk, pk, use_autoinc)); } // At the end, before the closing of the statement, we might need to add some constraints... // Technical keys if (tk!=null) { if (databaseMeta.requiresCreateTablePrimaryKeyAppend()) { retval.append(", PRIMARY KEY (").append(tk).append(")").append(Const.CR); } } // Primary keys if (pk!=null) { if (databaseMeta.requiresCreateTablePrimaryKeyAppend()) { retval.append(", PRIMARY KEY (").append(pk).append(")").append(Const.CR); } } retval.append(")").append(Const.CR); if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta && databaseMeta.getIndexTablespace()!=null && databaseMeta.getIndexTablespace().length()>0) { retval.append("TABLESPACE ").append(databaseMeta.getDataTablespace()); } if (pk==null && tk==null && databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta) { retval.append("NO PARTITION"); // use this as a default when no pk/tk is there, otherwise you get an error } if (semicolon) retval.append(";"); // TODO: All this custom database code shouldn't really be in Database.java. It should be in the DB implementations. if (databaseMeta.getDatabaseInterface() instanceof VerticaDatabaseMeta) { retval.append(Const.CR).append("CREATE PROJECTION ").append(tableName).append("_unseg_super").append(Const.CR); retval.append("(").append(Const.CR); for (int i=0;i<fields.size();i++) { if (i>0) retval.append(", "); else retval.append(" "); retval.append(fields.getValueMeta(i).getName()).append(Const.CR); } retval.append(")").append(Const.CR); retval.append("AS SELECT").append(Const.CR); for (int i=0;i<fields.size();i++) { if (i>0) retval.append(", "); else retval.append(" "); retval.append(fields.getValueMeta(i).getName()).append(Const.CR); } retval.append("FROM ").append(tableName).append(Const.CR); retval.append("-- Replace UNSEGMENTED with a hash segmentation for optimum performance").append(Const.CR); retval.append("--SEGMENTED BY HASH(X,Y,Z)").append(Const.CR); retval.append("UNSEGMENTED ALL NODES").append(Const.CR); retval.append(";"); } return retval.toString(); } public String getAlterTableStatement(String tableName, RowMetaInterface fields, String tk, boolean use_autoinc, String pk, boolean semicolon) throws KettleDatabaseException { String retval=""; // Get the fields that are in the table now: RowMetaInterface tabFields = getTableFields(tableName); // Don't forget to quote these as well... databaseMeta.quoteReservedWords(tabFields); // Find the missing fields RowMetaInterface missing = new RowMeta(); for (int i=0;i<fields.size();i++) { ValueMetaInterface v = fields.getValueMeta(i); // Not found? if (tabFields.searchValueMeta( v.getName() )==null ) { missing.addValueMeta(v); // nope --> Missing! } } if (missing.size()!=0) { for (int i=0;i<missing.size();i++) { ValueMetaInterface v=missing.getValueMeta(i); retval+=databaseMeta.getAddColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // Find the surplus fields RowMetaInterface surplus = new RowMeta(); for (int i=0;i<tabFields.size();i++) { ValueMetaInterface v = tabFields.getValueMeta(i); // Found in table, not in input ? if (fields.searchValueMeta( v.getName() )==null ) { surplus.addValueMeta(v); // yes --> surplus! } } if (surplus.size()!=0) { for (int i=0;i<surplus.size();i++) { ValueMetaInterface v=surplus.getValueMeta(i); retval+=databaseMeta.getDropColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } // OK, see if there are fields for which we need to modify the type... (length, precision) RowMetaInterface modify = new RowMeta(); for (int i=0;i<fields.size();i++) { ValueMetaInterface desiredField = fields.getValueMeta(i); ValueMetaInterface currentField = tabFields.searchValueMeta( desiredField.getName()); if (desiredField!=null && currentField!=null) { String desiredDDL = databaseMeta.getFieldDefinition(desiredField, tk, pk, use_autoinc); String currentDDL = databaseMeta.getFieldDefinition(currentField, tk, pk, use_autoinc); boolean mod = !desiredDDL.equalsIgnoreCase(currentDDL); if (mod) { // System.out.println("Desired field: ["+desiredField.toStringMeta()+"], current field: ["+currentField.toStringMeta()+"]"); modify.addValueMeta(desiredField); } } } if (modify.size()>0) { for (int i=0;i<modify.size();i++) { ValueMetaInterface v=modify.getValueMeta(i); retval+=databaseMeta.getModifyColumnStatement(tableName, v, tk, use_autoinc, pk, true); } } return retval; } public void truncateTable(String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { execStatement(databaseMeta.getTruncateTableStatement(null, tablename)); } else { execStatement("DELETE FROM "+databaseMeta.quoteField(tablename)); } } public void truncateTable(String schema, String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { execStatement(databaseMeta.getTruncateTableStatement(schema, tablename)); } else { execStatement("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename)); } } /** * Execute a query and return at most one row from the resultset * @param sql The SQL for the query * @return one Row with data or null if nothing was found. */ public RowMetaAndData getOneRow(String sql) throws KettleDatabaseException { ResultSet rs = openQuery(sql); if (rs!=null) { Object[] row = getRow(rs); // One row only; try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } return new RowMetaAndData(rowMeta, row); } else { throw new KettleDatabaseException("error opening resultset for query: "+sql); } } public RowMeta getMetaFromRow( Object[] row, ResultSetMetaData md ) throws SQLException { RowMeta meta = new RowMeta(); for( int i=0; i<md.getColumnCount(); i++ ) { String name = md.getColumnName(i+1); ValueMetaInterface valueMeta = getValueFromSQLType( name, md, i+1, true, false ); meta.addValueMeta( valueMeta ); } return meta; } public RowMetaAndData getOneRow(String sql, RowMetaInterface param, Object[] data) throws KettleDatabaseException { ResultSet rs = openQuery(sql, param, data); if (rs!=null) { Object[] row = getRow(rs); // One value: a number; rowMeta=null; RowMeta tmpMeta = null; try { ResultSetMetaData md = rs.getMetaData(); tmpMeta = getMetaFromRow( row, md ); } catch (Exception e) { e.printStackTrace(); } finally { try { rs.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close resultset", e); } if (pstmt!=null) { try { pstmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement pstmt", e); } pstmt=null; } if (sel_stmt!=null) { try { sel_stmt.close(); } catch(Exception e) { throw new KettleDatabaseException("Unable to close prepared statement sel_stmt", e); } sel_stmt=null; } } return new RowMetaAndData(tmpMeta, row); } else { return null; } } public RowMetaInterface getParameterMetaData(PreparedStatement ps) { RowMetaInterface par = new RowMeta(); try { ParameterMetaData pmd = ps.getParameterMetaData(); for (int i=1;i<=pmd.getParameterCount();i++) { String name = "par"+i; int sqltype = pmd.getParameterType(i); int length = pmd.getPrecision(i); int precision = pmd.getScale(i); ValueMeta val; switch(sqltype) { case java.sql.Types.CHAR: case java.sql.Types.VARCHAR: val=new ValueMeta(name, ValueMetaInterface.TYPE_STRING); break; case java.sql.Types.BIGINT: case java.sql.Types.INTEGER: case java.sql.Types.NUMERIC: case java.sql.Types.SMALLINT: case java.sql.Types.TINYINT: val=new ValueMeta(name, ValueMetaInterface.TYPE_INTEGER); break; case java.sql.Types.DECIMAL: case java.sql.Types.DOUBLE: case java.sql.Types.FLOAT: case java.sql.Types.REAL: val=new ValueMeta(name, ValueMetaInterface.TYPE_NUMBER); break; case java.sql.Types.DATE: case java.sql.Types.TIME: case java.sql.Types.TIMESTAMP: val=new ValueMeta(name, ValueMetaInterface.TYPE_DATE); break; case java.sql.Types.BOOLEAN: case java.sql.Types.BIT: val=new ValueMeta(name, ValueMetaInterface.TYPE_BOOLEAN); break; default: val=new ValueMeta(name, ValueMetaInterface.TYPE_NONE); break; } if (val.isNumeric() && ( length>18 || precision>18) ) { val = new ValueMeta(name, ValueMetaInterface.TYPE_BIGNUMBER); } par.addValueMeta(val); } } // Oops: probably the database or JDBC doesn't support it. catch(AbstractMethodError e) { return null; } catch(SQLException e) { return null; } catch(Exception e) { return null; } return par; } public int countParameters(String sql) { int q=0; boolean quote_opened=false; boolean dquote_opened=false; for (int x=0;x<sql.length();x++) { char c = sql.charAt(x); switch(c) { case '\'': quote_opened= !quote_opened; break; case '"' : dquote_opened=!dquote_opened; break; case '?' : if (!quote_opened && !dquote_opened) q++; break; } } return q; } // Get the fields back from an SQL query public RowMetaInterface getParameterMetaData(String sql, RowMetaInterface inform, Object[] data) { // The database couldn't handle it: try manually! int q=countParameters(sql); RowMetaInterface par=new RowMeta(); if (inform!=null && q==inform.size()) { for (int i=0;i<q;i++) { ValueMetaInterface inf=inform.getValueMeta(i); ValueMetaInterface v = inf.clone(); par.addValueMeta(v); } } else { for (int i=0;i<q;i++) { ValueMetaInterface v = new ValueMeta("name"+i, ValueMetaInterface.TYPE_NUMBER); par.addValueMeta(v); } } return par; } public void writeLogRecord(LogTableInterface logTable, LogStatus status, Object subject) throws KettleException { try { RowMetaAndData logRecord = logTable.getLogRecord(status, subject); boolean update = (logTable.getKeyField()!=null) && !status.equals(LogStatus.START); String schemaTable = databaseMeta.getSchemaTableCombination(logTable.getSchemaName(), logTable.getTableName()); RowMetaInterface rowMeta = logRecord.getRowMeta(); Object[] rowData = logRecord.getData(); if (update) { RowMetaInterface updateRowMeta = new RowMeta(); Object[] updateRowData = new Object[rowMeta.size()]; ValueMetaInterface keyValueMeta = rowMeta.getValueMeta(0); String sql = "UPDATE " + schemaTable + " SET "; for (int i = 1; i < rowMeta.size() ; i++) // Without ID_JOB or ID_BATCH { ValueMetaInterface valueMeta = rowMeta.getValueMeta(i); if (i > 1) { sql += ", "; } sql += databaseMeta.quoteField(valueMeta.getName()) + "=? "; updateRowMeta.addValueMeta(valueMeta); updateRowData[i-1] = rowData[i]; } sql += "WHERE "; sql += databaseMeta.quoteField(keyValueMeta.getName()) + "=? "; updateRowMeta.addValueMeta(keyValueMeta); updateRowData[rowMeta.size()-1] = rowData[0]; execStatement(sql, updateRowMeta, updateRowData); } else { insertRow(logTable.getSchemaName(), logTable.getTableName(), logRecord.getRowMeta(), logRecord.getData()); } } catch(Exception e) { throw new KettleDatabaseException("Unable to write log record to log table " + logTable.getTableName(), e); } } public void cleanupLogRecords(LogTableInterface logTable) throws KettleException { try { double timeout = Const.toDouble( Const.trim( environmentSubstitute( logTable.getTimeoutInDays())), 0.0 ); if (timeout>0.000001) { // The timeout has to be at least a few seconds, otherwise we don't bother String schemaTable = databaseMeta.getSchemaTableCombination(logTable.getSchemaName(), logTable.getTableName()); // The log date field LogTableField logField = logTable.getLogDateField(); if (logField!=null) { String sql = "DELETE FROM "+schemaTable+" WHERE "+databaseMeta.quoteField(logField.getFieldName())+" < ?"; // $NON-NLS$1 // Now calculate the date... long now = System.currentTimeMillis(); long limit = now - Math.round(timeout*24*60*60*1000); RowMetaAndData row = new RowMetaAndData(); row.addValue(logField.getFieldName(), ValueMetaInterface.TYPE_DATE, new Date(limit)); execStatement(sql, row.getRowMeta(), row.getData()); } else { throw new KettleException(BaseMessages.getString(PKG, "Database.Exception.LogTimeoutDefinedOnTableWithoutLogField", logTable.getTableName())); } } } catch(Exception e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToCleanUpOlderRecordsFromLogTable", logTable.getTableName()), e); } } public Object[] getLastLogDate( String logtable, String name, boolean job, LogStatus status ) throws KettleDatabaseException { Object[] row = null; String jobtrans = job?databaseMeta.quoteField("JOBNAME"):databaseMeta.quoteField("TRANSNAME"); String sql = ""; sql+=" SELECT "+databaseMeta.quoteField("ENDDATE")+", "+databaseMeta.quoteField("DEPDATE")+", "+databaseMeta.quoteField("STARTDATE"); sql+=" FROM "+logtable; sql+=" WHERE "+databaseMeta.quoteField("ERRORS")+" = 0"; sql+=" AND "+databaseMeta.quoteField("STATUS")+" = 'end'"; sql+=" AND "+jobtrans+" = ?"; sql+=" ORDER BY "+databaseMeta.quoteField("LOGDATE")+" DESC, "+databaseMeta.quoteField("ENDDATE")+" DESC"; try { pstmt = connection.prepareStatement(databaseMeta.stripCR(sql)); RowMetaInterface r = new RowMeta(); r.addValueMeta( new ValueMeta("TRANSNAME", ValueMetaInterface.TYPE_STRING)); setValues(r, new Object[] { name }); ResultSet res = pstmt.executeQuery(); if (res!=null) { rowMeta = getRowInfo(res.getMetaData(), false, false); row = getRow(res); res.close(); } pstmt.close(); pstmt=null; } catch(SQLException ex) { throw new KettleDatabaseException("Unable to obtain last logdate from table "+logtable, ex); } return row; } public synchronized Long getNextValue(Hashtable<String,Counter> counters, String tableName, String val_key) throws KettleDatabaseException { return getNextValue(counters, null, tableName, val_key); } public synchronized Long getNextValue(Hashtable<String,Counter> counters, String schemaName, String tableName, String val_key) throws KettleDatabaseException { Long nextValue = null; String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); String lookup = schemaTable+"."+databaseMeta.quoteField(val_key); // Try to find the previous sequence value... Counter counter = null; if (counters!=null) counter=counters.get(lookup); if (counter==null) { RowMetaAndData rmad = getOneRow("SELECT MAX("+databaseMeta.quoteField(val_key)+") FROM "+schemaTable); if (rmad!=null) { long previous; try { Long tmp = rmad.getRowMeta().getInteger(rmad.getData(), 0); // A "select max(x)" on a table with no matching rows will return null. if ( tmp != null ) previous = tmp.longValue(); else previous = 0L; } catch (KettleValueException e) { throw new KettleDatabaseException("Error getting the first long value from the max value returned from table : "+schemaTable); } counter = new Counter(previous+1, 1); nextValue = Long.valueOf( counter.next() ); if (counters!=null) counters.put(lookup, counter); } else { throw new KettleDatabaseException("Couldn't find maximum key value from table "+schemaTable); } } else { nextValue = Long.valueOf( counter.next() ); } return nextValue; } public String toString() { if (databaseMeta!=null) return databaseMeta.getName(); else return "-"; } public boolean isSystemTable(String table_name) { return databaseMeta.isSystemTable(table_name); } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(String sql, int limit) throws KettleDatabaseException { return getRows(sql, limit, null); } /** Reads the result of an SQL query into an ArrayList * * @param sql The SQL to launch * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(String sql, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { if (monitor!=null) monitor.setTaskName("Opening query..."); ResultSet rset = openQuery(sql); return getRows(rset, limit, monitor); } /** Reads the result of a ResultSet into an ArrayList * * @param rset the ResultSet to read out * @param limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException if something goes wrong. */ public List<Object[]> getRows(ResultSet rset, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { try { List<Object[]> result = new ArrayList<Object[]>(); boolean stop=false; int i=0; if (rset!=null) { if (monitor!=null && limit>0) monitor.beginTask("Reading rows...", limit); while ((limit<=0 || i<limit) && !stop) { Object[] row = getRow(rset); if (row!=null) { result.add(row); i++; } else { stop=true; } if (monitor!=null && limit>0) monitor.worked(1); } closeQuery(rset); if (monitor!=null) monitor.done(); } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of rows from ResultSet : ", e); } } public List<Object[]> getFirstRows(String table_name, int limit) throws KettleDatabaseException { return getFirstRows(table_name, limit, null); } /** * Get the first rows from a table (for preview) * @param table_name The table name (or schema/table combination): this needs to be quoted properly * @param limit limit <=0 means unlimited, otherwise this specifies the maximum number of rows read. * @param monitor The progress monitor to update while getting the rows. * @return An ArrayList of rows. * @throws KettleDatabaseException in case something goes wrong */ public List<Object[]> getFirstRows(String table_name, int limit, ProgressMonitorListener monitor) throws KettleDatabaseException { String sql = "SELECT"; if (databaseMeta.getDatabaseInterface() instanceof NeoviewDatabaseMeta) { sql+=" [FIRST " + limit +"]"; } else if (databaseMeta.getDatabaseInterface() instanceof SybaseIQDatabaseMeta) // improve support Sybase IQ { sql+=" TOP " + limit +" "; } sql += " * FROM "+table_name; if (limit>0) { sql+=databaseMeta.getLimitClause(limit); } return getRows(sql, limit, monitor); } public RowMetaInterface getReturnRowMeta() { return rowMeta; } public String[] getTableTypes() throws KettleDatabaseException { try { ArrayList<String> types = new ArrayList<String>(); ResultSet rstt = getDatabaseMetaData().getTableTypes(); while(rstt.next()) { String ttype = rstt.getString("TABLE_TYPE"); types.add(ttype); } return types.toArray(new String[types.size()]); } catch(SQLException e) { throw new KettleDatabaseException("Unable to get table types from database!", e); } } public String[] getTablenames() throws KettleDatabaseException { return getTablenames(false); } public String[] getTablenames(boolean includeSchema) throws KettleDatabaseException { return getTablenames(null, includeSchema); } public String[] getTablenames(String schemanamein, boolean includeSchema) throws KettleDatabaseException { String schemaname=schemanamein; if(schemaname==null) { if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase(); } List<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = getDatabaseMetaData().getTables(null, schemaname, null, databaseMeta.getTableTypes() ); while (alltables.next()) { // due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety String cat = ""; try { cat = alltables.getString("TABLE_CAT"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting tables for field TABLE_CAT (ignored): "+e.toString()); } String schema = ""; try { schema = alltables.getString("TABLE_SCHEM"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting tables for field TABLE_SCHEM (ignored): "+e.toString()); } if (Const.isEmpty(schema)) schema = cat; String table = alltables.getString("TABLE_NAME"); String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got table from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { log.logError("Error getting tablenames from schema ["+schemaname+"]"); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } if(log.isDetailed()) log.logDetailed("read :"+names.size()+" table names from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getViews() throws KettleDatabaseException { return getViews(false); } public String[] getViews(boolean includeSchema) throws KettleDatabaseException { return getViews(null, includeSchema); } public String[] getViews(String schemanamein, boolean includeSchema) throws KettleDatabaseException { if (!databaseMeta.supportsViews()) return new String[] {}; String schemaname = schemanamein; if(schemaname==null) { if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase(); } ArrayList<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getViewTypes() ); while (alltables.next()) { // due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety String cat = ""; try { cat = alltables.getString("TABLE_CAT"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting views for field TABLE_CAT (ignored): "+e.toString()); } String schema = ""; try { schema = alltables.getString("TABLE_SCHEM"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting views for field TABLE_SCHEM (ignored): "+e.toString()); } if (Const.isEmpty(schema)) schema = cat; String table = alltables.getString("TABLE_NAME"); String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting views from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting views from schema ["+schemaname+"]", e); } } if(log.isDetailed()) log.logDetailed("read :"+names.size()+" views from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getSynonyms() throws KettleDatabaseException { return getSynonyms(false); } public String[] getSynonyms(boolean includeSchema) throws KettleDatabaseException { return getSynonyms(null,includeSchema); } public String[] getSynonyms(String schemanamein, boolean includeSchema) throws KettleDatabaseException { if (!databaseMeta.supportsSynonyms()) return new String[] {}; String schemaname = schemanamein; if(schemaname==null) { if (databaseMeta.useSchemaNameForTableList()) schemaname = environmentSubstitute(databaseMeta.getUsername()).toUpperCase(); } ArrayList<String> names = new ArrayList<String>(); ResultSet alltables=null; try { alltables = dbmd.getTables(null, schemaname, null, databaseMeta.getSynonymTypes() ); while (alltables.next()) { // due to PDI-743 with ODBC and MS SQL Server the order is changed and try/catch included for safety String cat = ""; try { cat = alltables.getString("TABLE_CAT"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting synonyms for field TABLE_CAT (ignored): "+e.toString()); } String schema = ""; try { schema = alltables.getString("TABLE_SCHEM"); } catch (Exception e) { // ignore if(log.isDebug()) log.logDebug("Error getting synonyms for field TABLE_SCHEM (ignored): "+e.toString()); } if (Const.isEmpty(schema)) schema = cat; String table = alltables.getString("TABLE_NAME"); String schemaTable; if (includeSchema) schemaTable = databaseMeta.getQuotedSchemaTableCombination(schema, table); else schemaTable = table; if (log.isRowLevel()) log.logRowlevel(toString(), "got view from meta-data: "+schemaTable); names.add(schemaTable); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting synonyms from schema ["+schemaname+"]", e); } finally { try { if (alltables!=null) alltables.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting synonyms from schema ["+schemaname+"]", e); } } if(log.isDetailed()) log.logDetailed("read :"+names.size()+" views from db meta-data."); return names.toArray(new String[names.size()]); } public String[] getSchemas() throws KettleDatabaseException { ArrayList<String> catalogList = new ArrayList<String>(); ResultSet catalogResultSet=null; try { catalogResultSet =getDatabaseMetaData().getSchemas(); // Grab all the catalog names and put them in an array list while (catalogResultSet!=null && catalogResultSet.next()) { catalogList.add(catalogResultSet.getString(1)); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting schemas!", e); } finally { try { if (catalogResultSet!=null) catalogResultSet.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting schemas!", e); } } if(log.isDetailed()) log.logDetailed("read :"+catalogList.size()+" schemas from db meta-data."); return catalogList.toArray(new String[catalogList.size()]); } public String[] getCatalogs() throws KettleDatabaseException { ArrayList<String> catalogList = new ArrayList<String>(); ResultSet catalogResultSet=null; try { catalogResultSet =getDatabaseMetaData().getCatalogs(); // Grab all the catalog names and put them in an array list while (catalogResultSet!=null && catalogResultSet.next()) { catalogList.add(catalogResultSet.getString(1)); } } catch(SQLException e) { throw new KettleDatabaseException("Error getting catalogs!", e); } finally { try { if (catalogResultSet!=null) catalogResultSet.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing resultset after getting catalogs!", e); } } if(log.isDetailed()) log.logDetailed(toString(), "read :"+catalogList.size()+" catalogs from db meta-data."); return catalogList.toArray(new String[catalogList.size()]); } public String[] getProcedures() throws KettleDatabaseException { String sql = databaseMeta.getSQLListOfProcedures(); if (sql!=null) { //System.out.println("SQL= "+sql); List<Object[]> procs = getRows(sql, 1000); //System.out.println("Found "+procs.size()+" rows"); String[] str = new String[procs.size()]; for (int i=0;i<procs.size();i++) { str[i] = ((Object[])procs.get(i))[0].toString(); } return str; } else { ResultSet rs = null; try { DatabaseMetaData dbmd = getDatabaseMetaData(); rs = dbmd.getProcedures(null, null, null); List<Object[]> rows = getRows(rs, 0, null); String result[] = new String[rows.size()]; for (int i=0;i<rows.size();i++) { Object[] row = (Object[])rows.get(i); String procCatalog = rowMeta.getString(row, "PROCEDURE_CAT", null); String procSchema = rowMeta.getString(row, "PROCEDURE_SCHEMA", null); String procName = rowMeta.getString(row, "PROCEDURE_NAME", ""); String name = ""; if (procCatalog!=null) name+=procCatalog+"."; else if (procSchema!=null) name+=procSchema+"."; name+=procName; result[i] = name; } return result; } catch(Exception e) { throw new KettleDatabaseException("Unable to get list of procedures from database meta-data: ", e); } finally { if (rs!=null) try { rs.close(); } catch(Exception e) {} } } } public boolean isAutoCommit() { return commitsize<=0; } /** * @return Returns the databaseMeta. */ public DatabaseMeta getDatabaseMeta() { return databaseMeta; } /** * Lock a tables in the database for write operations * @param tableNames The tables to lock * @throws KettleDatabaseException */ public void lockTables(String tableNames[]) throws KettleDatabaseException { if (Const.isEmpty(tableNames)) return; // Quote table names too... String[] quotedTableNames = new String[tableNames.length]; for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.getQuotedSchemaTableCombination(null, tableNames[i]); // Get the SQL to lock the (quoted) tables String sql = databaseMeta.getSQLLockTables(quotedTableNames); if (sql!=null) { execStatements(sql); } } /** * Unlock certain tables in the database for write operations * @param tableNames The tables to unlock * @throws KettleDatabaseException */ public void unlockTables(String tableNames[]) throws KettleDatabaseException { if (Const.isEmpty(tableNames)) return; // Quote table names too... String[] quotedTableNames = new String[tableNames.length]; for (int i=0;i<tableNames.length;i++) quotedTableNames[i] = databaseMeta.getQuotedSchemaTableCombination(null, tableNames[i]); // Get the SQL to unlock the (quoted) tables String sql = databaseMeta.getSQLUnlockTables(quotedTableNames); if (sql!=null) { execStatement(sql); } } /** * @return the opened */ public int getOpened() { return opened; } /** * @param opened the opened to set */ public void setOpened(int opened) { this.opened = opened; } /** * @return the connectionGroup */ public String getConnectionGroup() { return connectionGroup; } /** * @param connectionGroup the connectionGroup to set */ public void setConnectionGroup(String connectionGroup) { this.connectionGroup = connectionGroup; } /** * @return the partitionId */ public String getPartitionId() { return partitionId; } /** * @param partitionId the partitionId to set */ public void setPartitionId(String partitionId) { this.partitionId = partitionId; } /** * @return the copy */ public int getCopy() { return copy; } /** * @param copy the copy to set */ public void setCopy(int copy) { this.copy = copy; } public void copyVariablesFrom(VariableSpace space) { variables.copyVariablesFrom(space); } public String environmentSubstitute(String aString) { return variables.environmentSubstitute(aString); } public String[] environmentSubstitute(String aString[]) { return variables.environmentSubstitute(aString); } public VariableSpace getParentVariableSpace() { return variables.getParentVariableSpace(); } public void setParentVariableSpace(VariableSpace parent) { variables.setParentVariableSpace(parent); } public String getVariable(String variableName, String defaultValue) { return variables.getVariable(variableName, defaultValue); } public String getVariable(String variableName) { return variables.getVariable(variableName); } public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) { if (!Const.isEmpty(variableName)) { String value = environmentSubstitute(variableName); if (!Const.isEmpty(value)) { return ValueMeta.convertStringToBoolean(value); } } return defaultValue; } public void initializeVariablesFrom(VariableSpace parent) { variables.initializeVariablesFrom(parent); } public String[] listVariables() { return variables.listVariables(); } public void setVariable(String variableName, String variableValue) { variables.setVariable(variableName, variableValue); } public void shareVariablesWith(VariableSpace space) { variables = space; // Also share the variables with the meta data object // Make sure it's not the databaseMeta object itself. We would get an infinite loop in that case. if (space!=databaseMeta) databaseMeta.shareVariablesWith(space); } public void injectVariables(Map<String,String> prop) { variables.injectVariables(prop); } public RowMetaAndData callProcedure(String arg[], String argdir[], int argtype[], String resultname, int resulttype) throws KettleDatabaseException { RowMetaAndData ret; try { cstmt.execute(); ret = new RowMetaAndData(); int pos = 1; if (resultname != null && resultname.length() != 0) { ValueMeta vMeta = new ValueMeta(resultname, resulttype); Object v =null; switch (resulttype) { case ValueMetaInterface.TYPE_BOOLEAN: v=Boolean.valueOf(cstmt.getBoolean(pos)); break; case ValueMetaInterface.TYPE_NUMBER: v=new Double(cstmt.getDouble(pos)); break; case ValueMetaInterface.TYPE_BIGNUMBER: v=cstmt.getBigDecimal(pos); break; case ValueMetaInterface.TYPE_INTEGER: v=Long.valueOf(cstmt.getLong(pos)); break; case ValueMetaInterface.TYPE_STRING: v=cstmt.getString(pos); break; case ValueMetaInterface.TYPE_BINARY: if (databaseMeta.supportsGetBlob()) { Blob blob = cstmt.getBlob(pos); if (blob!=null) { v = blob.getBytes(1L, (int)blob.length()); } else { v = null; } } else { v = cstmt.getBytes(pos); } break; case ValueMetaInterface.TYPE_DATE: if (databaseMeta.supportsTimeStampToDateConversion()) { v=cstmt.getTimestamp(pos); } else { v=cstmt.getDate(pos); } break; } ret.addValue(vMeta, v); pos++; } for (int i = 0; i < arg.length; i++) { if (argdir[i].equalsIgnoreCase("OUT") || argdir[i].equalsIgnoreCase("INOUT")) { ValueMeta vMeta = new ValueMeta(arg[i], argtype[i]); Object v=null; switch (argtype[i]) { case ValueMetaInterface.TYPE_BOOLEAN: v=Boolean.valueOf(cstmt.getBoolean(pos + i)); break; case ValueMetaInterface.TYPE_NUMBER: v=new Double(cstmt.getDouble(pos + i)); break; case ValueMetaInterface.TYPE_BIGNUMBER: v=cstmt.getBigDecimal(pos + i); break; case ValueMetaInterface.TYPE_INTEGER: v=Long.valueOf(cstmt.getLong(pos + i)); break; case ValueMetaInterface.TYPE_STRING: v=cstmt.getString(pos + i); break; case ValueMetaInterface.TYPE_BINARY: if (databaseMeta.supportsGetBlob()) { Blob blob = cstmt.getBlob(pos + i); if (blob!=null) { v = blob.getBytes(1L, (int)blob.length()); } else { v = null; } } else { v = cstmt.getBytes(pos + i); } break; case ValueMetaInterface.TYPE_DATE: if (databaseMeta.supportsTimeStampToDateConversion()) { v=cstmt.getTimestamp(pos + i); } else { v=cstmt.getDate(pos + i); } break; } ret.addValue(vMeta, v); } } return ret; } catch (SQLException ex) { throw new KettleDatabaseException("Unable to call procedure", ex); } } /** * Return SQL CREATION statement for a Table * @param tableName The table to create * @throws KettleDatabaseException */ public String getDDLCreationTable(String tableName, RowMetaInterface fields) throws KettleDatabaseException { String retval; // First, check for reserved SQL in the input row r... databaseMeta.quoteReservedWords(fields); String quotedTk=databaseMeta.quoteField(null); retval=getCreateTableStatement(tableName, fields, quotedTk, false, null, true); return retval; } /** * Return SQL TRUNCATE statement for a Table * @param schema The schema * @param tableNameWithSchema The table to create * @throws KettleDatabaseException */ public String getDDLTruncateTable(String schema, String tablename) throws KettleDatabaseException { if (Const.isEmpty(connectionGroup)) { return(databaseMeta.getTruncateTableStatement(schema, tablename)); } else { return("DELETE FROM "+databaseMeta.getQuotedSchemaTableCombination(schema, tablename)); } } /** * Return SQL statement (INSERT INTO TableName ... * @param schemaName tableName The schema * @param tableName * @param fields * @param dateFormat date format of field * @throws KettleDatabaseException */ public String getSQLOutput(String schemaName, String tableName, RowMetaInterface fields, Object[] r,String dateFormat) throws KettleDatabaseException { StringBuffer ins=new StringBuffer(128); try{ String schemaTable = databaseMeta.getQuotedSchemaTableCombination(schemaName, tableName); ins.append("INSERT INTO ").append(schemaTable).append('('); // now add the names in the row: for (int i=0;i<fields.size();i++) { if (i>0) ins.append(", "); String name = fields.getValueMeta(i).getName(); ins.append(databaseMeta.quoteField(name)); } ins.append(") VALUES ("); java.text.SimpleDateFormat[] fieldDateFormatters = new java.text.SimpleDateFormat[fields.size()]; // new add values ... for (int i=0;i<fields.size();i++) { ValueMetaInterface valueMeta = fields.getValueMeta(i); Object valueData = r[i]; if (i>0) ins.append(","); // Check for null values... if (valueMeta.isNull(valueData)) { ins.append("null"); } else { // Normal cases... switch(valueMeta.getType()) { case ValueMetaInterface.TYPE_BOOLEAN: case ValueMetaInterface.TYPE_STRING: String string = valueMeta.getString(valueData); // Have the database dialect do the quoting. // This also adds the single quotes around the string (thanks to PostgreSQL) string = databaseMeta.quoteSQLString(string); ins.append(string) ; break; case ValueMetaInterface.TYPE_DATE: Date date = fields.getDate(r,i); if (Const.isEmpty(dateFormat)) if (databaseMeta.getDatabaseInterface() instanceof OracleDatabaseMeta) { if (fieldDateFormatters[i]==null) { fieldDateFormatters[i]=new java.text.SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); } ins.append("TO_DATE('").append(fieldDateFormatters[i].format(date)).append("', 'YYYY/MM/DD HH24:MI:SS')"); } else { ins.append("'" + fields.getString(r,i)+ "'") ; } else { try { java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(dateFormat); ins.append("'" + formatter.format(fields.getDate(r,i))+ "'") ; } catch(Exception e) { throw new KettleDatabaseException("Error : ", e); } } break; default: ins.append( fields.getString(r,i)) ; break; } } } ins.append(')'); }catch (Exception e) { throw new KettleDatabaseException(e); } return ins.toString(); } public Savepoint setSavepoint() throws KettleDatabaseException { try { return connection.setSavepoint(); } catch (SQLException e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToSetSavepoint"), e); } } public Savepoint setSavepoint(String savePointName) throws KettleDatabaseException { try { return connection.setSavepoint(savePointName); } catch (SQLException e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToSetSavepointName", savePointName), e); } } public void releaseSavepoint(Savepoint savepoint) throws KettleDatabaseException { try { connection.releaseSavepoint(savepoint); } catch (SQLException e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToReleaseSavepoint"), e); } } public void rollback(Savepoint savepoint) throws KettleDatabaseException { try { connection.rollback(savepoint); } catch (SQLException e) { throw new KettleDatabaseException(BaseMessages.getString(PKG, "Database.Exception.UnableToRollbackToSavepoint"), e); } } public Object getParentObject() { return parentLoggingObject; } /** * Return primary key column names ... * @param tablename * @throws KettleDatabaseException */ public String[] getPrimaryKeyColumnNames(String tablename) throws KettleDatabaseException { List<String> names = new ArrayList<String>(); ResultSet allkeys=null; try { allkeys=getDatabaseMetaData().getPrimaryKeys(null, null, tablename); while (allkeys.next()) { String keyname=allkeys.getString("PK_NAME"); String col_name=allkeys.getString("COLUMN_NAME"); if(!names.contains(col_name)) names.add(col_name); if (log.isRowLevel()) log.logRowlevel(toString(), "getting key : "+keyname + " on column "+col_name); } } catch(SQLException e) { log.logError(toString(), "Error getting primary keys columns from table ["+tablename+"]"); } finally { try { if (allkeys!=null) allkeys.close(); } catch(SQLException e) { throw new KettleDatabaseException("Error closing connection while searching primary keys in table ["+tablename+"]", e); } } return names.toArray(new String[names.size()]); } /** * Return all sequence names from connection * @return The sequences name list. * @throws KettleDatabaseException */ public String[] getSequences() throws KettleDatabaseException { if(databaseMeta.supportsSequences()) { String sql = databaseMeta.getSQLListOfSequences(); if (sql!=null) { List<Object[]> seqs = getRows(sql, 0); String[] str = new String[seqs.size()]; for (int i=0;i<seqs.size();i++) { str[i] = ((Object[])seqs.get(i))[0].toString(); } return str; } }else { throw new KettleDatabaseException("Sequences are only available for Oracle databases."); } return null; } public String getFilename() { return null; } public String getLogChannelId() { return log.getLogChannelId(); } public String getObjectName() { return databaseMeta.getName(); } public String getObjectCopy() { return null; } public ObjectId getObjectId() { return databaseMeta.getObjectId(); } public ObjectRevision getObjectRevision() { return databaseMeta.getObjectRevision(); } public LoggingObjectType getObjectType() { return LoggingObjectType.DATABASE; } public LoggingObjectInterface getParent() { return parentLoggingObject; } public RepositoryDirectory getRepositoryDirectory() { return null; } public LogLevel getLogLevel() { return logLevel; } public void setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; log.setLogLevel(logLevel); } /** * @return the carteObjectId */ public String getContainerObjectId() { return containerObjectId; } /** * @param containerObjectId the execution container Object id to set */ public void setContainerObjectId(String containerObjectId) { this.containerObjectId = containerObjectId; } }
package jolie.net.http; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.io.OutputStream; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.ByteArrayOutputStream; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; import jolie.net.CommChannel; import jolie.runtime.ByteArray; /** * Utilities for handling HTTP messages. * @author Fabrizio Montesi */ public class HttpUtils { public final static String CRLF = new String(new char[]{13, 10}); public final static String URL_DECODER_ENC = "UTF-8"; // Checks if the message requests the channel to be closed or kept open public static void recv_checkForChannelClosing( HttpMessage message, CommChannel channel ) { if ( channel != null ) { HttpMessage.Version version = message.version(); if ( version == null || version.equals( HttpMessage.Version.HTTP_1_1 ) ) { // The default is to keep the connection open, unless Connection: close is specified if ( message.getPropertyOrEmptyString( "connection" ).equalsIgnoreCase( "close" ) ) { channel.setToBeClosed( true ); } else { channel.setToBeClosed( false ); } } else if ( version.equals( HttpMessage.Version.HTTP_1_0 ) ) { // The default is to close the connection, unless Connection: Keep-Alive is specified if ( message.getPropertyOrEmptyString( "connection" ).equalsIgnoreCase( "keep-alive" ) ) { channel.setToBeClosed( false ); } else { channel.setToBeClosed( true ); } } } } public static String httpMessageTypeToString( HttpMessage.Type type ) { switch ( type ) { case GET: return "get"; case HEAD: return "head"; case POST: return "post"; case DELETE: return "delete"; case PUT: return "put"; } return null; } public static void errorGenerator( OutputStream ostream, IOException e ) throws IOException { Writer writer = new OutputStreamWriter( ostream ); if ( e instanceof UnsupportedEncodingException ) { writer.write( "HTTP/1.1 415 Unsupported Media Type" + CRLF ); } else if ( e instanceof UnsupportedMethodException ) { UnsupportedMethodException ex = ( UnsupportedMethodException ) e; if ( ex.allowedMethods() == null ) { writer.write( "HTTP/1.1 501 Not Implemented" + CRLF ); } else { writer.write( "HTTP/1.1 405 Method Not Allowed" + CRLF ); writer.write( "Allowed: " ); Method[] methods = ex.allowedMethods(); for ( int i = 0; i < methods.length; i++ ) { writer.write( methods[i].id() + ( i+1 < methods.length ? ", " : "" ) ); } writer.write( CRLF ); } } else if ( e instanceof UnsupportedHttpVersionException ) { writer.write( "HTTP/1.1 505 HTTP Version Not Supported" + CRLF ); } else { writer.write( "HTTP/1.1 500 Internal Server Error" + CRLF ); } String message = e.getMessage() != null ? e.getMessage() : e.toString(); ByteArray content = new ByteArray( message.getBytes( "utf-8" ) ); writer.write( "Server: Jolie" + CRLF ); writer.write( "Content-Type: text/plain; charset=utf-8" + CRLF ); writer.write( "Content-Length: " + content.size() + CRLF + CRLF ); writer.flush(); ostream.write( content.getBytes() ); ostream.flush(); } public static String getCharset( String defaultCharset, HttpMessage message ) { if ( message != null && message.getProperty( "content-type" ) != null ) { String[] contentType = message.getProperty( "content-type" ).split( ";" ); for ( int i = 1; i < contentType.length; i++ ) { if ( contentType[i].toLowerCase().contains( "charset" ) ) { String pair[] = contentType[i].split( "=", 2 ); if ( pair.length == 2 ) { return pair[1]; } } } } if ( defaultCharset != null && !defaultCharset.isEmpty() ) { return defaultCharset; } return "utf-8"; // Jolie's default charset which is today's standard } public static ByteArray encode( String encoding, ByteArray content, StringBuilder headerBuilder ) throws IOException { if ( encoding.contains( "gzip" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); GZIPOutputStream outStream = new GZIPOutputStream( baOutStream ); outStream.write( content.getBytes() ); outStream.close(); content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: gzip" + HttpUtils.CRLF ); } else if ( encoding.contains( "deflate" ) ) { ByteArrayOutputStream baOutStream = new ByteArrayOutputStream(); DeflaterOutputStream outStream = new DeflaterOutputStream( baOutStream ); outStream.write( content.getBytes() ); outStream.close(); content = new ByteArray( baOutStream.toByteArray() ); headerBuilder.append( "Content-Encoding: deflate" + HttpUtils.CRLF ); } return content; } }
package JpAws; import java.io.IOException; import java.rmi.AlreadyBoundException; import java.rmi.RMISecurityManager; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import system.ClientToMaster; import system.FileSystem; import system.Master; /** * * @author Charles Munger */ public class Ec2Master extends Master { private WorkerMachines workerMachines; Ec2Master() throws RemoteException {} public static void main(String[] args) throws RemoteException, AlreadyBoundException { System.setSecurityManager(new RMISecurityManager()); Registry registry = LocateRegistry.createRegistry(Master.PORT); ClientToMaster master = new Ec2Master(); registry.bind(SERVICE_NAME, master); master.init(Integer.parseInt(args[0])); System.out.println("Ec2Master: Ready."); } @Override public void shutdown() { System.out.println("Master.shutdown: notifying Worker Services to shutdown."); // shutdown all Worker Services try { workerMachines.Stop(); } catch (IOException ex) { System.out.println("Exception shutting down workers. Check webUI for zombie instances."); } System.out.println("Master.shutdown: Worker Services shutdown."); // shutdown Master System.out.println("Master.shutdown: shutting down."); } @Override public FileSystem makeFileSystem(String jobDirectoryName) { return new S3FileSystem(jobDirectoryName); } }
package org.mwc.asset.scenariocontroller2; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.FileNotFoundException; import java.util.Enumeration; import java.util.Vector; import junit.framework.TestCase; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.widgets.Display; import org.junit.Test; import org.mwc.asset.scenariocontroller2.views.MultiScenarioView.UIDisplay; import org.mwc.asset.scenariocontroller2.views.ScenarioWrapper; import org.mwc.cmap.core.CorePlugin; import org.mwc.cmap.core.property_support.EditableWrapper; import ASSET.ScenarioType; import ASSET.GUI.CommandLine.CommandLine; import ASSET.GUI.CommandLine.CommandLine.ASSETProgressMonitor; import ASSET.GUI.CommandLine.MultiScenarioCore; import ASSET.Scenario.ScenarioSteppedListener; import ASSET.Scenario.Observers.RecordToFileObserverType; import ASSET.Scenario.Observers.ScenarioObserver; import ASSET.Util.XML.ASSETReaderWriter; import ASSET.Util.XML.ScenarioHandler; import ASSET.Util.XML.Control.StandaloneObserverListHandler; import ASSET.Util.XML.Control.Observers.ScenarioControllerHandler; public class MultiScenarioPresenter extends CoreControllerPresenter { /** * package up an operation with a progress monitor * * @author ian * */ public static interface JobWithProgress { void run(ASSETProgressMonitor montor); } /** * objects that handle a series of runs * * @author ian * */ public static interface ManageMultiListener { /** * trigger scenario generation * */ void doGenerate(); /** * trigger stepping through the scenarios * */ void doRunAll(); } /** * display (view) for scenario controller * * @author ian * */ public static interface MultiScenarioDisplay extends ScenarioDisplay { /** * listen out for scenarios being selected from the list * */ public void addSelectionChangedListener(ISelectionChangedListener listener); /** * someone is listening to the run/generate buttons * * @param listener */ void addMultiScenarioHandler(ManageMultiListener listener); /** * new controller loaded, ditch generated scenarios * */ void clearScenarios(); /** * start this monster job running * * @param theJob */ void runThisJob(JobWithProgress theJob); /** * get the detailed display components * * @return */ UIDisplay getUI(); /** * update the list of scenarios * * @param _myModel */ void setScenarios(MultiScenarioCore _myModel); } /** * our data model * */ private MultiScenarioCore _myModel; /** * our view * */ MultiScenarioDisplay _myDisplay; /** * the currently selected scenario * */ private ScenarioWrapper _currentScen; /** * listener to let us watch the selected scenario * */ private ScenarioSteppedListener _stepListener; public MultiScenarioPresenter(MultiScenarioDisplay display, MultiScenarioCore model) { super(display); // store the presenter _myDisplay = display; // generate our model _myModel = model; // listen out for scenarios being selected in the table _myDisplay.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { IStructuredSelection sel = (IStructuredSelection) event.getSelection(); EditableWrapper ed = (EditableWrapper) sel.getFirstElement(); ScenarioWrapper wrapped = (ScenarioWrapper) ed.getEditable(); selectThis(wrapped); } }); // ok, sort out the file drop handler _myDisplay.addFileDropListener(new FilesDroppedListener() { public void filesDropped(String[] files) { handleTheseFiles(files); } }); _myDisplay.addMultiScenarioHandler(new ManageMultiListener() { public void doGenerate() { generateScenarios(); } public void doRunAll() { runScenarios(); } }); _stepListener = new ScenarioSteppedListener() { @Override public void step(ScenarioType scenario, long newTime) { newTime(newTime); } @Override public void restart(ScenarioType scenario) { } }; } /** * display an updated time * * @param newTime */ protected void newTime(final long newTime) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { String timeStr = MWC.Utilities.TextFormatting.FormatRNDateTime .toShortString(newTime); _myDisplay.getUI().setTime(timeStr); } }); } protected void selectThis(final ScenarioWrapper wrap) { // is this the currently selected scenario if (_currentScen != wrap) { if (_currentScen != null) _currentScen.getScenario().removeScenarioSteppedListener(_stepListener); } // ok, remember the new one _currentScen = wrap; Display.getDefault().asyncExec(new Runnable() { @Override public void run() { ScenarioType scen = wrap.getScenario(); // ok start off with the time newTime(scen.getTime()); // now look at the state // TODO: carry on with state checking } }); } protected void controllerAssigned(String controlFile) { try { // hmm, check what type of control file it is String controlType = getFirstNodeName(controlFile); if (controlType == StandaloneObserverListHandler.type) { } else if (controlType == ScenarioControllerHandler.type) { _scenarioController = ASSETReaderWriter.importThisControlFile( controlFile, new java.io.FileInputStream(controlFile)); Vector<ScenarioObserver> theObservers = _scenarioController.observerList; // since we have a results container - we have enough information to set // the output files File tgtDir = _scenarioController.outputDirectory; // if the tgt dir is a relative reference, make it relative to // our first project, not the user's login directory if (isRelativePath(tgtDir)) { File outputDir = _myDisplay.getProjectPathFor(tgtDir); if (outputDir != null) _scenarioController.outputDirectory = outputDir; } Enumeration<ScenarioObserver> numer = theObservers.elements(); while (numer.hasMoreElements()) { ScenarioObserver thisS = numer.nextElement(); // does this worry about the output file? if (thisS instanceof RecordToFileObserverType) { // yup, better store it... RecordToFileObserverType rs = (RecordToFileObserverType) thisS; rs.setDirectory(tgtDir); } } } // get the ui to update itself _myDisplay.clearScenarios(); } catch (Exception e) { e.printStackTrace(); } } protected void generateScenarios() { // disable the genny button, until it's done. _myDisplay.getUI().setGenerateEnabled(false); JobWithProgress theJob = new JobWithProgress() { public void run(ASSETProgressMonitor montor) { // and let it create some files _myModel.prepareFiles(_controlFileName, _scenarioFileName, System.out, System.err, System.in, montor, _scenarioController.outputDirectory); // and sort out the observers _myModel.prepareControllers(_scenarioController, montor, null); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { // ok, now give the scenarios to the multi scenario table (in the UI // thread _myDisplay.setScenarios(_myModel); // and set the button states _myDisplay.getUI().setGenerateEnabled(false); _myDisplay.getUI().setRunAllEnabled(true); } }); } }; runThisJob(theJob); } /** * factor out how we actually run the job, so we can test it more easily * * @param theJob */ protected void runThisJob(JobWithProgress theJob) { _myDisplay.runThisJob(theJob); } @Override protected void handleTheseFiles(String[] fileNames) { // ok, loop through the files for (int i = 0; i < fileNames.length; i++) { final String thisName = fileNames[i]; if (thisName != null) { // ok, examine this file String firstNode = getFirstNodeName(thisName); if (firstNode != null) { // get the last component of the filename String fName = new File(thisName).getName(); if (firstNode.equals(ScenarioHandler.type)) { // remember it _scenarioFileName = thisName; // set the filename _myDisplay.setScenarioName(fName); } else if (firstNode.equals(ScenarioControllerHandler.type)) { // remember it _controlFileName = thisName; // show it _myDisplay.setControlName(fName); // now sort out the controller data controllerAssigned(_controlFileName); } } } } // right, make sure the correct buttons are enabled enableRelevantButtons(); // lastly, make our view the current selection _myDisplay.activate(); } /** * make the relevant buttons enabled * */ private void enableRelevantButtons() { if ((_controlFileName == null) || (_scenarioFileName == null)) return; try { // check if it's multi scenario.. boolean isMulti = CommandLine.checkIfGenerationRequired(_controlFileName); // get the UI ready if (isMulti) { _myDisplay.getUI().setGenerateEnabled(true); _myDisplay.getUI().setRunAllEnabled(false); } else { // we don't need to generate, just put the scenario in there. generateScenarios(); // we've only got one scenario - so select it. } } catch (FileNotFoundException e) { CorePlugin.logError(Status.ERROR, "whilst enabling model controls", e); } } @Override public void reloadDataFiles() { // let the parent do it's stuff super.reloadDataFiles(); // and clear the list of scenarios _myDisplay.clearScenarios(); } protected void runScenarios() { System.out.println("doing run"); Thread doRun = new Thread() { @Override public void run() { // tell them to go for it _myModel.nowRun(System.out, System.err, System.in, null); // ok, better refresh the workspace _myDisplay.refreshWorkspace(); } }; doRun.start(); } // testing for this class public static class TestMe extends TestCase { static public final String TEST_ALL_TEST_TYPE = "UNIT"; protected static String _controlfile; final String controlPath = "src/org/mwc/asset/scenariocontroller2/tests/trial1.xml"; final String control_multiP_Path = "src/org/mwc/asset/scenariocontroller2/tests/trial_multi_part.xml"; final String control_multiS_Path = "src/org/mwc/asset/scenariocontroller2/tests/trial_multi_scen.xml"; final String scenarioPath = "src/org/mwc/asset/scenariocontroller2/tests/trial1.asset"; public TestMe(final String val) { super(val); } @SuppressWarnings("synthetic-access") public final void testRelativePathMethod() { MultiScenarioDisplay mockDisplay = mock(MultiScenarioDisplay.class); MultiScenarioPresenter pres = new MultiScenarioPresenter(mockDisplay, null); super.assertEquals("failed to recognise drive", false, pres.isRelativePath(new File("c:\\test.rep"))); super.assertEquals("failed to root designator", false, pres.isRelativePath(new File("\\test.rep"))); super.assertEquals("failed to root designator", false, pres.isRelativePath(new File("\\\\test.rep"))); super.assertEquals("failed to root designator", false, pres.isRelativePath(new File("//test.rep"))); super.assertEquals("failed to root designator", false, pres.isRelativePath(new File("////test.rep"))); super.assertEquals("failed to recognise absolute ref", true, pres.isRelativePath(new File("test.rep"))); super.assertEquals("failed to recognise relative ref", true, pres.isRelativePath(new File("./test.rep"))); super.assertEquals("failed to recognise parent ref", true, pres.isRelativePath(new File("../test.rep"))); } @Test public final void testHandleScenarioFile() { MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = mock(MultiScenarioCore.class); MultiScenarioPresenter pres = new TestPresenter(display, model); UIDisplay ui = mock(UIDisplay.class); when(display.getUI()).thenReturn(ui); // ok, try for the scenario first String[] files = { scenarioPath }; assertTrue("scenario file exists", new File(scenarioPath).exists()); pres.handleTheseFiles(files); // ok, check the display got set verify(display).setScenarioName("trial1.asset"); verify(display).activate(); // aah, and check the control wasn't set verify(display, never()).setControlName(anyString()); } public void testTrackingSelection() { // TODO: test that we remove ourselves from unselected scenarios } public void testRealDataSinglePart() { // check we can see the files assertTrue("can't find scenario", new File(scenarioPath).exists()); assertTrue("can't find control", new File(controlPath).exists()); MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = new MultiScenarioCore(); MultiScenarioPresenter pres = new MultiScenarioPresenter(display, model) { @Override protected void runThisJob(JobWithProgress theJob) { ASSETProgressMonitor monitor = new ASSETProgressMonitor() { public void beginTask(String name, int totalWork) { } public void worked(int work) { } }; theJob.run(monitor); } }; // just add support for a couple of methods that we need to work when(display.getProjectPathFor(new File("results"))).thenReturn( new File("results")); UIDisplay ui = mock(UIDisplay.class); when(display.getUI()).thenReturn(ui); pres.handleTheseFiles(new String[] { scenarioPath, controlPath }); // check scenarios cleared verify(display).clearScenarios(); // check the list of scenarios got set verify(display).setScenarios((MultiScenarioCore) anyObject()); // check the UI is correctly enabled verify(ui).setInitEnabled(true); verify(ui).setStepEnabled(false); verify(ui).setPlayEnabled(false); } public void testRealDataMultiPart() { // check we can see the files assertTrue("can't find scenario", new File(scenarioPath).exists()); assertTrue("can't find control", new File(control_multiP_Path).exists()); MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = new MultiScenarioCore(); UIDisplay ui = mock(UIDisplay.class); MultiScenarioPresenter pres = new MultiScenarioPresenter(display, model); // just add support for a couple of methods that we need to work when(display.getProjectPathFor(new File("results"))).thenReturn( new File("results")); when(display.getUI()).thenReturn(ui); pres.handleTheseFiles(new String[] { scenarioPath, control_multiP_Path }); // ok, check they loaded verify(display).setScenarioName(anyString()); verify(display).setControlName(anyString()); // and that the UI looks right verify(ui).setGenerateEnabled(true); verify(ui).setRunAllEnabled(false); // and check the controller bits are done assertNotNull("controller loaded", pres._scenarioController); verify(display).activate(); // ok, go for the generate pres.generateScenarios(); } @Test public final void testHandleControlFile() { MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = mock(MultiScenarioCore.class); MultiScenarioPresenter pres = new TestPresenter(display, model); // ok, try for the scenario first String[] files = { controlPath }; pres.handleTheseFiles(files); // ok, check the display got set verify(display).setControlName("trial1.xml"); verify(display).activate(); // and the scenario wasn't set verify(display, never()).setScenarioName(anyString()); } @Test public final void testHandleBothFiles() { MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = mock(MultiScenarioCore.class); MultiScenarioPresenter pres = new TestPresenter(display, model); UIDisplay ui = mock(UIDisplay.class); when(display.getUI()).thenReturn(ui); // ok, try for the scenario first String[] files = { controlPath, scenarioPath }; pres.handleTheseFiles(files); // ok, check the display got set verify(display).setControlName("trial1.xml"); verify(display).setScenarioName("trial1.asset"); verify(display).activate(); } protected static class TestPresenter extends MultiScenarioPresenter { public TestPresenter(MultiScenarioDisplay display, MultiScenarioCore model) { super(display, model); } @Override protected void controllerAssigned(String controlFile) { _controlfile = controlFile; } } public void testReloadDatafiles() { MultiScenarioDisplay display = mock(MultiScenarioDisplay.class); MultiScenarioCore model = mock(MultiScenarioCore.class); MultiScenarioPresenter pres = new TestPresenter(display, model); UIDisplay ui = mock(UIDisplay.class); when(display.getUI()).thenReturn(ui); pres._controlFileName = controlPath; pres._scenarioFileName = scenarioPath; // ok, try for the scenario first pres.reloadDataFiles(); // ok, check the display got set verify(display).setControlName("trial1.xml"); verify(display).setScenarioName("trial1.asset"); verify(display, times(2)).activate(); verify(display).clearScenarios(); } } public Vector<ScenarioObserver> getObservers() { return _myModel.getObservers(); } }
package com.xpn.xwiki.objects.classes; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import org.apache.commons.lang3.StringUtils; import org.apache.ecs.xhtml.input; import org.apache.velocity.VelocityContext; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import org.hibernate.mapping.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xwiki.model.reference.ClassPropertyReference; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.EntityReference; import org.xwiki.template.Template; import org.xwiki.template.TemplateManager; import org.xwiki.velocity.VelocityManager; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.XWikiException; import com.xpn.xwiki.api.Context; import com.xpn.xwiki.api.DeprecatedContext; import com.xpn.xwiki.doc.XWikiDocument; import com.xpn.xwiki.doc.merge.MergeConfiguration; import com.xpn.xwiki.doc.merge.MergeResult; import com.xpn.xwiki.internal.template.SUExecutor; import com.xpn.xwiki.internal.xml.XMLAttributeValueFilter; import com.xpn.xwiki.objects.BaseCollection; import com.xpn.xwiki.objects.BaseObject; import com.xpn.xwiki.objects.BaseProperty; import com.xpn.xwiki.objects.meta.MetaClass; import com.xpn.xwiki.objects.meta.PropertyMetaClass; import com.xpn.xwiki.validation.XWikiValidationStatus; import com.xpn.xwiki.web.Utils; /** * Represents an XClass property and contains property definitions (eg "relational storage", "display type", * "separator", "multi select", etc). Each property definition is of type {@link BaseProperty}. * * @version $Id$ */ public class PropertyClass extends BaseCollection<ClassPropertyReference> implements PropertyClassInterface, Comparable<PropertyClass> { /** * Logging helper object. */ private static final Logger LOGGER = LoggerFactory.getLogger(PropertyClass.class); /** * Identifier used to specify that the property has a custom displayer in the XClass itself. */ private static final String CLASS_DISPLAYER_IDENTIFIER = "class"; /** * Identifier prefix used to specify that the property has a custom displayer in a wiki document. */ private static final String DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX = "doc:"; /** * Identifier prefix used to specify that the property has a custom displayer in a velocity template. */ private static final String TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX = "template:"; private BaseClass xclass; private long id; private PropertyMetaClass pMetaClass; protected String cachedCustomDisplayer; public PropertyClass() { } public PropertyClass(String name, String prettyname, PropertyMetaClass xWikiClass) { setName(name); setPrettyName(prettyname); setxWikiClass(xWikiClass); setUnmodifiable(false); setDisabled(false); } @Override protected ClassPropertyReference createReference() { return new ClassPropertyReference(getName(), this.xclass.getReference()); } @Override public BaseClass getXClass(XWikiContext context) { return getxWikiClass(); } public BaseClass getxWikiClass() { if (this.pMetaClass == null) { MetaClass metaClass = MetaClass.getMetaClass(); this.pMetaClass = (PropertyMetaClass) metaClass.get(getClassType()); } return this.pMetaClass; } public void setxWikiClass(BaseClass xWikiClass) { this.pMetaClass = (PropertyMetaClass) xWikiClass; } @Override public BaseCollection getObject() { return this.xclass; } @Override public void setObject(BaseCollection object) { this.xclass = (BaseClass) object; } public String getFieldFullName() { if (getObject() == null) { return getName(); } return getObject().getName() + "_" + getName(); } @Override public long getId() { if (getObject() == null) { return this.id; } return getObject().getId(); } @Override public void setId(long id) { this.id = id; } @Override public String toString(BaseProperty property) { return property.toText(); } @Override public BaseProperty fromString(String value) { return null; } public BaseProperty newPropertyfromXML(Element ppcel) { String value = ppcel.getText(); return fromString(value); } @Override public void displayHidden(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { input input = new input(); input.setAttributeFilter(new XMLAttributeValueFilter()); BaseProperty prop = (BaseProperty) object.safeget(name); if (prop != null) { input.setValue(prop.toText()); } input.setType("hidden"); input.setName(prefix + name); input.setID(prefix + name); buffer.append(input.toString()); } @Override public void displayView(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { BaseProperty prop = (BaseProperty) object.safeget(name); if (prop != null) { buffer.append(prop.toText()); } } @Override public void displayEdit(StringBuffer buffer, String name, String prefix, BaseCollection object, XWikiContext context) { input input = new input(); input.setAttributeFilter(new XMLAttributeValueFilter()); BaseProperty prop = (BaseProperty) object.safeget(name); if (prop != null) { input.setValue(prop.toText()); } input.setType("text"); input.setName(prefix + name); input.setID(prefix + name); input.setDisabled(isDisabled()); buffer.append(input.toString()); } public String displayHidden(String name, String prefix, BaseCollection object, XWikiContext context) { StringBuffer buffer = new StringBuffer(); displayHidden(buffer, name, prefix, object, context); return buffer.toString(); } public String displayHidden(String name, BaseCollection object, XWikiContext context) { return displayHidden(name, "", object, context); } public String displayView(String name, String prefix, BaseCollection object, XWikiContext context) { StringBuffer buffer = new StringBuffer(); displayView(buffer, name, prefix, object, context); return buffer.toString(); } public String displayView(String name, BaseCollection object, XWikiContext context) { return displayView(name, "", object, context); } public String displayEdit(String name, String prefix, BaseCollection object, XWikiContext context) { StringBuffer buffer = new StringBuffer(); displayEdit(buffer, name, prefix, object, context); return buffer.toString(); } public String displayEdit(String name, BaseCollection object, XWikiContext context) { return displayEdit(name, "", object, context); } public boolean isCustomDisplayed(XWikiContext context) { return (StringUtils.isNotEmpty(getCachedDefaultCustomDisplayer(context))); } public void displayCustom(StringBuffer buffer, String fieldName, String prefix, String type, BaseObject object, final XWikiContext context) throws XWikiException { String content = ""; try { VelocityContext vcontext = Utils.getComponent(VelocityManager.class).getVelocityContext(); vcontext.put("name", fieldName); vcontext.put("prefix", prefix); // The PropertyClass instance can be used to access meta properties in the custom displayer (e.g. // dateFormat, multiSelect). It can be obtained from the XClass of the given object but only if the property // has been added to the XClass. We need to have it in the Velocity context for the use case when an XClass // property needs to be previewed before being added to the XClass. vcontext.put("field", new com.xpn.xwiki.api.PropertyClass(this, context)); vcontext.put("object", new com.xpn.xwiki.api.Object(object, context)); vcontext.put("type", type); vcontext.put("context", new DeprecatedContext(context)); vcontext.put("xcontext", new Context(context)); BaseProperty prop = (BaseProperty) object.safeget(fieldName); if (prop != null) { vcontext.put("value", prop.getValue()); } else { // The $value property can exist in the velocity context, we overwrite it to make sure we don't get a // wrong value in the displayer when the property does not exist yet. vcontext.put("value", null); } String customDisplayer = getCachedDefaultCustomDisplayer(context); if (StringUtils.isNotEmpty(customDisplayer)) { if (customDisplayer.equals(CLASS_DISPLAYER_IDENTIFIER)) { final String rawContent = getCustomDisplay(); XWikiDocument classDocument = context.getWiki().getDocument(getObject().getDocumentReference(), context); final String classSyntax = classDocument.getSyntax().toIdString(); // Using author reference since the document content is not relevant in this case. DocumentReference authorReference = classDocument.getAuthorReference(); // Make sure we render the custom displayer with the rights of the user who wrote it (i.e. class // document author). content = renderContentInContext(rawContent, classSyntax, authorReference, context); } else if (customDisplayer.startsWith(DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX)) { XWikiDocument displayerDoc = context.getWiki().getDocument( StringUtils.substringAfter(customDisplayer, DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX), context); final String rawContent = displayerDoc.getContent(); final String displayerDocSyntax = displayerDoc.getSyntax().toIdString(); DocumentReference authorReference = displayerDoc.getContentAuthorReference(); // Make sure we render the custom displayer with the rights of the user who wrote it (i.e. displayer // document content author). content = renderContentInContext(rawContent, displayerDocSyntax, authorReference, context); } else if (customDisplayer.startsWith(TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX)) { content = context.getWiki().evaluateTemplate( StringUtils.substringAfter(customDisplayer, TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX), context); } } } catch (Exception e) { throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES, XWikiException.ERROR_XWIKI_CLASSES_CANNOT_PREPARE_CUSTOM_DISPLAY, "Exception while preparing the custom display of " + fieldName, e, null); } buffer.append(content); } /** * Render content in the current document's context with the rights of the given user. */ private String renderContentInContext(final String content, final String syntax, DocumentReference authorReference, final XWikiContext context) throws Exception { String result = Utils.getComponent(SUExecutor.class).call(new Callable<String>() { @Override public String call() throws Exception { return context.getDoc().getRenderedContent(content, syntax, context); } }, authorReference); return result; } @Override public String getClassName() { BaseClass bclass = getxWikiClass(); return (bclass == null) ? "" : bclass.getName(); } // In property classes we need to store this info in the HashMap for fields // This way it is readable by the displayEdit/displayView functions.. @Override public String getName() { return getStringValue("name"); } @Override public void setName(String name) { setStringValue("name", name); } public String getCustomDisplay() { return getStringValue("customDisplay"); } public void setCustomDisplay(String value) { setLargeStringValue("customDisplay", value); } @Override public String getPrettyName() { return getStringValue("prettyName"); } public String getPrettyName(XWikiContext context) { return getTranslatedPrettyName(context); } public String getTranslatedPrettyName(XWikiContext context) { String msgName = getFieldFullName(); if ((context == null) || (context.getWiki() == null)) { return getPrettyName(); } String prettyName = localizePlain(msgName); if (prettyName == null) { return getPrettyName(); } return prettyName; } @Override public void setPrettyName(String prettyName) { setStringValue("prettyName", prettyName); } public String getTooltip() { return getLargeStringValue("tooltip"); } /** * Gets international tooltip * * @param context * @return */ public String getTooltip(XWikiContext context) { String tooltipName = getFieldFullName() + "_tooltip"; String tooltip = localizePlain(tooltipName); if (tooltip == null) { tooltipName = getLargeStringValue("tooltip"); if ((tooltipName != null) && (!tooltipName.trim().equals(""))) { tooltip = localizePlainOrKey(tooltipName, tooltipName); } } return tooltip; } public void setTooltip(String tooltip) { setLargeStringValue("tooltip", tooltip); } @Override public int getNumber() { return getIntValue("number"); } @Override public void setNumber(int number) { setIntValue("number", number); } /** * Each type of XClass property is identified by a string that specifies the data type of the property value (e.g. * 'String', 'Number', 'Date') without disclosing implementation details. The internal implementation of an XClass * property type can change over time but its {@code classType} should not. * <p> * The {@code classType} can be used as a hint to lookup various components related to this specific XClass property * type. See {@link com.xpn.xwiki.internal.objects.classes.PropertyClassProvider} for instance. * * @return an identifier for the data type of the property value (e.g. 'String', 'Number', 'Date') */ public String getClassType() { // By default the hint is computed by removing the Class suffix, if present, from the Java simple class name // (without the package). Subclasses can overwrite this method to use a different hint format. return StringUtils.removeEnd(getClass().getSimpleName(), "Class"); } /** * Sets the property class type. * * @param type the class type * @deprecated since 4.3M1, the property class type cannot be modified */ @Deprecated public void setClassType(String type) { LOGGER.warn("The property class type cannot be modified!"); } @Override public PropertyClass clone() { PropertyClass pclass = (PropertyClass) super.clone(); pclass.setObject(getObject()); return pclass; } @Override public Element toXML(BaseClass bclass) { return toXML(); } @Override public Element toXML() { Element pel = new DOMElement(getName()); // Iterate over values sorted by field name so that the values are // exported to XML in a consistent order. Iterator it = getSortedIterator(); while (it.hasNext()) { BaseProperty bprop = (BaseProperty) it.next(); pel.add(bprop.toXML()); } Element el = new DOMElement("classType"); String classType = getClassType(); if (this.getClass().getSimpleName().equals(classType + "Class")) { // Keep exporting the full Java class name for old/default property types to avoid breaking the XAR format // (to allow XClasses created with the current version of XWiki to be imported in an older version). classType = this.getClass().getName(); } el.addText(classType); pel.add(el); return pel; } public void fromXML(Element pcel) throws XWikiException { List list = pcel.elements(); BaseClass bclass = getxWikiClass(); for (int i = 0; i < list.size(); i++) { Element ppcel = (Element) list.get(i); String name = ppcel.getName(); if (bclass == null) { Object[] args = { getClass().getName() }; throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES, XWikiException.ERROR_XWIKI_CLASSES_PROPERTY_CLASS_IN_METACLASS, "Cannot find property class {0} in MetaClass object", null, args); } PropertyClass pclass = (PropertyClass) bclass.safeget(name); if (pclass != null) { BaseProperty bprop = pclass.newPropertyfromXML(ppcel); bprop.setObject(this); safeput(name, bprop); } } } @Override public String toFormString() { return toString(); } public void initLazyCollections() { } public boolean isUnmodifiable() { return (getIntValue("unmodifiable") == 1); } public void setUnmodifiable(boolean unmodifiable) { if (unmodifiable) { setIntValue("unmodifiable", 1); } else { setIntValue("unmodifiable", 0); } } /** * See if this property is disabled or not. A disabled property should not be editable, but existing object values * are still kept in the database. * * @return {@code true} if this property is disabled and should not be used, {@code false} otherwise * @see #setDisabled(boolean) * @since 2.4M2 */ public boolean isDisabled() { return (getIntValue("disabled", 0) == 1); } /** * Disable or re-enable this property. A disabled property should not be editable, but existing object values are * still kept in the database. * * @param disabled whether the property is disabled or not * @see #isDisabled() * @since 2.4M2 */ public void setDisabled(boolean disabled) { if (disabled) { setIntValue("disabled", 1); } else { setIntValue("disabled", 0); } } public BaseProperty fromStringArray(String[] strings) { return fromString(strings[0]); } public boolean isValidColumnTypes(Property hibprop) { return true; } @Override public BaseProperty fromValue(Object value) { BaseProperty property = newProperty(); property.setValue(value); return property; } @Override public BaseProperty newProperty() { return new BaseProperty(); } public void setValidationRegExp(String validationRegExp) { setStringValue("validationRegExp", validationRegExp); } public String getValidationRegExp() { return getStringValue("validationRegExp"); } public String getValidationMessage() { return getStringValue("validationMessage"); } public void setValidationMessage(String validationMessage) { setStringValue("validationMessage", validationMessage); } public boolean validateProperty(BaseProperty property, XWikiContext context) { String regexp = getValidationRegExp(); if ((regexp == null) || (regexp.trim().equals(""))) { return true; } String value = ((property == null) || (property.getValue() == null)) ? "" : property.getValue().toString(); try { if (context.getUtil().match(regexp, value)) { return true; } XWikiValidationStatus.addErrorToContext((getObject() == null) ? "" : getObject().getName(), getName(), getTranslatedPrettyName(context), getValidationMessage(), context); return false; } catch (Exception e) { XWikiValidationStatus.addExceptionToContext((getObject() == null) ? "" : getObject().getName(), getName(), e, context); return false; } } @Override public void flushCache() { this.cachedCustomDisplayer = null; } /** * Compares two property definitions based on their index number. * * @param other the other property definition to be compared with * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than * the specified object. * @see #getNumber() * @since 2.4M2 */ @Override public int compareTo(PropertyClass other) { int result = this.getNumber() - other.getNumber(); // This should never happen, but just to remove the randomness in case it does happen, also compare their names. if (result == 0) { result = this.getName().compareTo(other.getName()); } return result; } protected String getFullQueryPropertyName() { return "obj." + getName(); } /** * Returns the current cached default custom displayer for the PropertyClass. The result will be cached and can be * flushed using {@link #flushCache()}. If it returns the empty string, then there is no default custom displayer * for this class. * * @param context the current request context * @return An identifier for the location of a custom displayer. This can be {@code class} if there's custom display * code specified in the class itself, {@code page:currentwiki:XWiki.BooleanDisplayer} if such a document * exists in the current wiki, {@code page:xwiki:XWiki.StringDisplayer} if such a document exists in the * main wiki, or {@code template:displayer_boolean.vm} if a template on the filesystem or in the current * skin exists. */ protected String getCachedDefaultCustomDisplayer(XWikiContext context) { // First look at custom displayer in class. We should not cache this one. String customDisplay = getCustomDisplay(); if (StringUtils.isNotEmpty(customDisplay)) { return CLASS_DISPLAYER_IDENTIFIER; } // Then look for pages or templates if (this.cachedCustomDisplayer == null) { this.cachedCustomDisplayer = getDefaultCustomDisplayer(getTypeName(), context); } return this.cachedCustomDisplayer; } /** * Method to find the default custom displayer to use for a specific Property Class. * * @param propertyClassName the type of the property; this is defined in each subclass, such as {@code boolean}, * {@code string} or {@code dblist} * @param context the current request context * @return An identifier for the location of a custom displayer. This can be {@code class} if there's custom display * code specified in the class itself, {@code page:currentwiki:XWiki.BooleanDisplayer} if such a document * exists in the current wiki, {@code page:xwiki:XWiki.StringDisplayer} if such a document exists in the * main wiki, or {@code template:displayer_boolean.vm} if a template on the filesystem or in the current * skin exists. */ protected String getDefaultCustomDisplayer(String propertyClassName, XWikiContext context) { LOGGER.debug("Looking up default custom displayer for property class name [{}]", propertyClassName); try { // First look into the current wiki String pageName = StringUtils.capitalize(propertyClassName) + "Displayer"; DocumentReference reference = new DocumentReference(context.getWikiId(), "XWiki", pageName); if (context.getWiki().exists(reference, context)) { LOGGER.debug("Found default custom displayer for property class name in local wiki: [{}]", pageName); return DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX + "XWiki." + pageName; } // Look in the main wiki if (!context.isMainWiki()) { reference = new DocumentReference(context.getMainXWiki(), "XWiki", pageName); if (context.getWiki().exists(reference, context)) { LOGGER.debug("Found default custom displayer for property class name in main wiki: [{}]", pageName); return DOCUMENT_DISPLAYER_IDENTIFIER_PREFIX + context.getMainXWiki() + ":XWiki." + pageName; } } // Look in templates String templateName = "displayer_" + propertyClassName + ".vm"; TemplateManager templateManager = Utils.getComponent(TemplateManager.class); Template existingTemplate = templateManager.getTemplate(templateName); if (existingTemplate != null) { LOGGER.debug("Found default custom displayer for property class name as template: [{}]", templateName); return TEMPLATE_DISPLAYER_IDENTIFIER_PREFIX + templateName; } } catch (Throwable e) { // If we fail we consider there is no custom displayer LOGGER.error("Error while trying to evaluate if a property has a custom displayer", e); } return null; } /** * Get a short name identifying this type of property. This is derived from the java class name, lowercasing the * part before {@code Class}. * * @return a string, for example {@code string}, {@code dblist}, {@code number} */ private String getTypeName() { return StringUtils.substringBeforeLast(this.getClass().getSimpleName(), "Class").toLowerCase(); } /** * Apply a 3 ways merge on passed current, previous and new version of the same property. The passed current version * is modified as result of the merge. * * @param currentProperty the current version of the element and the one to modify * @param previousProperty the previous version of the element * @param newProperty the new version of the property * @param configuration the configuration of the merge Indicate how to deal with some conflicts use cases, etc. * @param context the XWiki context * @param mergeResult the merge report * @return the merged version * @since 6.2M1 */ public <T extends EntityReference> void mergeProperty(BaseProperty<T> currentProperty, BaseProperty<T> previousProperty, BaseProperty<T> newProperty, MergeConfiguration configuration, XWikiContext context, MergeResult mergeResult) { currentProperty.merge(previousProperty, newProperty, configuration, context, mergeResult); } }
package org.jgroups.jmx; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.DynamicMBean; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.ReflectionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.annotations.MBean; import org.jgroups.annotations.ManagedAttribute; import org.jgroups.annotations.ManagedOperation; /** * * A DynamicMBean wrapping an annotated object instance. * * @author Chris Mills * @author Vladimir Blagojevic * @version $Id: ResourceDMBean.java,v 1.13 2008/03/07 09:53:27 vlada Exp $ * @see ManagedAttribute * @see ManagedOperation * @see MBean * */ public class ResourceDMBean implements DynamicMBean { private static final Class<?>[] primitives= { int.class, byte.class, short.class, long.class, float.class, double.class, boolean.class, char.class }; private static final String MBEAN_DESCRITION="Dynamic MBean Description"; private final Log log=LogFactory.getLog(ResourceDMBean.class); private final Object obj; private String description=""; private final MBeanAttributeInfo[] attrInfo; private final MBeanOperationInfo[] opInfo; private final HashMap<String,AttributeEntry> atts=new HashMap<String,AttributeEntry>(); private final List<MBeanOperationInfo> ops=new ArrayList<MBeanOperationInfo>(); public ResourceDMBean(Object instance) { if(instance == null) throw new NullPointerException("Cannot make an MBean wrapper for null instance"); this.obj=instance; findDescription(); findFields(); findMethods(); attrInfo=new MBeanAttributeInfo[atts.size()]; int i=0; log.info("Processing class " + instance.getClass()); log.info("Attributes are:"); MBeanAttributeInfo info=null; for(AttributeEntry entry:atts.values()) { info=entry.getInfo(); attrInfo[i++]=info; log.info("Attribute " + info.getName() + "[r=" + info.isReadable() + ",w=" + info.isWritable() + ",is=" + info.isIs() + "]"); } opInfo=new MBeanOperationInfo[ops.size()]; ops.toArray(opInfo); if(ops.size() > 0) log.info("Operations are:"); for(MBeanOperationInfo op:opInfo) { log.info("Operation " + op.getReturnType() + " " + op.getName()); } } Object getObject() { return obj; } private void findDescription() { MBean mbean=obj.getClass().getAnnotation(MBean.class); if(mbean.description() != null && mbean.description().trim().length() > 0) { description=mbean.description(); if(log.isDebugEnabled()) { log.debug("@MBean description set - " + mbean.description()); } MBeanAttributeInfo info=new MBeanAttributeInfo(ResourceDMBean.MBEAN_DESCRITION, "java.lang.String", "@MBean description", true, false, false); try { atts.put(ResourceDMBean.MBEAN_DESCRITION, new FieldAttributeEntry(info, this.getClass() .getDeclaredField("description"))); } catch(NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public synchronized MBeanInfo getMBeanInfo() { return new MBeanInfo(obj.getClass().getCanonicalName(), description, attrInfo, null, opInfo, null); } public synchronized Object getAttribute(String name) { if(log.isDebugEnabled()) { log.debug("getAttribute called for " + name); } Attribute attr=getNamedAttribute(name); if(log.isDebugEnabled()) { log.debug("getAttribute value found " + attr.getValue()); } return attr.getValue(); } public synchronized void setAttribute(Attribute attribute) { if(log.isDebugEnabled()) { log.debug("setAttribute called for " + attribute.getName() + " value " + attribute.getValue()); } setNamedAttribute(attribute); } public synchronized AttributeList getAttributes(String[] names) { if(log.isDebugEnabled()) { log.debug("getAttributes called"); } AttributeList al=new AttributeList(); for(String name:names) { Attribute attr=getNamedAttribute(name); if(attr != null) { al.add(attr); } else { log.warn("Did not find attribute " + name); } } return al; } public synchronized AttributeList setAttributes(AttributeList list) { if(log.isDebugEnabled()) { log.debug("setAttributes called"); } AttributeList results=new AttributeList(); for(int i=0;i < list.size();i++) { Attribute attr=(Attribute)list.get(i); if(log.isDebugEnabled()) { log.debug("Attribute name " + attr.getName() + " new value is " + attr.getValue()); } if(setNamedAttribute(attr)) { results.add(attr); } else { if(log.isWarnEnabled()) { log.debug("Failed to update attribute name " + attr.getName() + " with value " + attr.getValue()); } } } return results; } public Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException { try { if(log.isDebugEnabled()) { log.debug("Invoke method called on " + name); } Class<?>[] classes=new Class[sig.length]; for(int i=0;i < classes.length;i++) { classes[i]=getClassForName(sig[i]); } Method method=this.obj.getClass().getMethod(name, classes); return method.invoke(this.obj, args); } catch(Exception e) { throw new MBeanException(e); } } public static Class<?> getClassForName(String name) throws ClassNotFoundException { try { Class<?> c=Class.forName(name); return c; } catch(ClassNotFoundException cnfe) { //Could be a primative - let's check for(int i=0;i < primitives.length;i++) { if(name.equals(primitives[i].getName())) { return primitives[i]; } } } throw new ClassNotFoundException("Class " + name + " cannot be found"); } private void findMethods() { //find all methods Method[] methods=obj.getClass().getMethods(); for(Method method:methods) { ManagedAttribute attr=method.getAnnotation(ManagedAttribute.class); if(attr != null) { String methodName=method.getName(); if(!methodName.startsWith("get") && !methodName.startsWith("set") && !methodName.startsWith("is")) { if(log.isWarnEnabled()) log.warn("method name " + methodName + " doesn't start with \"get\", \"set\", or \"is\"" + ", but is annotated with @ManagedAttribute: will be ignored"); } else { MBeanAttributeInfo info=null; String attributeName=null; boolean writeAttribute=false; if(methodName.startsWith("set") && method.getReturnType() == java.lang.Void.TYPE) { // setter Class<?> params [] = method.getParameterTypes(); if(params.length == 1){ attributeName=methodName.substring(3); info=new MBeanAttributeInfo(attributeName, params[0].getCanonicalName(), attr.description(), true, true, false); writeAttribute=true; } } else { // getter if(method.getParameterTypes().length == 0 && method.getReturnType() != java.lang.Void.TYPE) { boolean hasSetter=atts.containsKey(attributeName); if(methodName.startsWith("is")) { attributeName=methodName.substring(2); info=new MBeanAttributeInfo(attributeName, method.getReturnType().getCanonicalName(), attr.description(), attr.readable(), true, true); } else { //this has to be get attributeName=methodName.substring(3); info=new MBeanAttributeInfo(attributeName, method.getReturnType().getCanonicalName(), attr.description(), attr.readable(), hasSetter, false); } } else { if(log.isWarnEnabled()) { log.warn("Method " + method.getName() + " must have a valid return type and zero parameters"); } continue; } } if(log.isDebugEnabled()) { log.debug("@Attr found for method " + method.getName()); } AttributeEntry ae=atts.get(attributeName); if(!writeAttribute) { //we already have annotated field as read if(ae instanceof FieldAttributeEntry && ae.getInfo().isReadable()) { log.warn("Not adding annotated method " + methodName + " since we already have read attribute"); } //we already have annotated set method else if(ae instanceof MethodAttributeEntry) { MethodAttributeEntry mae=(MethodAttributeEntry)ae; if(mae.hasSetMethod()) { atts.put(attributeName, new MethodAttributeEntry(info, mae.getSetMethod(), method)); } } //we don't have such entry else { atts.put(attributeName, new MethodAttributeEntry(info, null, method)); } } else { //we already have annotated field as write if(ae instanceof FieldAttributeEntry && ae.getInfo().isWritable()) { log.warn("Not adding annotated method " + methodName + " since we already have read attribute"); } //we already have annotated getOrIs method else if(ae instanceof MethodAttributeEntry) { MethodAttributeEntry mae=(MethodAttributeEntry)ae; if(mae.hasIsOrGetMethod()) { atts.put(attributeName, new MethodAttributeEntry(info, method, mae.getIsOrGetMethod())); } } //we don't have such entry else { atts.put(attributeName, new MethodAttributeEntry(info, method, null)); } } } } ManagedOperation op=method.getAnnotation(ManagedOperation.class); if(op != null) { ops.add(new MBeanOperationInfo(op.description(), method)); if(log.isDebugEnabled()) { log.debug("@Operation found for method " + method.getName()); } } } } private void findFields() { //walk annotated class hierarchy and find all fields for(Class<?> clazz=obj.getClass();clazz != null && clazz.isAnnotationPresent(MBean.class);clazz=clazz.getSuperclass()) { Field[] fields=clazz.getDeclaredFields(); for(Field field:fields) { ManagedAttribute attr=field.getAnnotation(ManagedAttribute.class); if(attr != null) { MBeanAttributeInfo info=new MBeanAttributeInfo(field.getName(), field.getType().getCanonicalName(), attr.description(), attr.readable(), Modifier.isFinal(field.getModifiers())? false: attr.writable(), false); atts.put(field.getName(), new FieldAttributeEntry(info, field)); if(log.isDebugEnabled()) { log.debug("@Attr found for field " + field.getName()); } } } } } private Attribute getNamedAttribute(String name) { Attribute result=null; try { if(name.equals(ResourceDMBean.MBEAN_DESCRITION)) { result=new Attribute(ResourceDMBean.MBEAN_DESCRITION, this.description); } else { AttributeEntry entry=atts.get(name); if(entry != null) { MBeanAttributeInfo i=entry.getInfo(); result=new Attribute(name, entry.invoke(null)); log.debug("Attribute " + name + " has r=" + i.isReadable() + ",w=" + i.isWritable() + ",is=" + i.isIs() + " and value " + result.getValue()); } else { log.warn("Did not find attribute " + name); } } } catch(Exception e) { e.printStackTrace(); } return result; } private boolean setNamedAttribute(Attribute attribute) { boolean result=false; try { AttributeEntry entry=atts.get(attribute.getName()); if(entry != null) { log.debug("Invoking set on attribute " + attribute.getName()); entry.invoke(attribute); result=true; } } catch(Exception e) { e.printStackTrace(); } return result; } private class MethodAttributeEntry implements AttributeEntry { final MBeanAttributeInfo info; final Method isOrGetmethod; final Method setMethod; public MethodAttributeEntry(final MBeanAttributeInfo info, final Method setMethod, final Method isOrGetMethod) { super(); this.info=info; this.setMethod=setMethod; this.isOrGetmethod=isOrGetMethod; } public Object invoke(Attribute a) throws Exception { if(a == null && isOrGetmethod != null) return isOrGetmethod.invoke(getObject(), new Object[] {}); else if(a != null && setMethod != null) return setMethod.invoke(getObject(), new Object[] { a.getValue() }); else return null; } public MBeanAttributeInfo getInfo() { return info; } public boolean hasIsOrGetMethod() { return isOrGetmethod != null; } public boolean hasSetMethod() { return setMethod != null; } public Method getIsOrGetMethod() { return isOrGetmethod; } public Method getSetMethod() { return setMethod; } } private class FieldAttributeEntry implements AttributeEntry { private final MBeanAttributeInfo info; private final Field field; public FieldAttributeEntry(final MBeanAttributeInfo info,final Field field) { super(); this.info=info; this.field=field; if(!field.isAccessible()) { field.setAccessible(true); } } public Object invoke(Attribute a) throws Exception { if(a == null) { return field.get(getObject()); } else { field.set(getObject(), a.getValue()); return null; } } public MBeanAttributeInfo getInfo() { return info; } } private interface AttributeEntry { public Object invoke(Attribute a) throws Exception; public MBeanAttributeInfo getInfo(); } }
package org.opendaylight.yangtools.yang.parser.spi.meta; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; import org.opendaylight.yangtools.yang.model.api.stmt.KeyStatement; import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier; import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.UnknownStatementImpl; public final class StmtContextUtils { public static final char LIST_KEY_SEPARATOR = ' '; private static final Splitter KEY_SPLITTER = Splitter.on(LIST_KEY_SEPARATOR).omitEmptyStrings().trimResults(); private static final Function<StmtContext<?, ?,?>, DeclaredStatement<?>> BUILD_DECLARED = new Function<StmtContext<?,?,?>, DeclaredStatement<?>>() { @Override public DeclaredStatement<?> apply(final StmtContext<?, ?, ?> input) { return input.buildDeclared(); } }; private static final Function<StmtContext<?, ?,?>, EffectiveStatement<?,?>> BUILD_EFFECTIVE = new Function<StmtContext<?,?,?>, EffectiveStatement<?,?>>() { @Override public EffectiveStatement<?, ?> apply(final StmtContext<?, ?, ?> input) { return input.buildEffective(); } }; public static final Predicate<StmtContext<?, ?,?>> IS_SUPPORTED_TO_BUILD_EFFECTIVE = new Predicate<StmtContext<?,?,?>>() { @Override public boolean apply(final StmtContext<?, ?, ?> input) { return input.isSupportedToBuildEffective(); } }; private StmtContextUtils() { throw new UnsupportedOperationException("Utility class"); } @SuppressWarnings("unchecked") public static <D extends DeclaredStatement<?>> Function<StmtContext<?, ? extends D, ?>, D> buildDeclared() { return Function.class.cast(BUILD_DECLARED); } @SuppressWarnings("unchecked") public static <E extends EffectiveStatement<?, ?>> Function<StmtContext<?, ?, ? extends E>, E> buildEffective() { return Function.class.cast(BUILD_EFFECTIVE); } @SuppressWarnings("unchecked") public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf( final Iterable<? extends StmtContext<?, ?, ?>> contexts, final Class<DT> declaredType) { for (StmtContext<?, ?, ?> ctx : contexts) { if (producesDeclared(ctx, declaredType)) { return (AT) ctx.getStatementArgument(); } } return null; } @SuppressWarnings("unchecked") public static <AT, DT extends DeclaredStatement<AT>> AT firstAttributeOf(final StmtContext<?, ?, ?> ctx, final Class<DT> declaredType) { return producesDeclared(ctx, declaredType) ? (AT) ctx.getStatementArgument() : null; } @SuppressWarnings("unchecked") public static <AT,DT extends DeclaredStatement<AT>> StmtContext<AT, ?, ?> findFirstDeclaredSubstatement( final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) { for (StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) { if (producesDeclared(subStmtContext,declaredType)) { return (StmtContext<AT, ?, ?>) subStmtContext; } } return null; } @SafeVarargs public static StmtContext<?, ?, ?> findFirstDeclaredSubstatement(final StmtContext<?, ?, ?> stmtContext, int startIndex, final Class<? extends DeclaredStatement<?>>... types) { if (startIndex >= types.length) { return null; } for (StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) { if (producesDeclared(subStmtContext,types[startIndex])) { return startIndex + 1 == types.length ? subStmtContext : findFirstDeclaredSubstatement(subStmtContext, ++startIndex, types); } } return null; } public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findFirstDeclaredSubstatementOnSublevel( final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType, int sublevel) { for (StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) { if (sublevel == 1 && producesDeclared(subStmtContext, declaredType)) { return subStmtContext; } if (sublevel > 1) { final StmtContext<?, ?, ?> result = findFirstDeclaredSubstatementOnSublevel( subStmtContext, declaredType, --sublevel); if (result != null) { return result; } } } return null; } public static <DT extends DeclaredStatement<?>> StmtContext<?, ?, ?> findDeepFirstDeclaredSubstatement( final StmtContext<?, ?, ?> stmtContext, final Class<DT> declaredType) { for (StmtContext<?, ?, ?> subStmtContext : stmtContext.declaredSubstatements()) { if (producesDeclared(subStmtContext, declaredType)) { return subStmtContext; } final StmtContext<?, ?, ?> result = findDeepFirstDeclaredSubstatement(subStmtContext, declaredType); if (result != null) { return result; } } return null; } public static boolean producesDeclared(final StmtContext<?, ?, ?> ctx, final Class<? extends DeclaredStatement<?>> type) { return type.isAssignableFrom(ctx.getPublicDefinition().getDeclaredRepresentationClass()); } public static boolean isInExtensionBody(final StmtContext<?,?,?> stmtCtx) { StmtContext<?,?,?> current = stmtCtx; while (!current.getParentContext().isRootContext()) { current = current.getParentContext(); if (producesDeclared(current, UnknownStatementImpl.class)) { return true; } } return false; } public static boolean isUnknownStatement(final StmtContext<?, ?, ?> stmtCtx) { return producesDeclared(stmtCtx, UnknownStatementImpl.class); } public static Collection<SchemaNodeIdentifier> replaceModuleQNameForKey( final StmtContext<Collection<SchemaNodeIdentifier>, KeyStatement, ?> keyStmtCtx, final QNameModule newQNameModule) { Set<SchemaNodeIdentifier> newKeys = new LinkedHashSet<>(); for (String keyToken : KEY_SPLITTER.split(keyStmtCtx.rawStatementArgument())) { final QName keyQName = QName.create(newQNameModule, keyToken); newKeys.add(SchemaNodeIdentifier.create(false, keyQName)); } return newKeys; } }
package com.microsoft.rest.serializer; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.deser.ResolvableDeserializer; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ObjectNode; import java.io.IOException; import java.lang.reflect.Field; /** * Custom serializer for deserializing complex types with wrapped properties. * For example, a property with annotation @JsonProperty(value = "properties.name") * will be mapped to a top level "name" property in the POJO model. */ public class FlatteningDeserializer extends StdDeserializer<Object> implements ResolvableDeserializer { /** * The default mapperAdapter for the current type. */ private final JsonDeserializer<?> defaultDeserializer; /** * The object mapper for default deserializations. */ private final ObjectMapper mapper; /** * Creates an instance of FlatteningDeserializer. * @param vc handled type * @param defaultDeserializer the default JSON mapperAdapter * @param mapper the object mapper for default deserializations */ protected FlatteningDeserializer(Class<?> vc, JsonDeserializer<?> defaultDeserializer, ObjectMapper mapper) { super(vc); this.defaultDeserializer = defaultDeserializer; this.mapper = mapper; } /** * Gets a module wrapping this serializer as an adapter for the Jackson * ObjectMapper. * * @param mapper the object mapper for default deserializations * @return a simple module to be plugged onto Jackson ObjectMapper. */ public static SimpleModule getModule(final ObjectMapper mapper) { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (beanDesc.getBeanClass().getAnnotation(JsonFlatten.class) != null) { return new FlatteningDeserializer(beanDesc.getBeanClass(), deserializer, mapper); } return deserializer; } }); return module; } @SuppressWarnings("unchecked") @Override public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { JsonNode root = mapper.readTree(jp); final Class<?> tClass = this.defaultDeserializer.handledType(); for (Field field : tClass.getDeclaredFields()) { JsonNode node = root; JsonProperty property = field.getAnnotation(JsonProperty.class); if (property != null) { String value = property.value(); if (value.matches(".+[^\\\\]\\..+")) { String[] values = value.split("((?<!\\\\))\\."); for (String val : values) { node = node.get(val); if (node == null) { break; } } ((ObjectNode) root).put(value, node); } } } JsonParser parser = new JsonFactory().createParser(root.toString()); parser.nextToken(); return defaultDeserializer.deserialize(parser, ctxt); } @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } }
package io.futurestud.tutorials.picasso.ui.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import io.futurestud.tutorials.picasso.R; public class AdvancedImageListAdapter extends ArrayAdapter { private Context context; private LayoutInflater inflater; private String[] imageUrls; public AdvancedImageListAdapter(Context context, String[] imageUrls) { super( context, R.layout.listview_item_image, imageUrls ); this.context = context; this.imageUrls = imageUrls; inflater = LayoutInflater.from( context ); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (null == convertView) { convertView = inflater.inflate( R.layout.listview_item_advanced, parent, false ); viewHolder = new ViewHolder(); viewHolder.text = (TextView) convertView.findViewById( R.id.listview_item_advanced_text ); viewHolder.icon = (ImageView) convertView.findViewById( R.id.listview_item_advanced_imageview ); convertView.setTag( viewHolder ); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.text.setText( "Position " + position ); Picasso .with( context ) .load( imageUrls[position] ) .fit() .centerCrop() .into( viewHolder.icon ); return convertView; } static class ViewHolder { TextView text; ImageView icon; } }
package im.actor.runtime; import im.actor.runtime.power.WakeLock; public class LifecycleRuntimeProvider implements LifecycleRuntime { @Override public void killApp() { throw new RuntimeException("Dumb"); } @Override public WakeLock makeWakeLock() { throw new RuntimeException("Dumb"); } }
package net.kevxu.senselib; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Data container which stores last n data, n is defined by poolSize. It uses * the concept of circular array, but the underlining data container uses * ArrayList due to the need of support generic. This data container is NOT * thread-safe, use with ABSOLUTE caution. * * @author Kaiwen Xu * * @param <T> * Type of data to be stored. */ public class DataPool<T> { private int mPoolSize; private List<T> mPool; private int mStartPos; private int mEndPos; private int mSize; public DataPool(int poolSize) { mPoolSize = poolSize; mPool = new ArrayList<T>(poolSize); mStartPos = 0; mEndPos = 0; mSize = 0; for (int i = 0; i < poolSize; i++) { mPool.add(null); } } public int size() { return mSize; } public int getPoolSize() { return mPoolSize; } public void append(T values) { if (mSize < mPoolSize) { mPool.set(mEndPos, values); mEndPos = (mEndPos + 1) % mPoolSize; mSize++; } else { mStartPos = (mStartPos + 1) % mPoolSize; mPool.set(mEndPos, values); mEndPos = (mEndPos + 1) % mPoolSize; } } public T get(int i) { if (i < mSize) { return mPool.get((mStartPos + i) % mPoolSize); } else { throw new IndexOutOfBoundsException("i is larger than DataPool size."); } } public List<T> getList(int n) { if (n > mSize) { throw new IndexOutOfBoundsException("n is larger than DataPool size."); } List<T> fd = new ArrayList<T>(n); for (int i = 0; i < n; i++) { fd.add(get(i)); } return fd; } public T getFromBack(int i) { return get(mSize - 1 - i); } public List<T> getListFromBack(int n) { if (n > mSize) { throw new IndexOutOfBoundsException("n is larger than DataPool size."); } List<T> pd = new ArrayList<T>(n); for (int i = 0; i < n; i++) { pd.add(getFromBack(i)); } return pd; } @Override public String toString() { return mPool.toString(); } public static void main(String[] args) { Random r = new Random(); DataPool<float[]> pool = new DataPool<float[]>(5); // Appending data System.out.println("Appending data:"); for (int i = 0; i < 10; i++) { float[] values = new float[3]; for (int j = 0; j < 3; j++) { values[j] = (float) r.nextInt(10); } pool.append(values); StringBuilder sb = new StringBuilder(); // sb.append("["); for (int idx = 0; idx < pool.size(); idx++) { sb.append("["); float[] getValues = pool.get(idx); for (int fidx = 0; fidx < 3; fidx++) { sb.append(getValues[fidx]); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append("], "); } sb.delete(sb.length() - 2, sb.length()); // sb.append("]"); System.out.println(sb.toString()); } System.out.println(); // Test get System.out.println("Testing get:"); for (int i = 0; i < 20; i++) { try { float[] value = pool.get(i); StringBuilder sb = new StringBuilder(); sb.append("["); for (int j = 0; j < 3; j++) { sb.append(value[j]).append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append("]"); System.out.println(i + ": " + sb.toString()); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } } System.out.println(); // Test getPrevious System.out.println("Testing getPrevious:"); for (int n = 0; n < 10; n++) { try { List<float[]> pd = pool.getListFromBack(n); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { sb.append("["); for (int j = 0; j < 3; j++) { sb.append(pd.get(i)[j]).append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append("], "); } if (n > 0) sb.delete(sb.length() - 2, sb.length()); System.out.println("previous " + n + ": " + sb.toString()); } catch (IndexOutOfBoundsException e) { e.printStackTrace(); } } System.out.println(); } }
package naftoreiclag.splendidanimator; import java.util.LinkedList; import java.util.List; import org.lwjgl.LWJGLException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.lwjgl.opengl.GL11; import static org.lwjgl.opengl.GL11.*; public class EasyOpenGL { // Shapes private static List<RenderThingy> shapes = new LinkedList(); // Initializer protected static void initialize(int dispW, int dispH) throws LWJGLException { // Make display Display.setDisplayMode(new DisplayMode(dispW, dispH)); Display.setResizable(true); Display.create(); // Set up OpenGL view port syncViewportAndDisplaySizes(); } // Send the stuff to GPU and put on display protected static void updateDisplay() { // If the view port is resized if (Display.wasResized()) { // Re-sync syncViewportAndDisplaySizes(); } clearGPU(); // Draw stuff sendStuffToGPU(); // Update the display Display.update(); // Make sure we go at 60 FPS Display.sync(60); } private static void clearGPU() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); } private static void sendStuffToGPU() { GL11.glColor3f(0.5f, 1.0f, 0.5f); GL11.glPushMatrix(); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2f(0, 0); GL11.glVertex2f(EasyOpenGL.getDisplayWidth(), 0); GL11.glVertex2f(EasyOpenGL.getDisplayWidth(), EasyOpenGL.getDisplayHeight()); GL11.glVertex2f(0, EasyOpenGL.getDisplayHeight()); GL11.glEnd(); GL11.glPopMatrix(); } public static void registerShape(RenderThingy shape) { shapes.add(shape); } public static void unregisterShape(RenderThingy shape) { shapes.remove(shape); } // Cleanup protected static void cleanup() { // Delete the display Display.destroy(); } // Resize the display public static void resizeDisplay(int dispW, int dispH) throws LWJGLException { Display.setDisplayMode(new DisplayMode(dispW, dispH)); } public static int getDisplayWidth() { return Display.getWidth(); } public static int getDisplayHeight() { return Display.getHeight(); } // Sync stuff private static void syncViewportAndDisplaySizes() { // Get the target size final int dispW = Display.getWidth(); final int dispH = Display.getHeight(); // Set image output size glViewport(0, 0, dispW, dispH); glLoadIdentity(); // Reset projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Set the coordinates of the display glOrtho(0.0f, dispW, dispH, 0.0f, 1.0f, -1.0f); // Reset model view glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } }
package net.sf.jaer.util; import java.awt.HeadlessException; import java.awt.event.*; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.logging.Logger; import javax.swing.JFrame; /** * Plays a spike sound on the speaker. Use it by constructing a new {@link SpikeSound}, then calling the {@link #play} method. * * @author tobi * @version $Revision: 1.8 $ */ public class SpikeSound{ static final byte[] ough = { -1,-1,-1,-1,0,-1,-1,-1,0,-1,-1,-1,0,-1,-1,-1,-1,-1,-1,0,0,-1,0,-1,-1,0,0,0,-1,0,-1,0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,0,0,1,1,2,2,2,1,0,-2,-4,-5,-5,-3,-2,1,2,2,2,2,2,3,2,0,-2,-4,-5,-5,-4,-2,0,3,5,6,5,2,-2,-5,-7,-7,-6,-5,-4,-3,-1,1,3,3,-1,-5,-9,-11,-11,-11,-8,-7,-1,14,34,51,78,77,48,22,-29,-71,-80,-79,-64,-48,-33,-19,-5,18,53,63,68,63,32,1,-17,-33,-38,-45,-44,-42,-45,-28,-9,13,39,51,47,33,14,8,1,2,18,28,34,37,22,-3,-26,-44,-56,-50,-47,-35,-27,-24,-1,4,22,41,45,41,30,9,-12,-18,-28,-27,-24,-26,-24,-24,-22,-3,-1,16,25,16,20,10,5,12,25,47,65,68,52,6,-44,-71,-85,-76,-61,-48,-39,-33,-13,11,27,59,73,63,54,25,1,-21,-21,-26,-30,-32,-39,-41,-42,-27,-3,7,20,38,21,30,28,45,75,74,95,71,11,-21,-74,-102,-111,-96,-76,-70,-42,-35,2,32,63,92,86,76,54,27,-5,-28,-33,-43,-53,-51,-64,-68,-58,-28,0,26,40,50,47,49,62,67,79,89,85,58,-13,-60,-91,-127,-122,-102,-86,-67,-41,-5,7,44,85,102,100,83,65,18,-5,-22,-43,-55,-61,-60,-73,-75,-52,-27,-7,34,62,62,66,64,74,64,76,84,74,60,13,-47,-107,-127,-127,-123,-103,-79,-51,-24,16,40,76,115,116,109,84,41,4,-21,-36,-57,-62,-68,-80,-90,-79,-47,-24,17,56,62,70,62,62,65,62,88,84,86,73,18,-53,-109,-127,-127,-127,-116,-95,-64,-34,20,43,79,126,126,126,111,61,18,-16,-40,-57,-80,-86,-109,-114,-103,-77,-32,4,69,84,98,84,69,82,69,87,104,97,87,45,-52,-104,-127,-127,-127,-127,-122,-78,-50,-5,41,68,126,126,126,123,77,28,-8,-33,-39,-55,-90,-111,-124,-127,-104,-67,-15,45,57,74,69,64,78,91,94,108,105,96,84,42,-35,-67,-127,-127,-127,-127,-127,-101,-57,-18,35,68,126,126,126,126,106,60,38,-1,-23,-54,-85,-104,-127,-127,-127,-110,-64,-17,15,63,82,100,117,126,120,126,126,119,95,76,38,-64,-127,-127,-127,-127,-127,-127,-114,-64,18,65,87,126,126,126,126,126,81,17,-21,-48,-80,-127,-127,-127,-127,-127,-109,-94,-44,25,83,116,126,126,126,116,78,87,72,70,85,90,45,-20,-104,-127,-127,-127,-127,-127,-82,-50,5,38,73,126,126,126,126,119,68,8,-25,-52,-71,-93,-102,-116,-127,-127,-111,-89,-62,14,66,101,119,126,126,98,85,74,47,41,48,57,64,52,9,-72,-127,-127,-127,-127,-112,-55,-12,0,37,51,76,95,106,95,78,50,0,-40,-62,-68,-61,-60,-61,-62,-80,-79,-63,-51,-10,35,72,86,100,90,69,57,29,29,28,30,59,91,100,79,18,-36,-108,-127,-127,-127,-108,-66,-44,-28,-7,4,23,69,82,87,99,52,22,-7,-20,-18,-15,-15,-25,-40,-85,-95,-90,-86,-32,12,38,64,70,70,53,43,41,29,38,40,73,91,106,117,78,0,-77,-110,-127,-127,-127,-124,-87,-62,-30,-15,-20,35,86,96,116,116,83,52,29,15,3,-13,-44,-66,-115,-127,-123,-102,-58,-20,41,72,77,84,87,79,66,68,63,33,37,47,57,87,86,43,-11,-95,-127,-127,-127,-127,-81,-26,-2,17,6,21,45,79,107,118,110,59,8,-23,-32,-40,-41,-39,-70,-82,-100,-93,-62,-33,16,54,70,73,65,53,43,43,34,27,15,8,19,37,60,83,96,64,-4,-43,-98,-127,-116,-96,-56,-52,-50,-55,-75,-73,-26,15,69,104,126,103,76,45,32,22,18,7,-21,-68,-100,-127,-127,-104,-71,-5,33,55,57,46,42,42,46,66,67,68,61,54,38,44,53,71,64,10,-25,-81,-127,-127,-127,-112,-84,-64,-61,-62,-53,-22,41,72,116,126,126,112,77,50,32,19,-18,-60,-107,-127,-127,-127,-124,-85,-24,31,61,73,81,89,90,93,98,89,56,24,2,-22,-29,-12,9,33,48,52,32,-17,-52,-71,-90,-88,-68,-58,-63,-55,-34,-18,6,35,72,84,84,86,65,27,10,2,-28,-57,-78,-85,-104,-108,-71,-54,-30,7,38,47,51,70,78,74,61,40,14,-18,-40,-36,-28,-6,10,28,39,44,55,75,76,58,44,6,-41,-77,-88,-95,-86,-68,-49,-33,-29,-12,-1,14,34,53,59,54,33,6,-10,-35,-48,-39,-39,-35,-33,-31,-30,-28,-14,9,26,33,43,42,25,17,7,-1,-11,-15,-9,-4,1,11,35,52,70,81,90,98,94,88,53,9,-40,-79,-120,-127,-127,-121,-98,-76,-58,-49,-41,-10,21,51,76,95,93,69,49,19,-13,-39,-44,-52,-64,-69,-70,-66,-53,-28,-8,23,43,52,59,59,49,41,34,22,13,6,4,5,5,16,25,30,38,46,47,50,52,46,45,37,3,-35,-66,-90,-109,-108,-92,-77,-58,-43,-30,-27,-24,-4,15,24,38,42,36,29,22,15,12,9,4,2,-12,-16,-18,-20,-17,-13,-9,-8,-5,-6,-1,7,5,11,12,7,14,20,26,35,40,44,40,33,21,8,-1,-7,-7,-7,-3,5,5,13,18,23,26,9,-5,-29,-60,-73,-73,-68,-56,-37,-30,-25,-19,-20,-9,3,15,40,50,47,41,28,9,2,-5,-13,-18,-20,-25,-21,-18,-14,-1,3,4,8,6,9,15,19,25,29,25,22,19,17,11,6,0,-1,-8,-10,-11,-17,-23,-23,-23,-20,-13,-2,6,18,22,30,34,36,42,41,38,21,-4,-34,-54,-67,-74,-67,-60,-51,-39,-36,-30,-12,6,30,43,58,57,47,37,22,14,9,7,8,-8,-18,-24,-28,-21,-8,6,13,11,10,4,3,4,8,7,0,-9,-20,-27,-24,-18,-1,10,14,19,15,9,8,10,13,11,10,-3,-16,-24,-26,-20,-7,2,6,4,-5,-8,-6,3,11,13,12,7,-11,-17,-12,-11,-7,6,13,13,11,14,16,16,17,20,12,8,2,-2,-8,-12,-14,-18,-23,-21,-18,-19,-14,-9,-3,1,1,1,5,5,11,12,8,8,3,-2,-6,-10,-20,-25,-26,-31,-31,-24,-24,-19,-15,-9,-4,10,14,23,24,26,27,28,27,29,27,24,23,14,3,1,-1,-1,4,6,8,9,4,5,3,1,6,6,6,8,-2,-8,-12,-13,-10,-11,-17,-22,-32,-32,-34,-34,-36,-32,-20,-13,-2,7,9,11,13,15,17,17,16,9,3,-1,-3,-1,-6,-5,-2,-1,10,13,13,19,18,21,22,16,13,9,4,4,-4,-9,-6,-2,1,4,2,1,-6,-3,-4,-10,-8,-13,-12,-13,-22,-24,-25,-29,-23,-22,-21,-24,-15,-10,2,5,9,22,17,17,12,0,-5,-7,1,15,15,17,14,7,10,11,17,17,20,13,9,8,4,7,6,4,-3,-1,-6,-9,-12,-13,-6,-7,-3,0,-7,-11,-11,-10,-6,-10,0,-2,-1,-4,-10,-8,-8,-8,-1,-2,0,-7,-2,-4,-8,-3,-6,-2,6,0,8,2,-2,16,20,23,29,26,20,14,10,11,-1,-6,-4,-12,-15,-6,-1,0,5,7,-2,0,0,-8,-11,-3,-11,-15,-14,-20,-21,-17,-27,-19,-12,-9,-4,-1,-4,3,-2,-2,10,0,3,6,-1,-4,1,-4,2,14,11,10,9,5,10,4,2,10,7,13,1,3,-4,0,10,14,15,12,17,12,15,13,4,2,-4,-8,-11,-14,-12,-18,-27,-19,-22,-19,-16,-11,-13,-16,-11,-11,-6,-2,1,3,-1,6,10,0,11,6,-1,8,0,-3,8,-3,0,12,-1,4,8,10,8,4,2,6,5,5,20,9,1,6,5,2,2,2,4,-5,-6,-6,-16,-11,-12,-9,-10,-15,-11,-7,-14,-6,-2,-8,-1,9,2,10,-2,-3,-2,-8,-6,-2,-5,3,-5,-13,-3,-7,4,13,16,7,19,12,11,21,14,5,17,1,0,3,-11,3,-14,-12,-3,-20,-7,-9,-11,-4,-5,0,-4,-6,-2,-12,-11,-5,-12,-1,-2,-11,-3,-11,-13,-5,-4,2,8,5,3,9,7,1,13,6,18,11,1,14,12,5,9,3,5,-3,-2,4,-8,-9,0,-5,-3,1,7,5,1,2,0,-8,-8,3,-1,-8,5,2,0,-2,-2,-5,-9,-12,-4,-10,-15,-9,-15,-20,-13,-19,-8,-7,-2,10,2,6,14,13,14,10,9,17,14,13,15,11,9,7,7,1,-1,-4,-3,-7,-10,-11,-10,-11,-10,3,2,5,8,8,3,2,-6,-3,-1,-4,2,0,-6,0,-4,-6,-4,-3,-3,-1,-5,-7,-7,-9,-7,-7,-2,-6,2,4,-1,1,2,1,5,-1,-1,-2,-4,-6,-4,-3,-3,4,7,7,11,5,7,2,3,7,5,0,1,-1,0,-2,-3,-4,-3,-7,-4,-7,1,5,4,10,7,9,-1,1,-5,-10,-4,-10,-6,-7,-12,-10,-8,-10,-1,2,0,4,8,4,5,8,4,1,4,3,3,-1,2,7,0,1,4,0,1,3,6,0,-3,2,0,-3,-4,-4,2,-2,-2,1,-1,0,-5,0,-1,-3,-3,-6,-2,1,-3,-3,-7,-14,-6,-5,-7,-4,-8,-3,-8,-5,-2,-4,-2,1,1,3,3,1,1,7,9,8,16,11,7,4,1,4,-2,1,8,2,-2,-3,-2,0,-9,-7,1,-6,-3,4,1,4,2,3,6,-1,2,3,-3,-5,-4,-10,-9,-8,-7,-8,-5,-7,2,0,0,3,0,0,2,4,2,1,-1,0,-3,-1,-3,-6,0,5,3,5,5,8,7,6,7,3,-1,-1,-6,-7,-9,-8,-6,-2,-3,-5,-2,0,4,4,-1,3,4,0,3,-2,-2,0,-4,-4,-7,-7,-8,-7,-5,-5,0,-1,2,1,-2,4,3,4,0,2,1,0,4,1,1,1,1,4,4,4,1,1,-1,1,3,0,4,1,-1,0,-1,-1,0,-1,2,-2,-3,0,-3,-4,-1,-2,-2,-1,-1,-1,-1,1,-5,-2,-6,-5,-2,-8,-4,-5,-7,-2,-2,-3,0,2,3,6,6,6,6,6,5,7,3,3,4,-1,4,1,-2,0,-1,-3,-4,-3,-1,-1,0,3,3,2,5,3,1,0,-4,-6,-7,-7,-4,-5,-6,-3,-3,-5,-1,-3,0,1,2,1,-2,-2,1,-4,-1,-3,-5,-4,-3,-2,0,-1,5,3,0,5,4,3,7,2,7,3,3,2,1,-2,-3,0,-2,1,2,-1,-1,-5,-4,-5,-7,-5,-5,-4,-5,-2,-5,1,0,-2,0,1,2,4,0,0,-3,-3,-1,0,-1,3,1,-1,-1,0,-1,-1,-1,1,0,0,5,4,3,3,2,1,0,0,4,0,1,0,-2,-2,-6,-3,-3,-1,0,-3,-2,-5,-3,-3,-3,-2,-4,-3,1,-1,1,0,-2,-2,-3,-1,-1,-2,-3,-2,-2,-1,0,-1,0,2,3,3,3,2,6,2,4,3,2,2,0,0,1,-1,-1,-2,-1,0,-1,-2,1,-2,1,1,0,1,-1,0,2,0,2,3,-1,0,0,-2,1,-2,-6,-2,-3,-3,-2,-3,-3,-2,-4,-2,1,-2,0,0,0,1,2,1,1,0,0,-4,-2,-4,-3,-1,-2,1,0,0,0,2,1,-1,1,-3,-2,0,-2,-1,0,0,1,3,2,0,0,-1,1,-4,-5,-1,-4,1,-2,-2,-3,-4,2,1,2,2,2,2,3,2,3,1,-1,-1,-4,-4,-3,-4,-3,-5,-3,-3,-2,2,2,2,2,1,1,1,1,1,0,-1,-2,-1,-2,-3,0,0,-1,0,-3,0,-1,-1,0,-2,0,1,1,0,1,1,2,1,-1,-3,-3,-4,-3,-3,0,1,0,1,2,1,3,3,2,2,1,-1,0,-2,1,0,-4,0,-2,-3,-1,-3,-3,-2,-2,-1,-2,-1,0,1,2,3,1,2,3,2,0,-1,-2,-3,-1,-2,-3,-3,-2,-1,-1,-1,0,-1,0,-1,1,-1,-1,1,0,0,-1,-3,-2,-3,-2,-1,-2,-2,-1,-1,-1,0,0,0,-1,-1,-1,0,1,2,2,-1,0,-1,-1,0,-2,-1,-1,-2,-1,0,-1,1,0,0,0,0,0,0,-1,0,-1,-1,1,-1,1,1,1,1,1,0,0,-2,1,1,0,-1,-2,-2,-2,-1,-2,-3,-4,-2,-2,0,3,2,1,0,0,-1,0,0,1,-1,0,0,1,0,0,2,0,0,-1,-2,-1,0,0,-1,-2,-1,1,1,1 }; enum SoundShape{ SQUARE, ROUNDED, OUGH }; SoundShape shape = SoundShape.ROUNDED; /** duration of spike sound in ms */ public static final int SPIKE_DURATION_MS = 2; /** sample rate in Hz */ public static final float SAMPLE_RATE = 8000f; // 44100; // tobi changed to try on linux since 8000f doesn't seem to work 8000f; /** length of spike sound sample in samples. Duration of spike sound is BUFFER_LENGTH/{@link #SAMPLE_RATE}. * e.g., with a sample rate of 4kHz, 8 sample spikes make the spikes 2ms long. This seems about right. */ public static int SPIKE_BUFFER_LENGTH = Math.round(SAMPLE_RATE * SPIKE_DURATION_MS / 1000); /** amplitude of spike sound. */ public static final byte SPIKE_AMPLITUDE = 127; public static AudioFormat audioFormat = null; AudioInputStream spike = null, spikeLeft = null, spikeRight = null; private byte[] spikeSoundSamples, spikeSoundSamplesLeft, spikeSoundSamplesRight; // private AudioInputStream spikeStream, spikeStreamLeft, spikeStreamRight; private SourceDataLine line = null; static Logger log = Logger.getLogger("SpikeSound"); /** Creates a new instance of SpikeSound */ public SpikeSound (){ // define format of sound audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,SAMPLE_RATE,8,2,2,SAMPLE_RATE,false); // spike sound defined here by the waveform contructed here spikeSoundSamples = new byte[ SPIKE_BUFFER_LENGTH ]; spikeSoundSamplesLeft = new byte[ SPIKE_BUFFER_LENGTH ]; spikeSoundSamplesRight = new byte[ SPIKE_BUFFER_LENGTH ]; // even samples are right channel, odd samples are left channel (by expt) switch ( shape ){ case SQUARE: for ( int i = 0 ; i < spikeSoundSamples.length / 2 - 1 ; i++ ){ spikeSoundSamples[i] = (byte)( SPIKE_AMPLITUDE ); } for ( int i = spikeSoundSamples.length / 2 ; i < spikeSoundSamples.length ; i++ ){ spikeSoundSamples[i] = (byte)( -SPIKE_AMPLITUDE ); } break; case ROUNDED: { int m = spikeSoundSamples.length / 2; for ( int i = 0 ; i < m - 1 ; i += 2 ){ double x = Math.PI * (double)( i - m / 2 ) / m * 2; double y = Math.sin(x); byte z = (byte)( ( SPIKE_AMPLITUDE ) * x ); spikeSoundSamples[i] = z; spikeSoundSamples[i + 1] = z; spikeSoundSamplesLeft[i + 1] = z; spikeSoundSamplesRight[i] = z; } } break; case OUGH: { SPIKE_BUFFER_LENGTH = ough.length; spikeSoundSamples = new byte[ SPIKE_BUFFER_LENGTH ]; spikeSoundSamplesLeft = new byte[ SPIKE_BUFFER_LENGTH ]; spikeSoundSamplesRight = new byte[ SPIKE_BUFFER_LENGTH ]; for ( int i = 0 ; i < spikeSoundSamples.length ; i++ ){ spikeSoundSamples[i] = ough[i]; spikeSoundSamplesLeft[i] = ough[i]; spikeSoundSamplesRight[i] = ough[i]; } } break; default: throw new Error("no such sound shape " + shape); } // make an input stream from the sound sample bytes InputStream spikeStream = new ByteArrayInputStream(spikeSoundSamples); InputStream spikeStreamLeft = new ByteArrayInputStream(spikeSoundSamplesLeft); InputStream spikeStreamRight = new ByteArrayInputStream(spikeSoundSamplesRight); // make an audio input stream using the bytes and with with audio format spike = new AudioInputStream(spikeStream,audioFormat,SPIKE_BUFFER_LENGTH); spikeLeft = new AudioInputStream(spikeStreamLeft,audioFormat,SPIKE_BUFFER_LENGTH); spikeRight = new AudioInputStream(spikeStreamRight,audioFormat,SPIKE_BUFFER_LENGTH); // System.out.println("spike format="+spike.getFormat()); // System.out.println("spike frame length="+spike.getFrameLength()); // get info on possible SourceDataLine's // these are lines that you can source into DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat); try{ // get a line from the system line = (SourceDataLine)AudioSystem.getLine(info); // line = (SourceDataLine) AudioSystem.getSourceDataLine(audioFormat); //open it with our AudioFormat line.open(audioFormat); if ( spike.markSupported() ){ spike.mark(SPIKE_BUFFER_LENGTH); } // System.out.println("line bufferSize="+line.getBufferSize()); // System.out.println("line format="+line.getFormat()); // System.out.println("line info="+line.getLineInfo()); line.start(); } catch ( LineUnavailableException e ){ log.warning("Could not open sound output for playing spike sounds: " + e.toString()); line = null; } catch ( Exception e ){ log.warning("Could not open sound output for playing spike sounds: " + e.toString()); // e.printStackTrace(); line = null; } } // used for buffering in to out in play()... private byte[] abData = new byte[ SPIKE_BUFFER_LENGTH ]; /** plays the spike sound once. Has a problem that it seems to recirculate the sound forever... */ public void play (){ if ( line == null ){ return; } try{ // flush any spike sound not yet played out. line.flush(); // reset ourselves to start of input data, to reread the spike data samples spike.reset(); // read the data to write int nRead = spike.read(abData); // write out the data from the input stream (the spike samples) to the output stream (the SourceDataLine) int nWritten = line.write(abData,0,nRead); } catch ( IOException e ){ e.printStackTrace(); } } /** @param leftRight 0 to play left, 1 to play right */ public void play (int leftRight){ if ( line == null ){ return; } try{ // flush any spike sound not yet played out. line.flush(); if ( leftRight % 2 == 0 ){// reset ourselves to start of input data, to reread the spike data samples spikeLeft.reset(); // read the data to write int nRead = spikeLeft.read(abData); // write out the data from the input stream (the spike samples) to the output stream (the SourceDataLine) int nWritten = line.write(abData,0,nRead); } else{ spikeRight.reset(); // read the data to write int nRead = spikeRight.read(abData); // write out the data from the input stream (the spike samples) to the output stream (the SourceDataLine) int nWritten = line.write(abData,0,nRead); } } catch ( IOException e ){ e.printStackTrace(); } } static class SSTest extends JFrame{ final SpikeSound ss = new SpikeSound(); int side = 0; public SSTest () throws HeadlessException{ super("SSTest"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(50,128); // We use window width as volume control addKeyListener(new KeyAdapter(){ public void keyPressed (KeyEvent e){ ss.play(side); } public void keyReleased (KeyEvent e){ } }); addMouseMotionListener(new MouseMotionAdapter(){ public void mouseMoved (MouseEvent e){ side = e.getX() > getWidth() / 2 ? 0 : 1; } }); } } public static void main (String[] args){ SSTest ssTest; ssTest=new SSTest(); ssTest.setVisible(true); } } // SpikeSound
package nl.mpi.arbil; import nl.mpi.arbil.data.ImdiTreeObject; import java.awt.Color; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Vector; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.table.AbstractTableModel; public class ImdiTableModel extends AbstractTableModel { // variables used by the thread boolean reloadRequested = false; boolean treeNodeSortQueueRunning = false; // end variables used by the thread private boolean showIcons = false; private Hashtable<String, ImdiTreeObject> imdiObjectHash = new Hashtable<String, ImdiTreeObject>(); private HashMap<String, ImdiField> filteredColumnNames = new HashMap<String, ImdiField>(); Vector childColumnNames = new Vector(); LinorgFieldView tableFieldView; boolean horizontalView = false; private int sortColumn = -1; private JLabel hiddenColumnsLabel; public boolean hideContextMenuAndStatusBar; boolean sortReverse = false; DefaultListModel listModel = new DefaultListModel(); // used by the image display panel Vector highlightCells = new Vector(); String[] singleNodeViewHeadings = new String[]{"IMDI Field", "Value"}; private String[] columnNames = new String[0]; private Object[][] data = new Object[0][0]; Color cellColour[][] = new Color[0][0]; public ImdiTableModel() { tableFieldView = ImdiFieldViews.getSingleInstance().getCurrentGlobalView().clone(); } public void setHiddenColumnsLabel(JLabel hiddenColumnsLabelLocal) { hiddenColumnsLabel = hiddenColumnsLabelLocal; } public DefaultListModel getListModel(LinorgSplitPanel imdiSplitPanel) { ImdiListDataListener listDataListener = new ImdiListDataListener(imdiSplitPanel); listModel.addListDataListener(listDataListener); return listModel; } // end code related to the list display of resources and loose files public void setCurrentView(LinorgFieldView localFieldView) { LinorgFieldView tempFieldView = localFieldView.clone(); for (Enumeration oldKnowenColoumns = tableFieldView.getKnownColumns(); oldKnowenColoumns.hasMoreElements();) { tempFieldView.addKnownColumn(oldKnowenColoumns.nextElement().toString()); } tableFieldView = tempFieldView; requestReloadTableData(); } public ImdiTreeObject[] getSelectedImdiNodes(int[] selectedRows) { ImdiTreeObject[] selectedNodesArray = new ImdiTreeObject[selectedRows.length]; for (int selectedRowCounter = 0; selectedRowCounter < selectedRows.length; selectedRowCounter++) { selectedNodesArray[selectedRowCounter] = getImdiNodeFromRow(selectedRows[selectedRowCounter]); } return selectedNodesArray; } public boolean containsImdiNode(ImdiTreeObject findable) { if (findable == null) { return false; } return imdiObjectHash.contains(findable); } public int getImdiNodeCount() { return imdiObjectHash.size(); } public Enumeration getImdiNodes() { return imdiObjectHash.elements(); } public String[] getImdiNodesURLs() { return imdiObjectHash.keySet().toArray(new String[]{}); } public void setShowIcons(boolean localShowIcons) { showIcons = localShowIcons; } public void addImdiObjects(ImdiTreeObject[] nodesToAdd) { for (int draggedCounter = 0; draggedCounter < nodesToAdd.length; draggedCounter++) { addImdiObject(nodesToAdd[draggedCounter]); } requestReloadTableData(); } public void addImdiObjects(Enumeration nodesToAdd) { while (nodesToAdd.hasMoreElements()) { Object currentObject = nodesToAdd.nextElement(); //System.out.println("addImdiObjects: " + currentObject.toString()); addImdiObject((ImdiTreeObject) currentObject); } requestReloadTableData(); } public void addSingleImdiObject(ImdiTreeObject imdiTreeObject) { addImdiObject(imdiTreeObject); requestReloadTableData(); } private void addImdiObject(ImdiTreeObject imdiTreeObject) { if (imdiTreeObject != null) { // on start up the previous windows are loaded and the imdi nodes will not be loaded hence they will have no fields, so we have to check for that here if (imdiTreeObject.isDirectory() || (!imdiTreeObject.getParentDomNode().isLoading() && imdiTreeObject.isEmptyMetaNode())) { // add child nodes if there are no fields ie actors node will add all the actors // add child nodes if it is a directory // this is non recursive and does not reload the table for (ImdiTreeObject currentChild : imdiTreeObject.getChildArray()) { imdiObjectHash.put(currentChild.getUrlString(), currentChild); currentChild.registerContainer(this); } } else { imdiObjectHash.put(imdiTreeObject.getUrlString(), imdiTreeObject); imdiTreeObject.registerContainer(this); } } } private ImdiTreeObject[] updateAllImdiObjects() { ImdiTreeObject[] returnImdiArray = imdiObjectHash.values().toArray(new ImdiTreeObject[]{}); filteredColumnNames.clear(); int hiddenColumnCount = 0; for (ImdiTreeObject currentRowImdi : returnImdiArray) { for (ImdiField[] currentFieldArray : currentRowImdi.getFields().values().toArray(new ImdiField[][]{})) { for (ImdiField currentField : currentFieldArray) { String currentColumnName = currentField.getTranslateFieldName(); if (tableFieldView.viewShowsColumn(currentColumnName)) { if (!filteredColumnNames.containsKey(currentColumnName)) { filteredColumnNames.put(currentColumnName, currentField); } else { // update the min id value ImdiField lastStoredField = filteredColumnNames.get(currentColumnName); if (currentField.getFieldOrder() != -1) { if (lastStoredField.getFieldOrder() > currentField.getFieldOrder()) { filteredColumnNames.put(currentColumnName, currentField); } } } } else { hiddenColumnCount++; } tableFieldView.addKnownColumn(currentColumnName); } } } if (hiddenColumnsLabel != null) { hiddenColumnsLabel.setVisible(!hideContextMenuAndStatusBar && hiddenColumnCount > 0); hiddenColumnsLabel.setText(hiddenColumnCount + " columns hidden (edit \"Column View\" in the table header to show)"); } return returnImdiArray; } private void updateImageDisplayPanel() { listModel.removeAllElements(); ImageBoxRenderer tempImageBoxRenderer = new ImageBoxRenderer(); for (int rowCounter = 0; rowCounter < data.length; rowCounter++) { ImdiTreeObject currentRowImdiObject = getImdiNodeFromRow(rowCounter); if (currentRowImdiObject != null) { if (tempImageBoxRenderer.canDisplay(currentRowImdiObject)) { if (!listModel.contains(currentRowImdiObject)) { listModel.addElement(currentRowImdiObject); } } } } } public void removeAllImdiRows() { listModel.removeAllElements(); for (Enumeration removableNodes = imdiObjectHash.elements(); removableNodes.hasMoreElements();) { ((ImdiTreeObject) removableNodes.nextElement()).removeContainer(this); } imdiObjectHash.clear(); filteredColumnNames.clear(); columnNames = new String[0]; data = new Object[0][0]; cellColour = new Color[0][0]; // add the icon column if icons are to be displayed setShowIcons(showIcons); requestReloadTableData(); } private ImdiTreeObject getImdiNodeFromRow(int rowNumber) { // TODO: find error removing rows // look again here... // if that the first column is the imdi node (ergo string and icon) use that to remove the row if (data[rowNumber][0] instanceof ImdiTreeObject) { return (ImdiTreeObject) data[rowNumber][0]; } else if (data[rowNumber][0] instanceof ImdiField[]) { return ((ImdiField[]) data[rowNumber][columnNames.length - 1])[0].parentImdi; } else { // in the case that the icon and sting are not displayed then try to get the imdifield in order to get the imdinode // TODO: this will fail if the imdiobject for the row does not have a field to display for the first column because there will be no imdi nor field in the first coloumn return ((ImdiField) data[rowNumber][columnNames.length - 1]).parentImdi; //throw new UnsupportedOperationException("Not supported yet."); } } public void removeImdiRows(int[] selectedRows) { ImdiTreeObject[] nodesToRemove = new ImdiTreeObject[selectedRows.length]; for (int selectedRowCounter = 0; selectedRowCounter < selectedRows.length; selectedRowCounter++) { System.out.println("removing: " + selectedRowCounter); nodesToRemove[selectedRowCounter] = getImdiNodeFromRow(selectedRows[selectedRowCounter]); } removeImdiObjects(nodesToRemove); } // utility to join an array to a comma separated string private String joinArray(Object[] arrayToJoin) { String joinedString = ""; for (Object currentArrayItem : arrayToJoin) { joinedString = joinedString + "," + currentArrayItem.toString(); } if (joinedString.length() > 1) { joinedString = joinedString.substring(1); } return joinedString; } public void copyHtmlEmbedTagToClipboard(int tableHeight, int tableWidth) { try { LinorgVersion arbilVersion = new LinorgVersion(); // TODO: the clas path specified here needs to be dynamically generated String embedTagString = "<APPLET CODEBASE=\"http: embedTagString = embedTagString + " WIDTH=" + tableWidth + " HEIGHT=" + tableHeight + " >\n"; embedTagString = embedTagString + " <PARAM NAME=\"ImdiFileList\" VALUE=\"" + joinArray(this.getImdiNodesURLs()) + "\">\n"; embedTagString = embedTagString + " <PARAM NAME=\"ShowOnlyColumns\" VALUE=\"" + joinArray(this.columnNames) + "\">\n"; embedTagString = embedTagString + " <PARAM NAME=\"ChildNodeColumns\" VALUE=\"" + joinArray(this.childColumnNames.toArray()) + "\">\n"; embedTagString = embedTagString + " <PARAM NAME=\"HighlightText\" VALUE=\"" + joinArray(this.highlightCells.toArray()) + "\">\n"; embedTagString = embedTagString + "</APPLET>"; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(embedTagString); clipboard.setContents(stringSelection, GuiHelper.clipboardOwner); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } public void copyImdiFields(ImdiField[] selectedCells) { String csvSeparator = "\t"; // excel seems to work with tab but not comma String copiedString = ""; copiedString = copiedString + "\"" + singleNodeViewHeadings[0] + "\"" + csvSeparator; copiedString = copiedString + "\"" + singleNodeViewHeadings[1] + "\""; copiedString = copiedString + "\n"; boolean isFirstCol = true; for (ImdiField currentField : selectedCells) { if (!isFirstCol) { copiedString = copiedString + csvSeparator; isFirstCol = false; } copiedString = copiedString + "\"" + currentField.getTranslateFieldName() + "\"" + csvSeparator; copiedString = copiedString + "\"" + currentField.getFieldValue() + "\""; copiedString = copiedString + "\n"; } System.out.println("copiedString: " + copiedString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(copiedString); clipboard.setContents(stringSelection, GuiHelper.clipboardOwner); } public void copyImdiRows(int[] selectedRows) { String csvSeparator = "\t"; // excel seems to work with tab but not comma String copiedString = ""; int firstColumn = 0; if (showIcons && horizontalView) { // horizontalView excludes icon display firstColumn = 1; } // add the headers int columnCount = getColumnCount(); for (int selectedColCounter = firstColumn; selectedColCounter < columnCount; selectedColCounter++) { copiedString = copiedString + "\"" + getColumnName(selectedColCounter) + "\""; if (selectedColCounter < columnCount - 1) { copiedString = copiedString + csvSeparator; } } copiedString = copiedString + "\n"; // add the cell data for (int selectedRowCounter = 0; selectedRowCounter < selectedRows.length; selectedRowCounter++) { System.out.println("copying row: " + selectedRowCounter); for (int selectedColCounter = firstColumn; selectedColCounter < columnCount; selectedColCounter++) { copiedString = copiedString + "\"" + data[selectedRows[selectedRowCounter]][selectedColCounter].toString().replace("\"", "\"\"") + "\""; if (selectedColCounter < columnCount - 1) { copiedString = copiedString + csvSeparator; } } copiedString = copiedString + "\n"; } //System.out.println("copiedString: " + this.get getCellSelectionEnabled()); System.out.println("copiedString: " + copiedString); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection stringSelection = new StringSelection(copiedString); clipboard.setContents(stringSelection, GuiHelper.clipboardOwner); } public String pasteIntoImdiFields(ImdiField[] selectedCells) { boolean pastedFieldOverwritten = false; int pastedCount = 0; String resultMessage = null; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transfer = clipboard.getContents(null); try { String clipBoardString = ""; Object clipBoardData = transfer.getTransferData(DataFlavor.stringFlavor); if (clipBoardData != null) {//TODO: check that this is not null first but let it pass on null so that the no data to paste messages get sent to the user clipBoardString = clipBoardData.toString(); } System.out.println("clipBoardString: " + clipBoardString); // to do this there must be either two rows or two columns otherwise we should abort String[] clipBoardLines = clipBoardString.split("\"\\n\""); if (clipBoardLines.length == 1) { // re try in case the csv text is not quoted clipBoardLines = clipBoardString.split("\n"); } if (clipBoardLines.length == 1) { String messageString = selectedCells.length + " fields will be overwritten with the single value on the clipboard.\nContinue?"; if (LinorgWindowManager.getSingleInstance().showMessageDialogBox(messageString, "Paste")) { for (ImdiField targetField : selectedCells) { targetField.setFieldValue(clipBoardString, true, false); pastedCount++; } } else { return null; } } else if (clipBoardLines.length > 1) { String areYouSureMessageString = ""; ArrayList<Object[]> pasteList = new ArrayList<Object[]>(); int deletingValuesCounter = 0; String[] firstLine = clipBoardLines[0].split("\"\\t\""); if (firstLine.length == 1) { firstLine = clipBoardLines[0].split("\t"); } boolean singleNodeAxis = false; String regexString = "[(\"^)($\")]"; System.out.println("regexString: " + (firstLine[0].replaceAll(regexString, ""))); if (firstLine[0].replaceAll(regexString, "").equals(singleNodeViewHeadings[0]) && firstLine[1].replaceAll(regexString, "").equals(singleNodeViewHeadings[1])) { singleNodeAxis = true; } if (!singleNodeAxis) { resultMessage = "Incorrect data to paste.\nThe data must be copied either from a table where only one IMDI file is displayed\nor by selecting individual cells in the table."; } if (singleNodeAxis) { boolean pasteOneFieldToAll = clipBoardLines.length == 2; /* skip the header */ HashSet<String> pastedFieldNames = new HashSet(); for (int lineCounter = 1 /* skip the header */; lineCounter < clipBoardLines.length; lineCounter++) { String clipBoardLine = clipBoardLines[lineCounter]; System.out.println("clipBoardLine: " + clipBoardLine); String[] clipBoardCells = clipBoardLine.split("\\t"); System.out.println("clipBoardCells.length: " + clipBoardCells.length); if (clipBoardCells.length != 2) { resultMessage = "Inconsistent number of columns in the data to paste.\nThe pasted data could be incorrect."; } else { String currentFieldName = clipBoardCells[0].replaceAll(regexString, ""); String currentFieldValue = clipBoardCells[1].replaceAll(regexString, ""); if (pastedFieldNames.contains(currentFieldName)) { pastedFieldOverwritten = true; } else { pastedFieldNames.add(currentFieldName); } if (selectedCells != null) { for (ImdiField targetField : selectedCells) { System.out.println("targetField: " + targetField.getTranslateFieldName()); //messagebox "The copied field name does not match the destination, do you want to paste anyway?" if (currentFieldName.equals(targetField.getTranslateFieldName()) || pasteOneFieldToAll) { if (currentFieldValue.trim().length() == 0 && targetField.getFieldValue().trim().length() > 0) { deletingValuesCounter++; } pasteList.add(new Object[]{targetField, currentFieldValue}); } } } } } if (pastedFieldOverwritten) { areYouSureMessageString = areYouSureMessageString + "Two fields of the same name are to be pasted into this table,\nthis will cause at least one field to be overwritten by another.\n\n"; } if (deletingValuesCounter > 0) { areYouSureMessageString = areYouSureMessageString + "There are " + deletingValuesCounter + " fields that will have their contents deleted by this paste action.\n\n"; } if (areYouSureMessageString.length() > 0) { if (!LinorgWindowManager.getSingleInstance().showMessageDialogBox(areYouSureMessageString + "Continue?", "Paste")) { return null; } } for (Object[] pasteListObject : pasteList) { ImdiField currentField = (ImdiField) pasteListObject[0]; String currentValue = (String) pasteListObject[1]; currentField.setFieldValue(currentValue, true, false); pastedCount++; } } } else { resultMessage = "No data to paste."; } if (pastedCount == 0) { if (resultMessage == null) { resultMessage = "No fields matched the data on the clipboard."; } } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } return resultMessage; } public void removeImdiObjects(ImdiTreeObject[] nodesToRemove) { for (ImdiTreeObject imdiTreeObject : nodesToRemove) { if (imdiTreeObject != null) { System.out.println("removing: " + imdiTreeObject.toString()); listModel.removeElement(imdiTreeObject); imdiObjectHash.remove(imdiTreeObject.getUrlString()); imdiTreeObject.removeContainer(this); } } // refresh the table data requestReloadTableData(); } public void clearCellColours() { highlightCells.clear(); for (int rowCounter = 0; rowCounter < cellColour.length; rowCounter++) { for (int colCounter = 0; colCounter < cellColour[rowCounter].length; colCounter++) { cellColour[rowCounter][colCounter] = new Color(0xFFFFFF); } } fireTableDataChanged(); } private Color[][] setCellColours(Object[][] dataTemp) { Color[][] cellColourTemp; if (dataTemp.length == 0) { cellColourTemp = new Color[0][0]; } else { cellColourTemp = new Color[dataTemp.length][dataTemp[0].length]; Color currentHighlightColur = new Color(0xFFFFFF); for (Enumeration currentHighlight = highlightCells.elements(); currentHighlight.hasMoreElements();) { // rotate the next colour currentHighlightColur = new Color(currentHighlightColur.getGreen() - 40, currentHighlightColur.getRed(), currentHighlightColur.getBlue()); String currentText = currentHighlight.nextElement().toString(); // search the table for matching cells for (int rowCounter = 0; rowCounter < dataTemp.length; rowCounter++) { for (int colCounter = 0; colCounter < dataTemp[rowCounter].length; colCounter++) { if (new ImdiTableCellRenderer(dataTemp[rowCounter][colCounter]).getText().equals(currentText)) { cellColourTemp[rowCounter][colCounter] = currentHighlightColur; } } } } } return cellColourTemp; } private Object[][] allocateCellData(int rows, int cols) { Object[][] dataTemp = new Object[rows][cols]; return dataTemp; } private class TableRowComparator implements Comparator { int sortColumn = 0; boolean sortReverse = false; public TableRowComparator(int tempSortColumn, boolean tempSortReverse) { sortColumn = tempSortColumn; sortReverse = tempSortReverse; // System.out.println("TableRowComparator: " + sortColumn + ":" + sortReverse); } public int compare(Object firstRowArray, Object secondRowArray) { if (sortColumn >= 0) { // (done by setting when the hor ver setting changes) need to add a check for horizontal view and -1 which is invalid String baseValueA = new ImdiTableCellRenderer(((Object[]) firstRowArray)[sortColumn]).getText(); String comparedValueA = new ImdiTableCellRenderer(((Object[]) secondRowArray)[sortColumn]).getText(); // TODO: add the second or more sort column // if (!(baseValueA.equals(comparedValueA))) { // return baseValueB.compareTo(comparedValueB); // } else { // return baseValueA.compareTo(comparedValueA); int returnValue = baseValueA.compareTo(comparedValueA); if (sortReverse) { returnValue = 1 - returnValue; } return returnValue; } else { try { // if (baseValueA != null && comparedValueA != null) { // if either id is null then check why it is being draw when it should be reloaded first int baseIntA = ((ImdiField) ((Object[]) firstRowArray)[1]).getFieldOrder(); int comparedIntA = ((ImdiField) ((Object[]) secondRowArray)[1]).getFieldOrder(); int returnValue = baseIntA - comparedIntA; if (returnValue == 0) { // if the xml node order is the same then also sort on the strings String baseStrA = ((ImdiField) ((Object[]) firstRowArray)[1]).getFieldValue(); String comparedStrA = ((ImdiField) ((Object[]) secondRowArray)[1]).getFieldValue(); returnValue = baseStrA.compareToIgnoreCase(comparedStrA); } return returnValue; // } else { // return 0; } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); return 1; } } } } private void sortTableRows(String[] columnNamesTemp, Object[][] dataTemp) { // System.out.println("sortTableRows"); if (sortColumn < columnNamesTemp.length) { Arrays.sort(dataTemp, new TableRowComparator(sortColumn, sortReverse)); } } synchronized public void requestReloadTableData() { reloadRequested = true; if (!treeNodeSortQueueRunning) { treeNodeSortQueueRunning = true; new Thread() { @Override public void run() { try { // here we only want to respond the a request when it is requred but also respond if the request has arrived since the last reload started while (reloadRequested) { reloadRequested = false; reloadTableDataPrivate(); } } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } treeNodeSortQueueRunning = false; } }.start(); } } // this will be hit by each imdi node in the table when the application starts hence it needs to be either put in a queue or be synchronised private synchronized void reloadTableDataPrivate() { // with the queue this does not need to be synchronised but in this case it will not slow things too much // System.out.println("reloadTableData"); int previousColumnCount = getColumnCount(); String[] columnNamesTemp = new String[0]; Object[][] dataTemp = new Object[0][0]; ImdiTreeObject[] tableRowsImdiArray = updateAllImdiObjects(); // set the view to either horizontal or vertical and set the default sort boolean lastHorizontalView = horizontalView; horizontalView = tableRowsImdiArray.length > 1; if (!horizontalView) { // set the table for a single image if that is all that is shown //if (imdiObjectHash.size() == listModel.getSize()) { // TODO: this does not account for when a resource is shown // TODO: this does not account for when a resource is shown if (filteredColumnNames.size() == 0) { horizontalView = true; } } if (lastHorizontalView != horizontalView) { sortReverse = false; // update to the default sort if (horizontalView) { sortColumn = 0; } else { sortColumn = -1; } } if (horizontalView) { // display the grid view // calculate which of the available columns to show ImdiField[] displayedColumnNames = filteredColumnNames.values().toArray(new ImdiField[filteredColumnNames.size()]); Arrays.sort(displayedColumnNames, new Comparator<ImdiField>() { public int compare(ImdiField firstColumn, ImdiField secondColumn) { try { int baseIntA = ((ImdiField) firstColumn).getFieldOrder(); int comparedIntA = ((ImdiField) secondColumn).getFieldOrder(); int returnValue = baseIntA - comparedIntA; if (returnValue == 0) { // if the xml node order is the same then also sort on the strings String baseStrA = firstColumn.getFieldValue(); String comparedStrA = secondColumn.getFieldValue(); returnValue = baseStrA.compareToIgnoreCase(comparedStrA); } return returnValue; } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); return 1; } } }); // end calculate which of the available columns to show // set the column offset to accomadate the icon which is not in the column hashtable int firstFreeColumn = 0; if (showIcons) { // System.out.println("showing icon"); // this assumes that the icon will always be in the leftmost column firstFreeColumn = 1; } // create and populate the column names array and prepend the icon and append the imdinode columnNamesTemp = new String[displayedColumnNames.length + firstFreeColumn + childColumnNames.size()]; int columnPopulateCounter = firstFreeColumn; if (columnNamesTemp.length > 0) { columnNamesTemp[0] = " "; // make sure the the icon column is shown its string is not null } for (ImdiField currentColumn : displayedColumnNames) { // System.out.println("columnPopulateCounter: " + columnPopulateCounter); columnNamesTemp[columnPopulateCounter] = currentColumn.getTranslateFieldName(); columnPopulateCounter++; } // populate the child node column titles for (Enumeration childColEnum = childColumnNames.elements(); childColEnum.hasMoreElements();) { columnNamesTemp[columnPopulateCounter] = childColEnum.nextElement().toString(); columnPopulateCounter++; } // end create the column names array and prepend the icon and append the imdinode dataTemp = allocateCellData(tableRowsImdiArray.length, columnNamesTemp.length); int rowCounter = 0; for (ImdiTreeObject currentNode : tableRowsImdiArray) { // System.out.println("currentNode: " + currentNode.toString()); Hashtable<String, ImdiField[]> fieldsHash = currentNode.getFields(); if (showIcons) { //data[rowCounter][0] = new JLabel(currentNode.toString(), currentNode.getIcon(), JLabel.LEFT); dataTemp[rowCounter][0] = currentNode; } for (int columnCounter = firstFreeColumn; columnCounter < columnNamesTemp.length; columnCounter++) { //System.out.println("columnNames[columnCounter]: " + columnNames[columnCounter] + " : " + columnCounter); if (columnCounter < columnNamesTemp.length - childColumnNames.size()) { ImdiField[] currentValue = fieldsHash.get(columnNamesTemp[columnCounter]); if (currentValue != null) { if (currentValue.length == 1) { dataTemp[rowCounter][columnCounter] = currentValue[0]; } else { dataTemp[rowCounter][columnCounter] = currentValue; } } else { dataTemp[rowCounter][columnCounter] = ""; } } else { // populate the cell with any the child nodes for the current child nodes column dataTemp[rowCounter][columnCounter] = currentNode.getChildNodesArray(columnNamesTemp[columnCounter]); // prevent null values if (dataTemp[rowCounter][columnCounter] == null) { dataTemp[rowCounter][columnCounter] = ""; } } } rowCounter++; } // System.out.println("setting column widths: " + maxColumnWidthsTemp); // // display the column names use count for testing only // Enumeration tempEnum = columnNameHash.elements(); // int tempColCount = 0; // while (tempEnum.hasMoreElements()){ // data[0][tempColCount] = tempEnum.nextElement().toString(); // tempColCount++; } else { // display the single node view columnNamesTemp = singleNodeViewHeadings; if (tableRowsImdiArray.length == 0) { dataTemp = allocateCellData(0, columnNamesTemp.length); } else { if (tableRowsImdiArray[0] != null) { Hashtable<String, ImdiField[]> fieldsHash = tableRowsImdiArray[0].getFields(); // calculate the real number of rows Vector<ImdiField> allRowFields = new Vector(); for (Enumeration<ImdiField[]> valuesEnum = fieldsHash.elements(); valuesEnum.hasMoreElements();) { ImdiField[] currentFieldArray = valuesEnum.nextElement(); for (ImdiField currentField : currentFieldArray) { if (tableFieldView.viewShowsColumn(currentField.getTranslateFieldName())) { allRowFields.add(currentField); } } } dataTemp = allocateCellData(allRowFields.size(), 2); // Enumeration<String> labelsEnum = fieldsHash.keys(); // Enumeration<ImdiField[]> valuesEnum = fieldsHash.elements(); int rowCounter = 0; for (Enumeration<ImdiField> allFieldsEnum = allRowFields.elements(); allFieldsEnum.hasMoreElements();) { ImdiField currentField = allFieldsEnum.nextElement(); dataTemp[rowCounter][0] = currentField.getTranslateFieldName(); dataTemp[rowCounter][1] = currentField; rowCounter++; } } } } // update the table model, note that this could be more specific, ie. just row or all it the columns have changed //fireTableDataChanged(); sortTableRows(columnNamesTemp, dataTemp); columnNames = columnNamesTemp; cellColour = setCellColours(dataTemp); Object[][] prevousData = data; data = dataTemp; if (previousColumnCount != getColumnCount() || prevousData.length != data.length) { try { fireTableStructureChanged(); } catch (Exception ex) { GuiHelper.linorgBugCatcher.logError(ex); } } else { for (int rowCounter = 0; rowCounter < getRowCount(); rowCounter++) { for (int colCounter = 0; colCounter < getColumnCount(); colCounter++) { // if (prevousData[rowCounter][colCounter] != data[rowCounter][colCounter]) { // System.out.println("fireTableCellUpdated: " + rowCounter + ":" + colCounter); fireTableCellUpdated(rowCounter, colCounter); } } } updateImageDisplayPanel(); // update the image panel now the rows have been sorted and the data array updated } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } @Override public String getColumnName(int col) { if (col < columnNames.length) { return columnNames[col]; } else { return ""; } } public Object getValueAt(int row, int col) { try { return data[row][col]; } catch (Exception e) { return null; } } // public boolean hasValueChanged(int row, int col) { // if (row > -1 && col > -1) { // if (data[row][col] instanceof ImdiField) { // return ((ImdiField) data[row][col]).fieldNeedsSaveToDisk; // if (data[row][col] instanceof ImdiField[]) { // boolean needsSave = false; // ImdiField[] fieldArray = (ImdiField[]) data[row][col]; // for (ImdiField fieldElement : fieldArray) { // System.out.println("hasValueChanged: " + fieldElement); // if (fieldElement.fieldNeedsSaveToDisk) { // needsSave = true; // return needsSave; // return false; public Color getCellColour(int row, int col) { try { return cellColour[row][col]; } catch (Exception e) { return new Color(0xFFFFFF); } } @Override // JTable uses this method to determine the default renderer public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } // @Override // public void setValueAt(Object value, int row, int col) { // error here maybe return without doing anything // System.out.println("setValueAt: " + value.toString() + " : " + row + " : " + col); //// if (data[row][col] instanceof ImdiField) { //// // multiple field colums will not be edited here or saved here //// ImdiField currentField = ((ImdiField) data[row][col]); //// currentField.setFieldValue(value.toString(), true); //// fireTableCellUpdated(row, col); //// } else if (data[row][col] instanceof Object[]) { //// System.out.println("cell is a child list so do not edit"); //// } else { //// // TODO: is this even valid, presumably this will be a string and therefore not saveable to the imdi ////// data[row][col] = value; ////// fireTableCellUpdated(row, col); //// fireTableCellUpdated(row, col); public void sortByColumn(int columnIndex) { // TODO: sort columns // System.out.println("sortByColumn: " + columnIndex); // set the reverse sort flag if (sortColumn == columnIndex) { if (horizontalView || sortReverse == false) { sortReverse = !sortReverse; } else { // set the sort by the imdi field order sortColumn = -1; } } else { //set the current sort column sortColumn = columnIndex; sortReverse = false; } System.out.println("sortByColumn: " + sortColumn); //fireTableStructureChanged(); requestReloadTableData(); } public void hideColumn(int columnIndex) { System.out.println("hideColumn: " + columnIndex); // TODO: hide column System.out.println("hideColumn: " + getColumnName(columnIndex)); if (!childColumnNames.remove(getColumnName(columnIndex))) { tableFieldView.addHiddenColumn(getColumnName(columnIndex)); } requestReloadTableData(); } public void showOnlyCurrentColumns() { tableFieldView.setShowOnlyColumns(columnNames); } public LinorgFieldView getFieldView() { return tableFieldView; } public void addChildTypeToDisplay(String childType) { System.out.println("addChildTypeToDisplay: " + childType); childColumnNames.add(childType); requestReloadTableData(); } public Object[] getChildNames() { Vector childNames = new Vector(); Enumeration imdiRowsEnum = imdiObjectHash.elements(); while (imdiRowsEnum.hasMoreElements()) { // Enumeration childEnum = .getChildEnum(); for (ImdiTreeObject currentChild : ((ImdiTreeObject) imdiRowsEnum.nextElement()).getChildArray()) { // TODO: maybe check the children for children before adding them to this list String currentChildName = currentChild.toString(); if (!childNames.contains(currentChildName)) { childNames.add(currentChildName); } } } return childNames.toArray(); } public void copyCellToColumn(int row, int col) { // if the col or row provided here is invalid then we want to know about it so don't try to prevent such an error // if (row == -1 || col == -1) { // return; System.out.println("copyCellToColumn for row: " + row + " col: " + col); for (int rowCounter = 0; rowCounter < getRowCount(); rowCounter++) { if (rowCounter != row) { // TODO: a user may want to copy fields with multiple values to the whole column eg descritions in multiple languages if (data[rowCounter][col] instanceof ImdiField) { ((ImdiField) data[rowCounter][col]).setFieldValue(((ImdiField) data[row][col]).getFieldValue(), false, false); } fireTableCellUpdated(rowCounter, col); } } } public void highlightMatchingText(String highlightText) { highlightCells.add(highlightText); cellColour = setCellColours(data); fireTableDataChanged(); } public void highlightMatchingCells(int row, int col) { highlightCells.add(new ImdiTableCellRenderer(data[row][col]).getText()); cellColour = setCellColours(data); fireTableDataChanged(); } public Vector getMatchingRows(int sampleRowNumber) { System.out.println("MatchingRows for: " + sampleRowNumber); Vector matchedRows = new Vector(); if (sampleRowNumber > -1 && sampleRowNumber < getRowCount()) { for (int rowCounter = 0; rowCounter < getRowCount(); rowCounter++) { boolean rowMatches = true; for (int colCounter = 0; colCounter < getColumnCount(); colCounter++) { if (!getValueAt(rowCounter, colCounter).toString().equals(getValueAt(sampleRowNumber, colCounter).toString())) { rowMatches = false; break; } } //System.out.println("Checking: " + getValueAt(sampleRowNumber, 0) + " : " + getValueAt(rowCounter, 0)); if (rowMatches) { //System.out.println("Matched: " + rowCounter + " : " + getValueAt(rowCounter, 0)); matchedRows.add(rowCounter); } } } return matchedRows; } }
package scalac.symtab.classfile; import ch.epfl.lamp.util.Position; import scalac.*; import scalac.util.*; import scalac.symtab.*; import java.io.*; import java.util.*; //todo: don't keep statics module in scope. public class ClassfileParser implements ClassfileConstants { static final int CLASS_ATTR = SOURCEFILE_ATTR | INNERCLASSES_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR | SCALA_ATTR | JACO_ATTR | SIG_ATTR; static final int METH_ATTR = CODE_ATTR | EXCEPTIONS_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR | SIG_ATTR | BRIDGE_ATTR; static final int FIELD_ATTR = CONSTANT_VALUE_ATTR | SYNTHETIC_ATTR | DEPRECATED_ATTR | META_ATTR | SIG_ATTR; protected Global global; protected AbstractFileReader in; protected Symbol c; protected Type ctype; protected Scope locals; protected Scope statics; protected JavaTypeFactory make; protected Signatures sigs; protected ConstantPool pool; protected AttributeParser attrib; public ClassfileParser(Global global, AbstractFileReader in, Symbol c) { this.global = global; this.in = in; this.c = c; this.ctype = c.typeConstructor(); this.make = new JavaTypeCreator(global.definitions); this.sigs = new Signatures(global, make); this.pool = new ConstantPool(in, sigs); this.attrib = new AttributeParser(in, pool, this); } /** parse the classfile and throw IO exception if there is an * error in the classfile structure */ public void parse() throws IOException { try { if (in.nextInt() != JAVA_MAGIC) throw new IOException("illegal start of class file"); int minorVersion = in.nextChar(); int majorVersion = in.nextChar(); if ((majorVersion < JAVA_MAJOR_VERSION) || ((majorVersion == JAVA_MAJOR_VERSION) && (minorVersion < JAVA_MINOR_VERSION))) throw new IOException("class file has wrong version " + majorVersion + "." + minorVersion + ", should be " + JAVA_MAJOR_VERSION + "." + JAVA_MINOR_VERSION); pool.indexPool(); int flags = in.nextChar(); Name name = readClassName(in.nextChar()); if (c.fullName() != name) throw new IOException("class file '" + c.fullName() + "' contains wrong class " + name); // todo: correct flag transition c.flags = transFlags(flags); if ((c.flags & Modifiers.DEFERRED) != 0) c.flags = c.flags & ~Modifiers.DEFERRED | Modifiers.ABSTRACT; Type supertpe = readClassType(in.nextChar()); Type[] basetpes = new Type[in.nextChar() + 1]; this.locals = new Scope(); this.statics = new Scope(); // set type of class Type classType = Type.compoundType(basetpes, locals, c); c.setFirstInfo(classType); // set type of statics Symbol staticsClass = c.module().moduleClass(); if (staticsClass.isModuleClass()) { Type staticsInfo = Type.compoundType(Type.EMPTY_ARRAY, statics, staticsClass); staticsClass.setFirstInfo(staticsInfo); c.module().setInfo(Type.typeRef(staticsClass.owner().thisType(), staticsClass, Type.EMPTY_ARRAY)); } basetpes[0] = supertpe; for (int i = 1; i < basetpes.length; i++) basetpes[i] = readClassType(in.nextChar()); int fieldCount = in.nextChar(); for (int i = 0; i < fieldCount; i++) parseField(); int methodCount = in.nextChar(); for (int i = 0; i < methodCount; i++) parseMethod(); Symbol constr = c.primaryConstructor(); if (!constr.isInitialized()) { constr.setFirstInfo( Type.MethodType(Symbol.EMPTY_ARRAY, ctype)); if ((c.flags & Modifiers.INTERFACE) == 0) constr.flags |= Modifiers.PRIVATE; } attrib.readAttributes(c, classType, CLASS_ATTR); //System.out.println("dynamic class: " + c); //System.out.println("statics class: " + staticsClass); //System.out.println("module: " + c.module()); //System.out.println("modules class: " + c.module().type().symbol()); } catch (RuntimeException e) { if (global.debug) e.printStackTrace(); String s = e.getMessage() == null ? "" : " (" +e.getMessage()+ ")"; throw new IOException("bad class file" + s); } } /** convert Java modifiers into Scala flags */ public int transFlags(int flags) { int res = 0; if (((flags & 0x0007) == 0) || ((flags & 0x0002) != 0)) res |= Modifiers.PRIVATE; else if ((flags & 0x0004) != 0) res |= Modifiers.PROTECTED; if ((flags & 0x0400) != 0) res |= Modifiers.DEFERRED; if ((flags & 0x0010) != 0) res |= Modifiers.FINAL; if ((flags & 0x0200) != 0) res |= Modifiers.INTERFACE | Modifiers.TRAIT | Modifiers.ABSTRACT; if ((flags & 0x1000) != 0) res |= Modifiers.SYNTHETIC; return res | Modifiers.JAVA; } /** read a class name */ protected Name readClassName(int i) { return (Name)pool.readPool(i); } /** read a class name and return the corresponding class type */ protected Type readClassType(int i) { if (i == 0) return make.anyType(); Type res = make.classType((Name)pool.readPool(i)); if (res == Type.ErrorType) global.error("unknown class reference " + pool.readPool(i)); return res; } /** read a signature and return it as a type */ protected Type readType(int i) { Name sig = pool.readExternal(i); return sigs.sigToType(Name.names, sig.index, sig.length()); } /** read a field */ protected void parseField() { int flags = in.nextChar(); Name name = (Name)pool.readPool(in.nextChar()); Type type = readType(in.nextChar()); int mods = transFlags(flags); if ((flags & 0x0010) == 0) mods |= Modifiers.MUTABLE; Symbol owner = c; if ((flags & 0x0008) != 0) owner = c.module().moduleClass(); Symbol s = new TermSymbol(Position.NOPOS, name, owner, mods); s.setFirstInfo(type); attrib.readAttributes(s, type, FIELD_ATTR); ((flags & 0x0008) != 0 ? statics : locals).enterOrOverload(s); } /** read a method */ protected void parseMethod() { int flags = in.nextChar(); int sflags = transFlags(flags); if ((flags & 0x0040) != 0) sflags |= Modifiers.BRIDGE; Name name = (Name)pool.readPool(in.nextChar()); Type type = readType(in.nextChar()); if (CONSTR_N.equals(name)) { Symbol s = TermSymbol.newConstructor(c, transFlags(flags)); // kick out package visible or private constructors if (((flags & 0x0002) != 0) || ((flags & 0x0007) == 0)) { attrib.readAttributes(s, type, METH_ATTR); return; } switch (type) { case MethodType(Symbol[] vparams, _): type = Type.MethodType(vparams, ctype); break; default: throw new ApplicationError(); } Symbol constr = c.primaryConstructor(); if (constr.isInitialized()) constr = c.addConstructor(); s.copyTo(constr); setParamOwners(type, constr); constr.setFirstInfo(type); attrib.readAttributes(constr, type, METH_ATTR); //System.out.println(c + " " + c.allConstructors() + ":" + c.allConstructors().info());//debug //System.out.println("-- enter " + s); } else { Symbol s = new TermSymbol( Position.NOPOS, name, ((flags & 0x0008) != 0) ? c.module().moduleClass() : c, transFlags(flags)); setParamOwners(type, s); s.setFirstInfo(type); attrib.readAttributes(s, type, METH_ATTR); if ((s.flags & Modifiers.BRIDGE) == 0) ((flags & 0x0008) != 0 ? statics : locals).enterOrOverload(s); } } private void setParamOwners(Type type, Symbol owner) { switch (type) { case PolyType(Symbol[] params, Type result): for (int i = 0; i < params.length; i++) params[i].setOwner(owner); setParamOwners(result, owner); break; case MethodType(Symbol[] params, Type result): for (int i = 0; i < params.length; i++) params[i].setOwner(owner); setParamOwners(result, owner); break; } } }
import java.io.File; import java.io.IOException; import java.io.PrintWriter; public class MainBatchTester { private enum TestType { /** * Cycle Cancelling */ CC, /** * Sucessive Shortest Paths */ SSP, /** * Sucessive Shortest Paths, com Capacity Scalling */ SSP_CS } public static void main(String[] args) throws IOException, InterruptedException { File netDirs = new File("netg"); // arquivo final int numOfExecutions = 2; File reportFile = new File("report.csv"); PrintWriter reportWriter = new PrintWriter(reportFile); try { for (File file : netDirs.listFiles()) { if (!file.getName().endsWith(".net")) continue; runTestsWith(file, reportWriter, numOfExecutions); } } finally { reportWriter.close(); } } private static void runTestsWith(File file, PrintWriter report, int numOfExecutions) throws IOException, InterruptedException { for (TestType type : TestType.values()) { for (int execution = 0; execution < numOfExecutions; execution += 1) { if (!runOneTest(file, report, type, execution)) break; } } } @SuppressWarnings("deprecation") private static boolean runOneTest(File file, final PrintWriter report, final TestType type, int executionIdx) throws IOException, InterruptedException { String instanceName = file.getName().substring(0, file.getName().length() - 4); long timer; System.out.println("\n\n" + instanceName + " com " + type + " - teste + executionIdx); System.out.println(" // Carregar arquivo final Network net = new Network(); System.out.print("* Carregando " + file.getAbsolutePath() + "..."); timer = System.currentTimeMillis(); net.loadFromFile(file); System.out.println("ok em " + (System.currentTimeMillis() - timer) + "ms."); final Response result[] = new Response[1]; final long[] time = new long[1]; System.out.println("* Chamando algoritmo de " + type + "..."); Thread runThread = new Thread() { @Override public void run() { time[0] = System.currentTimeMillis(); switch (type) { case CC: result[0] = net.cycleCanceling(); break; case SSP: result[0] = net.sucessiveShortestPath(); break; case SSP_CS: result[0] = net.capacityScaling(); break; default: throw new IllegalStateException(); } time[0] = System.currentTimeMillis() - time[0]; } }; runThread.setPriority(Thread.MAX_PRIORITY); runThread.setDaemon(true); runThread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println("* !! Thread interrompida por exceção: "+e.getClass().getName()+" - "+e.getMessage()); } }); final long timeout = 1000l * 60l * 5l; //final long timeout = 5000l; runThread.start(); runThread.join(timeout); boolean methodResult = !runThread.isAlive(); if (runThread.isAlive()) { runThread.interrupt(); runThread.join(5000); if (runThread.isAlive()) runThread.stop(new RuntimeException("Tempo limite excedido!")); } if (!methodResult || result[0]==null) { time[0] = 0; result[0] = new Response(0); } String reportLine = instanceName + "," + type + "," + result[0].isFeasibleSolution() + "," + (executionIdx + 1) + "," + result[0].getCostFlow() + "," + time[0]; System.out.println("* Linha CSV para relatório: " + reportLine); report.println(reportLine); System.out .print("* Rodando Garbage Collector para evitar interferências no tempo..."); Runtime.getRuntime().gc(); System.out.println("Ok!"); return methodResult; } }
package ru.elazarev; /** * Class for create user interface. * @author Eugene Lazarev mailto(helycopternicht@rambler.ru) * @since 09.04.17 */ public class StartUI { /** * Field to get program input. */ private Input input; /** * Tracker storage/ Simple database. */ private Tracker tracker; /** * Default constructor. * @param input - Input interface implementation. */ public StartUI(Input input) { this.input = input; this.tracker = new Tracker(); } /** * Method to start user interface. */ public void init() { printGreeting(); while (true) { printMenu(); String answer = input.ask("Select:"); if ("6".equals(answer)) { System.out.println("Exit..."); break; } switch (answer) { case "0": addNewItem(); break; case "1": printAllItems(); break; case "2": editItem(); break; case "3": deleteItem(); break; case "4": findItemById(); break; case "5": findItemByName(); break; default: System.out.println("Incorrect input, repeat please"); } } } /** * Method finds item by name in tracker storage and prints it if exist. */ private void findItemByName() { System.out.println(" System.out.println("Finding item by NAME."); TrackerItem item = this.findByName(); if (item == null) { System.out.println("Item with same name is not found"); } else { processFounded(item); } System.out.println(" } /** * Method finds item by ID in tracker storage and prints it if exist. */ private void findItemById() { System.out.println(" System.out.println("Finding item by ID."); TrackerItem item = this.findById(); if (item == null) { System.out.println("Item with same id not found"); } else { processFounded(item); } System.out.println(" } /** * Method encapsulates search by id. * @return founded item or null */ private TrackerItem findById() { String id = this.input.ask("Enter item's id:"); return tracker.findById(id); } /** * Method encapsulates search by name. * @return - founded item or null */ private TrackerItem findByName() { String id = this.input.ask("Enter item's name:"); return tracker.findByName(id); } /** * Render process item menu. * @param item - item to process */ private void processFounded(TrackerItem item) { while (true) { System.out.println("Founded item :" + item); System.out.println("1. Edit fields"); System.out.println("2. Add comment"); System.out.println("3. Exit to main menu"); String answer = this.input.ask("Select:"); if (answer.equals("3")) { break; } switch (answer) { case "1": editItem(item); break; case "2": addComment(item); break; default: System.out.println("Incorrect input"); } } } /** * Method finds item by ID in tracker storage and delete it if exist. */ private void deleteItem() { System.out.println(" System.out.println("Deleting item."); TrackerItem item = this.findById(); if (item == null) { System.out.println("Item with same id not found"); } else { tracker.delete(item); System.out.println("Deleted"); } System.out.println(" } /** * Method finds item by ID in tracker storage and edit it if exist. */ private void editItem() { System.out.println(" System.out.println("Editing item."); TrackerItem item = this.findById(); if (item == null) { System.out.println("Item with same id not found"); } else { editItem(item); } System.out.println(" } /** * Mathod adds comment to tracker item. * @param item - item to add comment */ private void addComment(TrackerItem item) { String msg = this.input.ask("Write comment:"); if ("".equals(msg)) { return; } item.addComment(msg); System.out.println("Comment added..."); } /** * Encapsulates edit logic. * @param item - tracking item to edit */ private void editItem(TrackerItem item) { String newName = this.input.ask("Name is " + item.getName() + ". Enter new name:"); String newDesc = this.input.ask("Description is " + item.getDescription() + "Enter new description:"); if ("".equals(newName)) { newName = item.getName(); } if ("".equals(newDesc)) { newDesc = item.getDescription(); } this.tracker.update(new TrackerItem(item.getId(), newName, newDesc, item.getCreatedAt(), item.getComments())); System.out.println("Edited"); } /** * Method adding new item in tracker storage. */ private void addNewItem() { System.out.println(" System.out.println("Adding new item."); String name = this.input.ask("Enter name:"); String id = this.input.ask("Enter id:"); String desc = this.input.ask("Enter description:"); this.tracker.add(new TrackerItem(id, name, desc)); System.out.println("New item added."); System.out.println(" } /** * Method prints all items in tracker storage. */ private void printAllItems() { System.out.println(" System.out.println("All items:"); for (TrackerItem item : this.tracker.findAll()) { System.out.println(item); } System.out.println(" } /** * Method prints menu to make selection. */ private void printMenu() { System.out.println("0. Add new Item"); System.out.println("1. Show all items"); System.out.println("2. Edit item"); System.out.println("3. Delete item"); System.out.println("4. Find item by Id"); System.out.println("5. Find items by name"); System.out.println("6. Exit Program"); } /** * Method prints greeting to user. */ private void printGreeting() { System.out.println("/ System.out.println("This program is tracker for any tasks. It can add, edit, delete, comment and find tasks."); System.out.println("To start work, Select one of the menu items. For example '1' to see all tasks in tracker"); System.out.println("or '6' to exit from program."); System.out.println(""); } /** * Getter for tracker field. Used in testing classes. * @return tracker storage. */ public Tracker getTracker() { return tracker; } /** * The main method to start app. * @param args - not used */ public static void main(String[] args) { new StartUI(new ConsoleInput()).init(); } }
package ru.job4j.iterator; import java.util.Iterator; import java.util.NoSuchElementException; public class Converter{ class IterateInteger { private Iterator<Integer> integerIterator; } private Iterator<Integer> iteratorInt = new IterateInteger().integerIterator; Iterator<Integer> convert(Iterator<Iterator<Integer>> it) { return new Iterator<Integer>() { @Override public boolean hasNext() { selectIterator(); if (iteratorInt == null) { return false; } if (iteratorInt.hasNext()) { return true; } if (it.hasNext()) { iteratorInt = it.next(); } return iteratorInt.hasNext(); } @Override public Integer next() { selectIterator(); if (iteratorInt == null) { throw new NoSuchElementException(); } if (!iteratorInt.hasNext() && it.hasNext()) { iteratorInt = it.next(); } return iteratorInt.next(); } private void selectIterator() { if (iteratorInt == null && it.hasNext()) { iteratorInt = it.next(); } } }; } }
package com.jme3.water; import com.jme3.asset.AssetManager; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.FastMath; import com.jme3.math.Plane; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.post.SceneProcessor; import com.jme3.renderer.Camera; import com.jme3.renderer.RenderManager; import com.jme3.renderer.Renderer; import com.jme3.renderer.ViewPort; import com.jme3.renderer.queue.RenderQueue; import com.jme3.scene.Geometry; import com.jme3.scene.Spatial; import com.jme3.scene.shape.Quad; import com.jme3.texture.FrameBuffer; import com.jme3.texture.Image.Format; import com.jme3.texture.Texture.WrapMode; import com.jme3.texture.Texture2D; import com.jme3.ui.Picture; import com.jme3.util.TempVars; /** * * @author normenhansen */ public class SimpleWaterProcessor implements SceneProcessor { protected RenderManager rm; protected ViewPort vp; protected Spatial reflectionScene; protected ViewPort reflectionView; protected ViewPort refractionView; protected FrameBuffer reflectionBuffer; protected FrameBuffer refractionBuffer; protected Camera reflectionCam; protected Camera refractionCam; protected Texture2D reflectionTexture; protected Texture2D refractionTexture; protected Texture2D depthTexture; protected Texture2D normalTexture; protected Texture2D dudvTexture; protected int renderWidth = 512; protected int renderHeight = 512; protected Plane plane = new Plane(Vector3f.UNIT_Y, Vector3f.ZERO.dot(Vector3f.UNIT_Y)); protected float speed = 0.05f; protected Ray ray = new Ray(); protected Vector3f targetLocation = new Vector3f(); protected AssetManager manager; protected Material material; protected float waterDepth = 1; protected float waterTransparency = 0.4f; protected boolean debug = false; private Picture dispRefraction; private Picture dispReflection; private Picture dispDepth; private Plane reflectionClipPlane; private Plane refractionClipPlane; private float refractionClippingOffset = 0.3f; private float reflectionClippingOffset = -5f; public SimpleWaterProcessor(AssetManager manager) { this.manager = manager; material = new Material(manager, "Common/MatDefs/Water/SimpleWater.j3md"); material.setFloat("waterDepth", waterDepth); material.setFloat("waterTransparency", waterTransparency / 10); material.setColor("waterColor", ColorRGBA.White); material.setVector3("lightPos", new Vector3f(1, -1, 1)); material.setColor("distortionScale", new ColorRGBA(0.2f, 0.2f, 0.2f, 0.2f)); material.setColor("distortionMix", new ColorRGBA(0.5f, 0.5f, 0.5f, 0.5f)); material.setColor("texScale", new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); updateClipPlanes(); } public void initialize(RenderManager rm, ViewPort vp) { this.rm = rm; this.vp = vp; loadTextures(manager); createTextures(); applyTextures(material); createPreViews(); material.setVector2("FrustumNearFar", new Vector2f(vp.getCamera().getFrustumNear(), vp.getCamera().getFrustumFar())); if (debug) { dispRefraction = new Picture("dispRefraction"); dispRefraction.setTexture(manager, refractionTexture, false); dispReflection = new Picture("dispRefraction"); dispReflection.setTexture(manager, reflectionTexture, false); dispDepth = new Picture("depthTexture"); dispDepth.setTexture(manager, depthTexture, false); } } public void reshape(ViewPort vp, int w, int h) { } public boolean isInitialized() { return rm != null; } float time = 0; public void preFrame(float tpf) { time = time + (tpf * speed); if (time > 1f) { time = 0; } material.setFloat("time", time); } public void postQueue(RenderQueue rq) { Camera sceneCam = rm.getCurrentCamera(); //update ray ray.setOrigin(sceneCam.getLocation()); ray.setDirection(sceneCam.getDirection()); //update refraction cam refractionCam.setLocation(sceneCam.getLocation()); refractionCam.setRotation(sceneCam.getRotation()); refractionCam.setFrustum(sceneCam.getFrustumNear(), sceneCam.getFrustumFar(), sceneCam.getFrustumLeft(), sceneCam.getFrustumRight(), sceneCam.getFrustumTop(), sceneCam.getFrustumBottom()); //update reflection cam boolean inv = false; if (!ray.intersectsWherePlane(plane, targetLocation)) { ray.setDirection(ray.getDirection().negateLocal()); ray.intersectsWherePlane(plane, targetLocation); inv = true; } Vector3f loc = plane.reflect(sceneCam.getLocation(), new Vector3f()); reflectionCam.setLocation(loc); reflectionCam.setFrustum(sceneCam.getFrustumNear(), sceneCam.getFrustumFar(), sceneCam.getFrustumLeft(), sceneCam.getFrustumRight(), sceneCam.getFrustumTop(), sceneCam.getFrustumBottom()); TempVars vars=TempVars.get(); vars.lock(); // tempVec and calcVect are just temporary vector3f objects vars.vect1.set( sceneCam.getLocation() ).addLocal( sceneCam.getUp() ); float planeDistance = plane.pseudoDistance( vars.vect1 ); vars.vect2.set(plane.getNormal()).multLocal( planeDistance * 2.0f ); vars.vect3.set( vars.vect1.subtractLocal( vars.vect2 ) ).subtractLocal( loc ).normalizeLocal().negateLocal(); // now set the up vector reflectionCam.lookAt(targetLocation, vars.vect3); vars.unlock(); if (inv) { reflectionCam.setAxes(reflectionCam.getLeft().negateLocal(), reflectionCam.getUp(), reflectionCam.getDirection().negateLocal()); } } public void postFrame(FrameBuffer out) { if (debug) { displayMap(rm.getRenderer(), dispRefraction, 64); displayMap(rm.getRenderer(), dispReflection, 256); displayMap(rm.getRenderer(), dispDepth, 448); } } public void cleanup() { } //debug only : displays maps protected void displayMap(Renderer r, Picture pic, int left) { Camera cam = vp.getCamera(); rm.setCamera(cam, true); int h = cam.getHeight(); pic.setPosition(left, h / 20f); pic.setWidth(128); pic.setHeight(128); pic.updateGeometricState(); rm.renderGeometry(pic); rm.setCamera(cam, false); } protected void loadTextures(AssetManager manager) { normalTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/gradient_map.jpg"); dudvTexture = (Texture2D) manager.loadTexture("Common/MatDefs/Water/Textures/dudv_map.jpg"); normalTexture.setWrap(WrapMode.Repeat); dudvTexture.setWrap(WrapMode.Repeat); } protected void createTextures() { reflectionTexture = new Texture2D(renderWidth, renderHeight, Format.RGBA8); refractionTexture = new Texture2D(renderWidth, renderHeight, Format.RGBA8); depthTexture = new Texture2D(renderWidth, renderHeight, Format.Depth); } protected void applyTextures(Material mat) { mat.setTexture("water_reflection", reflectionTexture); mat.setTexture("water_refraction", refractionTexture); mat.setTexture("water_depthmap", depthTexture); mat.setTexture("water_normalmap", normalTexture); mat.setTexture("water_dudvmap", dudvTexture); } protected void createPreViews() { reflectionCam = new Camera(renderWidth, renderHeight); refractionCam = new Camera(renderWidth, renderHeight); // create a pre-view. a view that is rendered before the main view reflectionView = rm.createPreView("Reflection View", reflectionCam); reflectionView.setClearEnabled(true); reflectionView.setBackgroundColor(ColorRGBA.Black); // create offscreen framebuffer reflectionBuffer = new FrameBuffer(renderWidth, renderHeight, 1); //setup framebuffer to use texture reflectionBuffer.setDepthBuffer(Format.Depth); reflectionBuffer.setColorTexture(reflectionTexture); //set viewport to render to offscreen framebuffer reflectionView.setOutputFrameBuffer(reflectionBuffer); reflectionView.addProcessor(new ReflectionProcessor(reflectionCam, reflectionBuffer, reflectionClipPlane)); // attach the scene to the viewport to be rendered reflectionView.attachScene(reflectionScene); // create a pre-view. a view that is rendered before the main view refractionView = rm.createPreView("Refraction View", refractionCam); refractionView.setClearEnabled(true); refractionView.setBackgroundColor(ColorRGBA.Black); // create offscreen framebuffer refractionBuffer = new FrameBuffer(renderWidth, renderHeight, 1); //setup framebuffer to use texture refractionBuffer.setDepthBuffer(Format.Depth); refractionBuffer.setColorTexture(refractionTexture); refractionBuffer.setDepthTexture(depthTexture); //set viewport to render to offscreen framebuffer refractionView.setOutputFrameBuffer(refractionBuffer); refractionView.addProcessor(new RefractionProcessor()); // attach the scene to the viewport to be rendered refractionView.attachScene(reflectionScene); } protected void destroyViews() { // rm.removePreView(reflectionView); rm.removePreView(refractionView); } /** * Get the water material from this processor, apply this to your water quad. * @return */ public Material getMaterial() { return material; } /** * Sets the reflected scene, should not include the water quad! * Set before adding processor. * @param spat */ public void setReflectionScene(Spatial spat) { reflectionScene = spat; } public int getRenderWidth() { return renderWidth; } public int getRenderHeight() { return renderHeight; } /** * Set the reflection Texture render size, * set before adding the processor! * @param with * @param height */ public void setRenderSize(int width, int height) { renderWidth = width; renderHeight = height; } public Plane getPlane() { return plane; } /** * Set the water plane for this processor. * @param plane */ public void setPlane(Plane plane) { this.plane.setConstant(plane.getConstant()); this.plane.setNormal(plane.getNormal()); updateClipPlanes(); } /** * Set the water plane using an origin (location) and a normal (reflection direction). * @param origin Set to 0,-6,0 if your water quad is at that location for correct reflection * @param normal Set to 0,1,0 (Vector3f.UNIT_Y) for normal planar water */ public void setPlane(Vector3f origin, Vector3f normal) { this.plane.setOriginNormal(origin, normal); updateClipPlanes(); } private void updateClipPlanes() { reflectionClipPlane = plane.clone(); reflectionClipPlane.setConstant(reflectionClipPlane.getConstant() + reflectionClippingOffset); refractionClipPlane = plane.clone(); refractionClipPlane.setConstant(refractionClipPlane.getConstant() + refractionClippingOffset); } /** * Set the light Position for the processor * @param position */ //TODO maybe we should provide a convenient method to compute position from direction public void setLightPosition(Vector3f position) { material.setVector3("lightPos", position); } /** * Set the color that will be added to the refraction texture. * @param color */ public void setWaterColor(ColorRGBA color) { material.setColor("waterColor", color); } /** * Higher values make the refraction texture shine through earlier. * Default is 4 * @param depth */ public void setWaterDepth(float depth) { waterDepth = depth; material.setFloat("waterDepth", depth); } public float getWaterDepth() { return waterDepth; } public float getWaterTransparency() { return waterTransparency; } public void setWaterTransparency(float waterTransparency) { this.waterTransparency = Math.max(0, waterTransparency); material.setFloat("waterTransparency", waterTransparency / 10); } /** * Sets the speed of the wave animation, default = 0.05f. * @param speed */ public void setWaveSpeed(float speed) { this.speed = speed; } /** * Sets the scale of distortion by the normal map, default = 0.2 */ public void setDistortionScale(float value) { material.setColor("distortionScale", new ColorRGBA(value, value, value, value)); } /** * Sets how the normal and dudv map are mixed to create the wave effect, default = 0.5 */ public void setDistortionMix(float value) { material.setColor("distortionMix", new ColorRGBA(value, value, value, value)); } /** * Sets the scale of the normal/dudv texture, default = 1. * Note that the waves should be scaled by the texture coordinates of the quad to avoid animation artifacts, * use mesh.scaleTextureCoordinates(Vector2f) for that. */ public void setTexScale(float value) { material.setColor("texScale", new ColorRGBA(value, value, value, value)); } public boolean isDebug() { return debug; } public void setDebug(boolean debug) { this.debug = debug; } /** * Creates a quad with the water material applied to it. * @param width * @param height * @return */ public Geometry createWaterGeometry(float width, float height) { Quad quad = new Quad(width, height); Geometry geom = new Geometry("WaterGeometry", quad); geom.setLocalRotation(new Quaternion().fromAngleAxis(-FastMath.HALF_PI, Vector3f.UNIT_X)); geom.setMaterial(material); return geom; } /** * returns the reflection clipping plane offset * @return */ public float getReflectionClippingOffset() { return reflectionClippingOffset; } /** * sets the reflection clipping plane offset * set a nagetive value to lower the clipping plane for relection texture rendering. * @param reflectionClippingOffset */ public void setReflectionClippingOffset(float reflectionClippingOffset) { this.reflectionClippingOffset = reflectionClippingOffset; updateClipPlanes(); } /** * returns the refraction clipping plane offset * @return */ public float getRefractionClippingOffset() { return refractionClippingOffset; } /** * Sets the refraction clipping plane offset * set a positive value to raise the clipping plane for refraction texture rendering * @param refractionClippingOffset */ public void setRefractionClippingOffset(float refractionClippingOffset) { this.refractionClippingOffset = refractionClippingOffset; updateClipPlanes(); } /** * Refraction Processor */ public class RefractionProcessor implements SceneProcessor { RenderManager rm; ViewPort vp; public void initialize(RenderManager rm, ViewPort vp) { this.rm = rm; this.vp = vp; } public void reshape(ViewPort vp, int w, int h) { } public boolean isInitialized() { return rm != null; } public void preFrame(float tpf) { refractionCam.setClipPlane(refractionClipPlane, Plane.Side.Negative); } public void postQueue(RenderQueue rq) { } public void postFrame(FrameBuffer out) { } public void cleanup() { } } }
package com.malhartech.dag; import com.malhartech.annotation.NodeAnnotation; import com.malhartech.annotation.PortAnnotation; import com.malhartech.util.CircularBuffer; import java.nio.BufferOverflowException; import java.util.HashMap; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Chetan Narsude <chetan@malhar-inc.com> */ public abstract class AbstractInputNode implements Node, Runnable { private static final Logger logger = LoggerFactory.getLogger(AbstractInputNode.class); private transient String id; private transient HashMap<String, CircularBuffer<Object>> afterBeginWindows; private transient HashMap<String, CircularBuffer<Tuple>> afterEndWindows; private transient HashMap<String, Sink> outputs = new HashMap<String, Sink>(); @SuppressWarnings("VolatileArrayField") private transient volatile Sink[] sinks = NO_SINKS; private transient NodeContext ctx; private transient volatile int producedTupleCount; private transient volatile int spinMillis = 10; private transient volatile int bufferCapacity = 1024 * 1024; public AbstractInputNode() { afterBeginWindows = new HashMap<String, CircularBuffer<Object>>(); afterEndWindows = new HashMap<String, CircularBuffer<Tuple>>(); Class<? extends Node> clazz = this.getClass(); NodeAnnotation na = clazz.getAnnotation(NodeAnnotation.class); if (na != null) { PortAnnotation[] ports = na.ports(); for (PortAnnotation pa: ports) { if (pa.type() == PortAnnotation.PortType.OUTPUT || pa.type() == PortAnnotation.PortType.BIDI) { afterBeginWindows.put(pa.name(), new CircularBuffer<Object>(bufferCapacity)); afterEndWindows.put(pa.name(), new CircularBuffer<Tuple>(bufferCapacity)); } } } } @Override @SuppressWarnings("SleepWhileInLoop") public final void activate(NodeContext context) { ctx = context; activateSinks(); run(); try { EndStreamTuple est = new EndStreamTuple(); for (CircularBuffer<Tuple> cb: afterEndWindows.values()) { while (true) { try { cb.add(est); break; } catch (BufferOverflowException boe) { Thread.sleep(spinMillis); } } } /* * make sure that it's sent. */ boolean pendingMessages; do { Thread.sleep(spinMillis); pendingMessages = false; for (CircularBuffer<Tuple> cb: afterEndWindows.values()) { if (cb.size() > 0) { pendingMessages = true; break; } } } while (pendingMessages); } catch (InterruptedException ex) { logger.info("Not waiting for the emitted tuples to be flushed as got interrupted by {}", ex.getLocalizedMessage()); } } @Override public final void deactivate() { sinks = NO_SINKS; outputs.clear(); } @Override public final Sink connect(String port, Sink component) { Sink retvalue; if (Component.INPUT.equals(port)) { retvalue = this; } else { if (component == null) { outputs.remove(port); } else { outputs.put(port, component); } if (sinks != NO_SINKS) { activateSinks(); } retvalue = null; } connected(port, component); return retvalue; } public void connected(String id, Sink dagpart) { /* implementation to be optionally overridden by the user */ } @Override @SuppressWarnings("SillyAssignment") public final void process(Object payload) { Tuple t = (Tuple)payload; switch (t.getType()) { case BEGIN_WINDOW: beginWindow(); for (int i = sinks.length; i sinks[i].process(payload); } for (Entry<String, CircularBuffer<Object>> e: afterBeginWindows.entrySet()) { final Sink s = outputs.get(e.getKey()); if (s != null) { CircularBuffer<?> cb = e.getValue(); for (int i = cb.size(); i s.process(cb.get()); } } } break; case END_WINDOW: for (Entry<String, CircularBuffer<Object>> e: afterBeginWindows.entrySet()) { final Sink s = outputs.get(e.getKey()); if (s != null) { CircularBuffer<?> cb = e.getValue(); for (int i = cb.size(); i s.process(cb.get()); } } } endWindow(); for (int i = sinks.length; i sinks[i].process(payload); } ctx.report(producedTupleCount, 0L, ((Tuple)payload).getWindowId()); producedTupleCount = 0; // the default is UNSPECIFIED which we ignore anyways as we ignore everything // that we do not understand! try { switch (ctx.getRequestType()) { case BACKUP: ctx.backup(this, ((Tuple)payload).getWindowId()); break; case RESTORE: logger.info("restore requests are not implemented"); break; } } catch (Exception e) { logger.warn("Exception while catering to external request", e.getLocalizedMessage()); } // i think there should be just one queue instead of one per port - lets defer till we find an example. for (Entry<String, CircularBuffer<Tuple>> e: afterEndWindows.entrySet()) { final Sink s = outputs.get(e.getKey()); if (s != null) { CircularBuffer<?> cb = e.getValue(); for (int i = cb.size(); i s.process(cb.get()); } } } break; default: for (int i = sinks.length; i sinks[i].process(payload); } } } @SuppressWarnings("SleepWhileInLoop") public void emit(String id, Object payload) { if (payload instanceof Tuple) { while (true) { try { afterEndWindows.get(id).add((Tuple)payload); break; } catch (BufferOverflowException ex) { try { Thread.sleep(spinMillis); } catch (InterruptedException ex1) { break; } } } } else { while (true) { try { afterBeginWindows.get(id).add(payload); break; } catch (BufferOverflowException ex) { try { Thread.sleep(spinMillis); } catch (InterruptedException ex1) { break; } } } } producedTupleCount++; } @Override public void setup(NodeConfiguration config) throws FailedOperationException { // TODO: // component should always have identity assigned // final setup method that cannot be bypassed by user code to perform required initialization id = config.get("Id"); } @Override public void beginWindow() { } @Override public void endWindow() { } @Override public void teardown() { } @Override public int hashCode() { return id == null ? super.hashCode() : id.hashCode(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AbstractInputNode other = (AbstractInputNode)obj; if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) { return false; } return true; } @Override public String toString() { return getClass().getSimpleName() + "{" + "id=" + id + ", outputs=" + outputs.keySet() + '}'; } @SuppressWarnings("SillyAssignment") private void activateSinks() { sinks = new Sink[outputs.size()]; int i = 0; for (Sink s: outputs.values()) { sinks[i++] = s; } sinks = sinks; } }
package com.atlassian.plugin.servlet; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.util.PluginUtils; import com.atlassian.plugin.elements.ResourceLocation; import com.atlassian.plugin.servlet.util.LastModifiedHandler; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This base class is used to provide the ability to server minified versions of files * if required and available. * * @since 2.2 */ abstract class AbstractDownloadableResource implements DownloadableResource { private static final Logger log = LoggerFactory.getLogger(AbstractDownloadableResource.class); /** * This is a the system environment variable to set to disable the minification naming strategy used to find web * resources. */ private static final String ATLASSIAN_WEBRESOURCE_DISABLE_MINIFICATION = "atlassian.webresource.disable.minification"; /* the following protected fields are marked final since 2.5 */ protected final Plugin plugin; protected final String extraPath; protected final ResourceLocation resourceLocation; // PLUG-538 cache this so we don't recreate the string every time it is called private final String location; private final boolean disableMinification; public AbstractDownloadableResource(final Plugin plugin, final ResourceLocation resourceLocation, final String extraPath) { this(plugin, resourceLocation, extraPath, false); } public AbstractDownloadableResource(final Plugin plugin, final ResourceLocation resourceLocation, String extraPath, final boolean disableMinification) { if ((extraPath != null) && !"".equals(extraPath.trim()) && !resourceLocation.getLocation().endsWith("/")) { extraPath = "/" + extraPath; } this.disableMinification = disableMinification; this.plugin = plugin; this.extraPath = extraPath; this.resourceLocation = resourceLocation; this.location = resourceLocation.getLocation() + extraPath; } public void serveResource(final HttpServletRequest request, final HttpServletResponse response) throws DownloadException { log.debug("Serving: " + this); final InputStream resourceStream = getResourceAsStreamViaMinificationStrategy(); if (resourceStream == null) { log.warn("Resource not found: " + this); return; } final String contentType = getContentType(); if (StringUtils.isNotBlank(contentType)) { response.setContentType(contentType); } OutputStream out; try { out = response.getOutputStream(); } catch (final IOException e) { throw new DownloadException(e); } streamResource(resourceStream, out); log.debug("Serving file done."); } public void streamResource(final OutputStream out) throws DownloadException { final InputStream resourceStream = getResourceAsStreamViaMinificationStrategy(); if (resourceStream == null) { log.warn("Resource not found: " + this); return; } streamResource(resourceStream, out); } /** * Copy from the supplied OutputStream to the supplied InputStream. Note that the InputStream will be closed on * completion. * * @param in the stream to read from * @param out the stream to write to * @throws DownloadException if an IOException is encountered writing to the out stream */ private void streamResource(final InputStream in, final OutputStream out) throws DownloadException { try { IOUtils.copy(in, out); } catch (final IOException e) { throw new DownloadException(e); } finally { IOUtils.closeQuietly(in); try { out.flush(); } catch (final IOException e) { log.debug("Error flushing output stream", e); } } } /** * Checks any "If-Modified-Since" header from the request against the plugin's loading time, since plugins can't * be modified after they've been loaded this is a good way to determine if a plugin resource has been modified * or not. * * If this method returns true, don't do any more processing on the request -- the response code has already been * set to "304 Not Modified" for you, and you don't need to serve the file. */ public boolean isResourceModified(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) { final Date resourceLastModifiedDate = (plugin.getDateLoaded() == null) ? new Date() : plugin.getDateLoaded(); final LastModifiedHandler lastModifiedHandler = new LastModifiedHandler(resourceLastModifiedDate); return lastModifiedHandler.checkRequest(httpServletRequest, httpServletResponse); } public String getContentType() { return resourceLocation.getContentType(); } /** * Returns an {@link InputStream} to stream the resource from based on resource name. * * @param resourceLocation the location of the resource to try and load * * @return an InputStream if the resource can be found or null if cant be found */ protected abstract InputStream getResourceAsStream(String resourceLocation); /** * This is called to return the location of the resource that this object represents. * * @return the location of the resource that this object represents. */ protected String getLocation() { return location; } @Override public String toString() { return "Resource: " + getLocation() + " (" + getContentType() + ")"; } /** * This is called to use a minification naming strategy to find resources. If a minified file cant by found then * the base location is ised as the fall back * * @return an InputStream r null if nothing can be found for the resource name */ private InputStream getResourceAsStreamViaMinificationStrategy() { InputStream inputStream = null; final String location = getLocation(); if (minificationStrategyInPlay(location)) { final String minifiedLocation = getMinifiedLocation(location); inputStream = getResourceAsStream(minifiedLocation); } if (inputStream == null) { inputStream = getResourceAsStream(location); } return inputStream; } /** * Returns true if the minification strategy should be applied to a given resource name * * @param resourceLocation the location of the resource * * @return true if the minification strategy should be used. */ private boolean minificationStrategyInPlay(final String resourceLocation) { // check if minification has been turned off for this resource (at the module level) if (disableMinification) { return false; } // secondly CHECK if we have a System property set to true that DISABLES the minification try { if (Boolean.getBoolean(ATLASSIAN_WEBRESOURCE_DISABLE_MINIFICATION) || Boolean.getBoolean(PluginUtils.ATLASSIAN_DEV_MODE)) { return false; } } catch (final SecurityException se) { // some app servers might have protected access to system properties. Unlikely but lets be defensive } // We only minify .js or .css files if (resourceLocation.endsWith(".js")) { // Check if it is already the minified vesrion of the file return !(resourceLocation.endsWith("-min.js") || resourceLocation.endsWith(".min.js")); } if (resourceLocation.endsWith(".css")) { // Check if it is already the minified vesrion of the file return !(resourceLocation.endsWith("-min.css") || resourceLocation.endsWith(".min.css")); } // Not .js or .css, don't bother trying to find a minified version (may save some file operations) return false; } private String getMinifiedLocation(final String location) { final int lastDot = location.lastIndexOf("."); // this can never but -1 since the method call is protected by a call to minificationStrategyInPlay() first return location.substring(0, lastDot) + "-min" + location.substring(lastDot); } }
package org.broad.igv.data; import com.google.java.contract.util.Objects; import org.broad.tribble.Feature; public class Interval implements Feature { protected String chr = null; protected int start = -1; protected int end = -1; public Interval(String chr, int start, int end){ this.chr = chr; this.start = start; this.end = end; } public String getChr() { return chr; } public int getStart() { return start; } public int getEnd() { return end; } /** * Determine whether this interval fully contains the specified * input interval. * * A negative input start position is special meaning. It is considered within the interval if the interval * contains position "0". * * @param chr * @param start * @param end * @return */ public boolean contains(String chr, int start, int end) { return Objects.equal(this.chr, chr) && this.start <= (start < 0 ? 0 : start) && this.end >= end; } /** * Determine whether there is any overlap between this interval and the specified interval * @param chr * @param start * @param end * @return */ public boolean overlaps(String chr, int start, int end) { return Objects.equal(this.chr, chr) && this.start <= end && this.end >= start; } }
package org.ovirt.engine.core.common.queries; public enum ConfigurationValues { MaxNumOfVmCpus(ConfigAuthType.User), MaxNumOfVmSockets(ConfigAuthType.User), MaxNumOfCpuPerSocket(ConfigAuthType.User), VdcVersion(ConfigAuthType.User), // GetAllAdDomains, SSLEnabled(ConfigAuthType.User), CipherSuite(ConfigAuthType.User), VmPoolLeaseDays(ConfigAuthType.User), VmPoolLeaseStartTime(ConfigAuthType.User), VmPoolLeaseEndTime(ConfigAuthType.User), MaxVmsInPool(ConfigAuthType.User), MaxVdsMemOverCommit(ConfigAuthType.User), MaxVdsMemOverCommitForServers(ConfigAuthType.User), AdUserName, // TODO remove remarks and AdUserPassword completely in version 3.1. // AdUserPassword field format has been changed. // AdUserPassword, ValidNumOfMonitors(ConfigAuthType.User), EnableUSBAsDefault(ConfigAuthType.User), SpiceSecureChannels(ConfigAuthType.User), ConsoleReleaseCursorKeys(ConfigAuthType.User), ConsoleToggleFullScreenKeys(ConfigAuthType.User), SpiceProxyDefault(ConfigAuthType.User), RemoteViewerSupportedVersions(ConfigAuthType.User), RemoteViewerNewerVersionUrl(ConfigAuthType.User), RemapCtrlAltDelDefault(ConfigAuthType.User), ClientModeSpiceDefault(ConfigAuthType.User), ClientModeVncDefault(ConfigAuthType.User), ClientModeRdpDefault(ConfigAuthType.User), UseFqdnForRdpIfAvailable(ConfigAuthType.User), WebSocketProxy(ConfigAuthType.User), WebSocketProxyTicketValiditySeconds(ConfigAuthType.User), HighUtilizationForEvenlyDistribute(ConfigAuthType.User), SpiceUsbAutoShare(ConfigAuthType.User), ImportDefaultPath, ComputerADPaths(ConfigAuthType.User), VdsSelectionAlgorithm, LowUtilizationForEvenlyDistribute, LowUtilizationForPowerSave, HighUtilizationForPowerSave, CpuOverCommitDurationMinutes, InstallVds, AsyncTaskPollingRate, FenceProxyDefaultPreferences, VcpuConsumptionPercentage(ConfigAuthType.User), SearchResultsLimit(ConfigAuthType.User), MaxBlockDiskSize(ConfigAuthType.User), EnableSpiceRootCertificateValidation(ConfigAuthType.User), VMMinMemorySizeInMB(ConfigAuthType.User), VM32BitMaxMemorySizeInMB(ConfigAuthType.User), VM64BitMaxMemorySizeInMB(ConfigAuthType.User), VmPriorityMaxValue(ConfigAuthType.User), WarningLowSpaceIndicator(ConfigAuthType.User), CriticalSpaceActionBlocker(ConfigAuthType.User), StorageDomainNameSizeLimit(ConfigAuthType.User), ImportDataStorageDomain, HostedEngineStorageDomainName, StoragePoolNameSizeLimit(ConfigAuthType.User), SANWipeAfterDelete(ConfigAuthType.User), AuthenticationMethod(ConfigAuthType.User), UserDefinedVMProperties(ConfigAuthType.User), PredefinedVMProperties(ConfigAuthType.User), VdsFenceOptionTypes, FenceAgentMapping, FenceAgentDefaultParams, FenceAgentDefaultParamsForPPC, VdsFenceOptionMapping, VdsFenceType, SupportedClusterLevels(ConfigAuthType.User), OvfUpdateIntervalInMinutes, OvfItemsCountPerUpdate, ProductRPMVersion(ConfigAuthType.User), RhevhLocalFSPath, HotPlugEnabled(ConfigAuthType.User), HotPlugCpuSupported(ConfigAuthType.User), IoThreadsSupported(ConfigAuthType.User), NetworkLinkingSupported(ConfigAuthType.User), SupportBridgesReportByVDSM(ConfigAuthType.User), ApplicationMode(ConfigAuthType.User), ShareableDiskEnabled(ConfigAuthType.User), DirectLUNDiskEnabled(ConfigAuthType.User), PopulateDirectLUNDiskDescriptionWithLUNId, WANDisableEffects(ConfigAuthType.User), WANColorDepth(ConfigAuthType.User), SupportForceCreateVG, NetworkConnectivityCheckTimeoutInSeconds, AllowClusterWithVirtGlusterEnabled, MTUOverrideSupported(ConfigAuthType.User), GlusterVolumeOptionGroupVirtValue, GlusterVolumeOptionOwnerUserVirtValue, GlusterVolumeOptionOwnerGroupVirtValue, GlusterDefaultBrickMountPoint, GlusterMetaVolumeName, CpuPinningEnabled, CpuPinMigrationEnabled, MigrationSupportForNativeUsb(ConfigAuthType.User), MigrationNetworkEnabled, VncKeyboardLayout(ConfigAuthType.User), VncKeyboardLayoutValidValues(ConfigAuthType.User), SupportCustomDeviceProperties, CustomDeviceProperties(ConfigAuthType.User), NetworkCustomPropertiesSupported, PreDefinedNetworkCustomProperties, UserDefinedNetworkCustomProperties, MultipleGatewaysSupported, VirtIoScsiEnabled(ConfigAuthType.User), OvfStoreOnAnyDomain, SshSoftFencingCommand, MemorySnapshotSupported(ConfigAuthType.User), HostNetworkQosSupported, StorageQosSupported(ConfigAuthType.User), CpuQosSupported(ConfigAuthType.User), MaxAverageNetworkQoSValue, MaxPeakNetworkQoSValue, MaxBurstNetworkQoSValue, MaxHostNetworkQosShares, UserMessageOfTheDay(ConfigAuthType.User), QoSInboundAverageDefaultValue, QoSInboundPeakDefaultValue, QoSInboundBurstDefaultValue, QoSOutboundAverageDefaultValue, QoSOutboundPeakDefaultValue, QoSOutboundBurstDefaultValue, MaxVmNameLengthWindows(ConfigAuthType.User), MaxVmNameLengthNonWindows(ConfigAuthType.User), AttestationServer, DefaultGeneralTimeZone, DefaultWindowsTimeZone, SpeedOptimizationSchedulingThreshold, SchedulerAllowOverBooking, SchedulerOverBookingThreshold, UserSessionTimeOutInterval(ConfigAuthType.User), DefaultMaximumMigrationDowntime, IsMigrationSupported(ConfigAuthType.User), IsMemorySnapshotSupported(ConfigAuthType.User), IsSuspendSupported(ConfigAuthType.User), SerialNumberPolicySupported(ConfigAuthType.User), IscsiMultipathingSupported, BootMenuSupported(ConfigAuthType.User), MixedDomainTypesInDataCenter, GlusterFsStorageEnabled, PosixStorageEnabled, VirtIoRngDeviceSupported(ConfigAuthType.User), ClusterRequiredRngSourcesDefault(ConfigAuthType.User), SpiceFileTransferToggleSupported(ConfigAuthType.User), SpiceCopyPasteToggleSupported(ConfigAuthType.User), DefaultMTU, LiveMergeSupported(ConfigAuthType.User), SkipFencingIfSDActiveSupported, JsonProtocolSupported(ConfigAuthType.User), MaxThroughputUpperBoundQosValue, MaxReadThroughputUpperBoundQosValue, MaxWriteThroughputUpperBoundQosValue, MaxIopsUpperBoundQosValue, MaxReadIopsUpperBoundQosValue, MaxWriteIopsUpperBoundQosValue, MaxCpuLimitQosValue, AutoConvergenceSupported(ConfigAuthType.User), MigrationCompressionSupported(ConfigAuthType.User), DefaultAutoConvergence, DefaultMigrationCompression, CORSSupport, CORSAllowedOrigins, CinderProviderSupported, NetworkSriovSupported, NetworkExclusivenessPermissiveValidation, HostDevicePassthroughCapabilities, LiveStorageMigrationBetweenDifferentStorageTypes, MaxIoThreadsPerVm(ConfigAuthType.User), RefreshLunSupported; public static enum ConfigAuthType { Admin, User } private ConfigAuthType authType; private ConfigurationValues(ConfigAuthType authType) { this.authType = authType; } private ConfigurationValues() { this(ConfigAuthType.Admin); } public ConfigAuthType getConfigAuthType() { return authType; } public boolean isAdmin() { return ConfigAuthType.Admin == authType; } public int getValue() { return ordinal(); } public static ConfigurationValues forValue(int value) { return values()[value]; } }
package org.dita.dost.util; import static org.dita.dost.util.Constants.INT_1024; import static org.dita.dost.util.Constants.INT_16; import static org.dita.dost.util.Constants.UNIX_SEPARATOR; import static org.dita.dost.util.Constants.WINDOWS_SEPARATOR; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import javax.imageio.ImageIO; import org.apache.commons.codec.binary.Base64; import org.dita.dost.log.DITAOTJavaLogger; import org.dita.dost.log.MessageUtils; /** * Image utility to get the width, height, type and binary data from * specific image file. * * @author Zhang, Yuan Peng * */ public final class ImgUtils { /** * Default Constructor * */ private ImgUtils(){ } private static String getImageOutPutPath(String fileName) { final DITAOTJavaLogger logger = new DITAOTJavaLogger(); String uplevelPath = null; String outDir = OutputUtils.getOutputDir(); String imgoutDir= null; String filename = fileName.replace( WINDOWS_SEPARATOR, UNIX_SEPARATOR); imgoutDir = outDir; if (OutputUtils.getGeneratecopyouter() != OutputUtils.Generate.OLDSOLUTION) { Properties propterties = null; try { propterties = ListUtils.getDitaList(); uplevelPath = propterties.getProperty("uplevels"); if (uplevelPath != null&&uplevelPath.length()>0){ imgoutDir = outDir +File.separator+uplevelPath; } } catch (final IOException e) { throw new RuntimeException("Reading list file failed: " + e.getMessage(), e); } } String imagePath = null; try { imagePath =new File(imgoutDir+File.separator+filename).getCanonicalPath(); } catch (IOException e) { logger.logException(e); } return imagePath; } private static boolean checkDirName(String dirName) { String outDir = OutputUtils.getOutputDir(); if (outDir != null) { outDir = new File(outDir).getPath().replace( WINDOWS_SEPARATOR, UNIX_SEPARATOR); if (new File(dirName).getPath().replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR).equalsIgnoreCase(outDir)) { return true; } } return false; } /** * Get the image width. * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return int - * The width of the picture in pixels. */ public static int getWidth (final String dirName, final String fileName){ final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName + File.separatorChar + fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); try { final BufferedImage img = ImageIO.read(imgInput); return img.getWidth(); }catch (final Exception e){ final Properties prop = new Properties(); prop.put("%1", dirName+File.separatorChar+fileName); logger.logError(MessageUtils.getMessage("DOTJ023E", prop).toString()); logger.logException(e); return -1; } } /** * Get the image height. * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return int - * The height of the picture in pixels. */ public static int getHeight (final String dirName, final String fileName){ final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName+File.separatorChar+fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); try { final BufferedImage img = ImageIO.read(imgInput); return img.getHeight(); }catch (final Exception e){ final Properties prop = new Properties(); prop.put("%1", dirName+File.separatorChar+fileName); logger.logError(MessageUtils.getMessage("DOTJ023E", prop).toString()); logger.logException(e); return -1; } } /** * Get the image width(ODT Transform). * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return int - * The width of the picture in pixels. */ public static int getWidthODT (final String dirName, final String fileName){ final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName+File.separatorChar+fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); try { final BufferedImage img = ImageIO.read(imgInput); return img.getWidth(); }catch (final Exception e){ final Properties prop = new Properties(); prop.put("%1", dirName+File.separatorChar+fileName); logger.logError(MessageUtils.getMessage("DOTJ023E", prop).toString()); logger.logException(e); return -1; } } /** * Get the image height(ODT Transform). * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return int - * The height of the picture in pixels. */ public static int getHeightODT (final String dirName, final String fileName){ final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName+File.separatorChar+fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); try { final BufferedImage img = ImageIO.read(imgInput); return img.getHeight(); }catch (final Exception e){ final Properties prop = new Properties(); prop.put("%1", dirName+File.separatorChar+fileName); logger.logError(MessageUtils.getMessage("DOTJ023E", prop).toString()); logger.logException(e); return -1; } } /** * Get the image binary data, with hexical output. For RTF transformation * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return java.lang.String - * The Hexical binary of image data converted to String. */ public static String getBinData (final String dirName, final String fileName){ final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName+File.separatorChar+fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); FileInputStream binInput = null; int bin; try{ String binStr = null; final StringBuffer ret = new StringBuffer(INT_16*INT_1024); binInput = new FileInputStream(imgInput); bin = binInput.read(); while (bin != -1){ binStr = Integer.toHexString(bin); if(binStr.length() < 2){ ret.append("0"); } ret.append(binStr); bin = binInput.read(); } return ret.toString(); }catch (final Exception e){ logger.logError(MessageUtils.getMessage("DOTJ023E").toString()); logger.logException(e); return null; }finally{ try{ binInput.close(); }catch(final IOException ioe){ logger.logException(ioe); } } } /** * Get Base64 encoding content. For ODT transformation * @param dirName - * The directory name that will be added to the path * of the image file. * @param fileName - * The file name of the image file. * @return base64 encoded binary data. */ public static String getBASE64(final String dirName, final String fileName) { final DITAOTJavaLogger logger = new DITAOTJavaLogger(); File imgInput = new File(dirName+File.separatorChar+fileName); if (checkDirName(dirName)) imgInput = new File(getImageOutPutPath(fileName)); //BASE64Encoder encoder = new BASE64Encoder(); final Base64 encoder = new Base64(); final byte buff[]=new byte[(int)imgInput.length()]; FileInputStream file = null; try { file = new FileInputStream(imgInput); file.read(buff); //String ret = encoder.encode(buff); final String ret = encoder.encodeToString(buff); return ret; } catch (final FileNotFoundException e) { logger.logError(MessageUtils.getMessage("DOTJ023E").toString()); logger.logException(e); return null; } catch (final IOException e) { logger.logError(MessageUtils.getMessage("DOTJ023E").toString()); logger.logException(e); return null; }finally{ try{ file.close(); }catch(final IOException ioe){ logger.logException(ioe); } } } /** * Get the type of image file by extension. * @param fileName - * The file name of the image file. * @return int - * The type of the picture in RTF specification. (JPG or PNG) */ public static String getType (final String fileName){ final String name = fileName.toLowerCase(); final DITAOTJavaLogger logger = new DITAOTJavaLogger(); final Properties prop = new Properties(); if (name.endsWith(".jpg")||name.endsWith(".jpeg")){ return "jpegblip"; }else if (name.endsWith(".gif")||name.endsWith(".png")){ return "pngblip"; } prop.put("%1", fileName); logger.logWarn(MessageUtils.getMessage("DOTJ024W", prop).toString()); return "other"; } }
package org.intermine.bio.dataconversion; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.util.SAXParser; import org.intermine.util.StringUtil; import org.intermine.xml.full.FullRenderer; import org.intermine.xml.full.Item; import org.intermine.xml.full.ItemFactory; import org.flymine.model.genomic.Publication; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.net.URL; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; import org.apache.commons.lang.StringUtils; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DatabaseException; import com.sleepycat.je.Environment; import com.sleepycat.je.EnvironmentConfig; import com.sleepycat.je.OperationStatus; import com.sleepycat.je.Transaction; /** * Class to fill in all publication information from pubmed * @author Mark Woodbridge */ public class EntrezPublicationsRetriever { protected static final Logger LOG = Logger.getLogger(EntrezPublicationsRetriever.class); protected static final String ENDL = System.getProperty("line.separator"); protected static final String ESUMMARY_URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?tool=flymine&db=pubmed&id="; // number of summaries to retrieve per request protected static final int BATCH_SIZE = 500; // number of times to try the same bacth from the server private static final int MAX_TRIES = 5; private String osAlias = null, outputFile = null; private Set<String> seenPubMeds = new HashSet<String>(); private Map<String, Item> authorMap = new HashMap<String, Item>(); private String cacheDirName; private ItemFactory itemFactory; static final String TARGET_NS = "http://www.flymine.org/model/genomic /** * Set the ObjectStore alias. * @param osAlias The ObjectStore alias */ public void setOsAlias(String osAlias) { this.osAlias = osAlias; } /** * Set the output file name * @param outputFile The output file name */ public void setOutputFile(String outputFile) { this.outputFile = outputFile; } /** * Set the cache file name * @param cacheDirName The cache file */ public void setCacheDirName(String cacheDirName) { this.cacheDirName = cacheDirName; } /** * Synchronize publications with pubmed using pmid * @throws Exception if an error occurs */ public void execute() throws Exception { // Needed so that STAX can find it's implementation classes ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Database db = null; Transaction txn = null; try { if (osAlias == null) { throw new BuildException("osAlias attribute is not set"); } if (outputFile == null) { throw new BuildException("outputFile attribute is not set"); } // environment is transactional EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(true); envConfig.setAllowCreate(true); Environment env = new Environment(new File(cacheDirName), envConfig); DatabaseConfig dbConfig = new DatabaseConfig(); dbConfig.setTransactional(true); dbConfig.setAllowCreate(true); dbConfig.setSortedDuplicates(true); db = env.openDatabase(null , "publications_db", dbConfig); txn = env.beginTransaction(null, null); LOG.info("Starting EntrezPublicationsRetriever"); Writer writer = new FileWriter(outputFile); ObjectStore os = ObjectStoreFactory.getObjectStore(osAlias); Set<String> idsToFetch = new HashSet<String>(); itemFactory = new ItemFactory(os.getModel(), "-1_"); writer.write(FullRenderer.getHeader() + ENDL); for (Iterator<Publication> iter = getPublications(os).iterator(); iter.hasNext();) { String pubMedId = iter.next().getPubMedId(); if (seenPubMeds.contains(pubMedId)) { continue; } DatabaseEntry key = new DatabaseEntry(pubMedId.getBytes()); DatabaseEntry data = new DatabaseEntry(); if (db.get(txn, key, data, null).equals(OperationStatus.SUCCESS)) { try { ByteArrayInputStream mapInputStream = new ByteArrayInputStream(data.getData()); ObjectInputStream deserializer = new ObjectInputStream(mapInputStream); Map<String, Object> pubMap = (Map) deserializer.readObject(); writeItems(writer, mapToItems(itemFactory, pubMap)); // System.err. println("found in cache: " + pubMedId); seenPubMeds.add(pubMedId); } catch (EOFException e) { // ignore and fetch it again System.err .println("found in cache, but igored due to cache problem: " + pubMedId); } } else { idsToFetch.add(pubMedId); } } Iterator<String> idIter = idsToFetch.iterator(); Set<String> thisBatch = new HashSet<String>(); while (idIter.hasNext()) { String pubMedId = idIter.next(); thisBatch.add(pubMedId); if (thisBatch.size() == BATCH_SIZE || !idIter.hasNext() && thisBatch.size() > 0) { try { // the server may return less publications than we ask for, so keep a Map Map<String, Map<String, Object>> fromServerMap = null; for (int i = 0; i < MAX_TRIES; i++) { BufferedReader br = new BufferedReader(getReader(thisBatch)); StringBuffer buf = new StringBuffer(); String line; while ((line = br.readLine()) != null) { buf.append(line + "\n"); } fromServerMap = new HashMap<String, Map<String, Object>>(); Throwable throwable = null; try { SAXParser.parse(new InputSource(new StringReader(buf.toString())), new Handler(fromServerMap)); } catch (Throwable e) { // try again or re-throw the Throwable throwable = e; } if (i == MAX_TRIES) { throw new RuntimeException("failed to parse: " + buf.toString() + " - tried " + MAX_TRIES + " times", throwable); } else { if (throwable != null) { // try again continue; } } for (String id: fromServerMap.keySet()) { writeItems(writer, mapToItems(itemFactory, fromServerMap.get(id))); } addToDb(txn, db, fromServerMap); break; } thisBatch.clear(); } finally { txn.commit(); // start a new transaction incase there is an exception while parsing txn = env.beginTransaction(null, null); } } } writeItems(writer, authorMap.values()); writer.write(FullRenderer.getFooter() + ENDL); writer.flush(); writer.close(); } catch (Throwable e) { throw new RuntimeException("failed to get all publications", e); } finally { txn.commit(); db.close(); Thread.currentThread().setContextClassLoader(cl); } } private void writeItems(Writer writer, Collection<Item> items) throws IOException { for (Item item: items) { writer.write(FullRenderer.render(item)); } } /** * Add a Map of pubication information to the Database */ private void addToDb(Transaction txn, Database db, Map<String, Map<String, Object>> fromServerMap) throws IOException, DatabaseException { for (Map.Entry<String, Map<String, Object>> entry: fromServerMap.entrySet()) { String pubMedId = entry.getKey(); // System.err .println("adding to cache: " + pubMedId); DatabaseEntry key = new DatabaseEntry(pubMedId.getBytes()); Map dataMap = entry.getValue(); ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(arrayOutputStream); serializer.writeObject(dataMap); DatabaseEntry data = new DatabaseEntry(arrayOutputStream.toByteArray()); db.put(txn, key, data); } } /** * Retrieve the publications to be updated * @param os The ObjectStore to read from * @return a List of publications */ protected List<Publication> getPublications(ObjectStore os) { Query q = new Query(); QueryClass qc = new QueryClass(Publication.class); q.addFrom(qc); q.addToSelect(qc); return (List<Publication>) os.executeSingleton(q); } /** * Obtain the pubmed esummary information for the publications * @param ids the pubMedIds of the publications * @return a Reader for the information * @throws Exception if an error occurs */ protected Reader getReader(Set<String> ids) throws Exception { String urlString = ESUMMARY_URL + StringUtil.join(ids, ","); System.err .println("retrieving: " + urlString); return new BufferedReader(new InputStreamReader(new URL(urlString).openStream())); } private Set<Item> mapToItems(ItemFactory itemFactory, Map map) { Set<Item> retSet = new HashSet<Item>(); Item publication = itemFactory.makeItemForClass(TARGET_NS + "Publication"); retSet.add(publication); publication.setAttribute("pubMedId", (String) map.get("id")); publication.setAttribute("journal", (String) map.get("journal")); publication.setAttribute("title", (String) map.get("title")); publication.setAttribute("volume", (String) map.get("volume")); if (!StringUtils.isEmpty((String) map.get("volume"))) { publication.setAttribute("issue", (String) map.get("issue")); } publication.setAttribute("pages", (String) map.get("pages")); if (map.get("year") != null) { publication.setAttribute("year", (String) map.get("year")); } List<String> authors = (List<String>) map.get("authors"); if (authors != null) { for (String authorString : authors) { Item author = authorMap.get(authorString); if (author == null) { author = itemFactory.makeItemForClass(TARGET_NS + "Author"); author.setAttribute("name", authorString); authorMap.put(authorString, author); } author.addToCollection("publications", publication); publication.addToCollection("authors", author); if (!publication.hasAttribute("firstAuthor")) { publication.setAttribute("firstAuthor", authorString); } } } return retSet; } /** * Extension of DefaultHandler to handle an esummary for a publication */ class Handler extends DefaultHandler { Map<String, Object> pubMap; String name; StringBuffer characters; boolean duplicateEntry = false; Map<String, Map<String, Object>> cache; /** * Constructor * @param fromServerMap cache of publications */ public Handler(Map<String, Map<String, Object>> fromServerMap) { this.cache = fromServerMap; } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attrs) { if ("ERROR".equals(qName)) { name = qName; } else if ("Id".equals(qName)) { name = "Id"; } else if ("DocSum".equals(qName)) { duplicateEntry = false; } else { name = attrs.getValue("Name"); } characters = new StringBuffer(); } /** * {@inheritDoc} */ @Override public void characters(char[] ch, int start, int length) { characters.append(new String(ch, start, length)); } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) { // do nothing if we have seen this pubmed id before if (duplicateEntry) { return; } if ("ERROR".equals(name)) { LOG.error("Unable to retrieve pubmed record: " + characters); } else if ("Id".equals(name)) { String pubMedId = characters.toString(); if (seenPubMeds.contains(pubMedId)) { duplicateEntry = true; return; } pubMap = new HashMap<String, Object>(); pubMap.put("id", pubMedId); seenPubMeds.add(pubMedId); cache.put(pubMedId, pubMap); } else if ("PubDate".equals(name)) { String year = characters.toString().split(" ")[0]; try { Integer.parseInt(year); pubMap.put("year", year); } catch (NumberFormatException e) { LOG.warn("Cannot parse year from publication: " + year); } } else if ("Source".equals(name)) { pubMap.put("journal", characters.toString()); } else if ("Title".equals(name)) { pubMap.put("title", characters.toString()); } else if ("Volume".equals(name)) { pubMap.put("volume", characters.toString()); } else if ("Issue".equals(name)) { pubMap.put("issue", characters.toString()); } else if ("Pages".equals(name)) { pubMap.put("pages", characters.toString()); } else if ("Author".equals(name)) { String authorString = characters.toString(); List<String> authorList = (List<String>) pubMap.get("authors"); if (authorList == null) { authorList = new ArrayList<String>(); pubMap.put("authors", authorList); } authorList.add(authorString); } name = null; } } }
package verification.platu.stategraph; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.Stack; import lpn.parser.LhpnFile; import lpn.parser.Transition; import verification.platu.common.IndexObjMap; import verification.platu.logicAnalysis.Constraint; import verification.platu.lpn.DualHashMap; import verification.platu.lpn.LpnTranList; import verification.platu.main.Main; import verification.platu.main.Options; import verification.platu.project.PrjState; import verification.timed_state_exploration.zoneProject.Event; import verification.timed_state_exploration.zoneProject.EventSet; import verification.timed_state_exploration.zoneProject.InequalityVariable; import verification.timed_state_exploration.zoneProject.IntervalPair; import verification.timed_state_exploration.zoneProject.LPNContAndRate; import verification.timed_state_exploration.zoneProject.LPNContinuousPair; import verification.timed_state_exploration.zoneProject.LPNTransitionPair; import verification.timed_state_exploration.zoneProject.TimedPrjState; import verification.timed_state_exploration.zoneProject.Zone; public class StateGraph { protected State init = null; protected IndexObjMap<State> stateCache; protected IndexObjMap<State> localStateCache; protected HashMap<State, State> state2LocalMap; protected HashMap<State, LpnTranList> enabledSetTbl; protected HashMap<State, HashMap<Transition, State>> nextStateMap; protected List<State> stateSet = new LinkedList<State>(); protected List<State> frontierStateSet = new LinkedList<State>(); protected List<State> entryStateSet = new LinkedList<State>(); protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> newConstraintSet = new LinkedList<Constraint>(); protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>(); protected Set<Constraint> constraintSet = new HashSet<Constraint>(); protected LhpnFile lpn; protected static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0); public StateGraph(LhpnFile lpn) { this.lpn = lpn; this.stateCache = new IndexObjMap<State>(); this.localStateCache = new IndexObjMap<State>(); this.state2LocalMap = new HashMap<State, State>(); this.enabledSetTbl = new HashMap<State, LpnTranList>(); this.nextStateMap = new HashMap<State, HashMap<Transition, State>>(); } public LhpnFile getLpn(){ return this.lpn; } public void printStates(){ System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size())); } public Set<Transition> getTranList(State currentState){ return this.nextStateMap.get(currentState).keySet(); } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * @param baseState - State to start from * @return Number of new transitions. */ public int constrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); // TODO: What if we just read tranVector from baseState? LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { System.out.println("firedTran: " + firedTran.getLabel() + "(" + firedTran.getLpn().getLabel() + ")"); State newState = constrFire(firedTran,currentState); State nextState = addState(newState); newStateFlag = false; if(nextState == newState){ addFrontierState(nextState); newStateFlag = true; } // StateTran stTran = new StateTran(currentState, firedTran, state); if(nextState != currentState){ // this.addStateTran(currentState, nextState, firedTran); this.addStateTran(currentState, firedTran, nextState); newTransitions++; // TODO: (original) check that a variable was changed before creating a constraint if(!firedTran.isLocal()){ for(LhpnFile lpn : firedTran.getDstLpnList()){ //TODO: No need to generate constraint for the lpn where firedTran lives. if (firedTran.getLpn().equals(lpn)) continue; Constraint c = new Constraint(currentState, nextState, firedTran, lpn); lpn.getStateGraph().addConstraint(c); } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions.isEmpty()) continue; Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); if(disabledTran != null) { System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + firedTran.getFullLabel()); currentState.setFailure(); return -1; } stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } /** * Finds reachable states from the given state. * Also generates new constraints from the state transitions. * Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods * @param baseState State to start from * @return Number of new transitions. */ public int synchronizedConstrFindSG(final State baseState){ boolean newStateFlag = false; int ptr = 1; int newTransitions = 0; Stack<State> stStack = new Stack<State>(); Stack<LpnTranList> tranStack = new Stack<LpnTranList>(); LpnTranList currentEnabledTransitions = getEnabled(baseState); stStack.push(baseState); tranStack.push((LpnTranList) currentEnabledTransitions); while (true){ ptr State currentState = stStack.pop(); currentEnabledTransitions = tranStack.pop(); for (Transition firedTran : currentEnabledTransitions) { State st = constrFire(firedTran,currentState); State nextState = addState(st); newStateFlag = false; if(nextState == st){ newStateFlag = true; addFrontierState(nextState); } if(nextState != currentState){ newTransitions++; if(!firedTran.isLocal()){ // TODO: (original) check that a variable was changed before creating a constraint for(LhpnFile lpn : firedTran.getDstLpnList()){ Constraint c = new Constraint(currentState, nextState, firedTran, lpn); lpn.getStateGraph().synchronizedAddConstraint(c); } } } if(!newStateFlag) continue; LpnTranList nextEnabledTransitions = getEnabled(nextState); if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) { continue; } // currentEnabledTransitions = getEnabled(nexState); // Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions); // if(disabledTran != null) { // prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " + // firedTran.getFullLabel()); // currentState.setFailure(); // return -1; stStack.push(nextState); tranStack.push(nextEnabledTransitions); ptr++; } if (ptr == 0) { break; } } return newTransitions; } public List<State> getFrontierStateSet(){ return this.frontierStateSet; } public List<State> getStateSet(){ return this.stateSet; } public void addFrontierState(State st){ this.entryStateSet.add(st); } public List<Constraint> getOldConstraintSet(){ return this.oldConstraintSet; } /** * Adds constraint to the constraintSet. * @param c - Constraint to be added. * @return True if added, otherwise false. */ public boolean addConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } /** * Adds constraint to the constraintSet. Synchronized version of addConstraint(). * @param c - Constraint to be added. * @return True if added, otherwise false. */ public synchronized boolean synchronizedAddConstraint(Constraint c){ if(this.constraintSet.add(c)){ this.frontierConstraintSet.add(c); return true; } return false; } public List<Constraint> getNewConstraintSet(){ return this.newConstraintSet; } public void genConstraints(){ oldConstraintSet.addAll(newConstraintSet); newConstraintSet.clear(); newConstraintSet.addAll(frontierConstraintSet); frontierConstraintSet.clear(); } public void genFrontier(){ this.stateSet.addAll(this.frontierStateSet); this.frontierStateSet.clear(); this.frontierStateSet.addAll(this.entryStateSet); this.entryStateSet.clear(); } public void setInitialState(State init){ this.init = init; } public State getInitialState(){ return this.init; } public void draw(){ String dotFile = Options.getDotPath(); if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){ String dirSlash = "/"; if(Main.isWindows) dirSlash = "\\"; dotFile = dotFile += dirSlash; } dotFile += this.lpn.getLabel() + ".dot"; PrintStream graph = null; try { graph = new PrintStream(new FileOutputStream(dotFile)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } graph.println("digraph SG{"); //graph.println(" fixedsize=true"); int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size(); String[] variables = new String[size]; DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap(); int i; for(i = 0; i < size; i++){ variables[i] = varIndexMap.getKey(i); } //for(State state : this.reachableSet.keySet()){ for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) { State state = this.getState(stateIdx); String dotLabel = state.getIndex() + ": "; int[] vector = state.getVector(); for(i = 0; i < size; i++){ dotLabel += variables[i]; if(vector[i] == 0) dotLabel += "'"; if(i < size-1) dotLabel += " "; } int[] mark = state.getMarking(); dotLabel += "\\n"; for(i = 0; i < mark.length; i++){ if(i == 0) dotLabel += "["; dotLabel += mark[i]; if(i < mark.length - 1) dotLabel += ", "; else dotLabel += "]"; } String attributes = ""; if(state == this.init) attributes += " peripheries=2"; if(state.failure()) attributes += " style=filled fillcolor=\"red\""; graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " + "label=\"" + dotLabel + "\"" + attributes + "]"); for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){ State tailState = state; State headState = stateTran.getValue(); Transition lpnTran = stateTran.getKey(); String edgeLabel = lpnTran.getLabel() + ": "; int[] headVector = headState.getVector(); int[] tailVector = tailState.getVector(); for(i = 0; i < size; i++){ if(headVector[i] != tailVector[i]){ if(headVector[i] == 0){ edgeLabel += variables[i]; edgeLabel += "-"; } else{ edgeLabel += variables[i]; edgeLabel += "+"; } } } graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]"); } } graph.println("}"); graph.close(); } /** * Return the enabled transitions in the state with index 'stateIdx'. * @param stateIdx * @return */ public LpnTranList getEnabled(int stateIdx) { State curState = this.getState(stateIdx); return this.getEnabled(curState); } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); return curEnabled; } /** * Return the set of all LPN transitions that are enabled in 'state'. * @param curState * @return */ public LpnTranList getEnabled(State curState, boolean init) { if (curState == null) { throw new NullPointerException(); } if(enabledSetTbl.containsKey(curState) == true){ if (Options.getDebugMode()) { // System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~"); // printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state "); } return (LpnTranList)enabledSetTbl.get(curState).clone(); } LpnTranList curEnabled = new LpnTranList(); if (init) { for (Transition tran : this.lpn.getAllTransitions()) { if (isEnabled(tran,curState)) { if (Options.getDebugMode()) { // System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled"); } if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } } else { for (int i=0; i < this.lpn.getAllTransitions().length; i++) { Transition tran = this.lpn.getAllTransitions()[i]; if (curState.getTranVector()[i]) if(tran.isLocal()==true) curEnabled.addLast(tran); else curEnabled.addFirst(tran); } } this.enabledSetTbl.put(curState, curEnabled); if (Options.getDebugMode()) { // System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl."); // printEnabledSetTbl(); } return curEnabled; } // private void printEnabledSetTbl() { // for (State s : enabledSetTbl.keySet()) { // System.out.print("S" + s.getIndex() + " -> "); // printTransitionSet(enabledSetTbl.get(s), ""); public boolean isEnabled(Transition tran, State curState) { int[] varValuesVector = curState.getVector(); String tranName = tran.getLabel(); int tranIndex = tran.getIndex(); if (Options.getDebugMode()) { // System.out.println("Checking " + tran); } if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0 && !(tran.isPersistent() && curState.getTranVector()[tranIndex])) { if (Options.getDebugMode()) { // System.out.println(tran.getName() + " " + "Enabling condition is false"); } return false; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) { if (Options.getDebugMode()) { // System.out.println("Rate is zero"); } return false; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { int[] curMarking = curState.getMarking(); for (int place : this.lpn.getPresetIndex(tranName)) { if (curMarking[place]==0) { if (Options.getDebugMode()) { // System.out.println(tran.getName() + " " + "Missing a preset token"); } return false; } } // if a transition is enabled and it is not recorded in the enabled transition vector curState.getTranVector()[tranIndex] = true; } return true; } public int reachSize() { if(this.stateCache == null){ return this.stateSet.size(); } return this.stateCache.size(); } public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) { boolean isStateOnStack = false; for (PrjState prjState : stateStack) { State[] stateArray = prjState.toStateArray(); for (State s : stateArray) { if (s == curState) { isStateOnStack = true; break; } } if (isStateOnStack) break; } return isStateOnStack; } /* * Add the module state mState to the local cache, and also add its local portion to * the local portion cache, and build the mapping between the mState and lState for fast lookup * in the future. */ public State addState(State mState) { State cachedState = this.stateCache.add(mState); State lState = this.state2LocalMap.get(cachedState); if(lState == null) { lState = cachedState.getLocalState(); lState = this.localStateCache.add(lState); this.state2LocalMap.put(cachedState, lState); } return cachedState; } /* * Get the local portion of mState from the cache.. */ public State getLocalState(State mState) { return this.state2LocalMap.get(mState); } public State getState(int stateIdx) { return this.stateCache.get(stateIdx); } public void addStateTran(State curSt, Transition firedTran, State nextSt) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) { nextMap = new HashMap<Transition,State>(); nextMap.put(firedTran, nextSt); this.nextStateMap.put(curSt, nextMap); } else nextMap.put(firedTran, nextSt); } public State getNextState(State curSt, Transition firedTran) { HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt); if(nextMap == null) return null; return nextMap.get(firedTran); } public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){ HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState); if(tranMap == null){ return emptySet; } return tranMap.entrySet(); } public int numConstraints(){ if(this.constraintSet == null){ return this.oldConstraintSet.size(); } return this.constraintSet.size(); } public void clear(){ this.constraintSet.clear(); this.frontierConstraintSet.clear(); this.newConstraintSet.clear(); this.frontierStateSet.clear(); this.entryStateSet.clear(); this.constraintSet = null; this.frontierConstraintSet = null; this.newConstraintSet = null; this.frontierStateSet = null; this.entryStateSet = null; this.stateCache = null; } public State genInitialState() { // create initial vector int size = this.lpn.getVarIndexMap().size(); int[] initialVector = new int[size]; for(int i = 0; i < size; i++) { String var = this.lpn.getVarIndexMap().getKey(i); int val = this.lpn.getInitVector(var); initialVector[i] = val; } this.init = new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector)); return this.init; } /** * Fire a transition on a state array, find new local states, and return the new state array formed by the new local states. * @param firedTran * @param curLpnArray * @param curStateArray * @param curLpnIndex * @return */ public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) { State[] stateArray = new State[curSgArray.length]; for(int i = 0; i < curSgArray.length; i++) stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]); return this.fire(curSgArray, stateArray, firedTran); } /** * This method is called by search_dfs(StateGraph[], State[]). * @param curSgArray * @param curStateArray * @param firedTran * @return */ public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran){ // HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) { // public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran, // ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) { // public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran, // ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) { int thisLpnIndex = this.getLpn().getLpnIndex(); State[] nextStateArray = curStateArray.clone(); State curState = curStateArray[thisLpnIndex]; // State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, continuousValues, z); // State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran, newAssignValues, z); State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran); //int[] nextVector = nextState.getVector(); //int[] curVector = curState.getVector(); // TODO: (future) assertions in our LPN? /* for(Expression e : assertions){ if(e.evaluate(nextVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ nextStateArray[thisLpnIndex] = nextState; if(firedTran.isLocal()==true) { // nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState); return nextStateArray; } HashMap<String, Integer> vvSet = new HashMap<String, Integer>(); vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector()); // for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) { // if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); // if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) { // int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector())); // vvSet.put(key, newValue); /* for (VarExpr s : this.getAssignments()) { int newValue = nextVector[s.getVar().getIndex(curVector)]; vvSet.put(s.getVar().getName(), newValue); } */ // Update other local states with the new values generated for the shared variables. //nextStateArray[this.lpn.getIndex()] = nextState; // if (!firedTran.getDstLpnList().contains(this.lpn)) // firedTran.getDstLpnList().add(this.lpn); for(LhpnFile curLPN : firedTran.getDstLpnList()) { int curIdx = curLPN.getLpnIndex(); // System.out.println("Checking " + curLPN.getLabel() + " " + curIdx); State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran); if(newState != null) { nextStateArray[curIdx] = newState; } else { State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap()); if (newOther == null) nextStateArray[curIdx] = curStateArray[curIdx]; else { State cachedOther = curSgArray[curIdx].addState(newOther); //nextStateArray[curIdx] = newOther; nextStateArray[curIdx] = cachedOther; // System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" + // curStateArray[curIdx].print() + firedTran.getName() + "\n" + // cachedOther.getIndex() + ":\n" + cachedOther.print()); curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther); //((ProbabilisticStateGraph) curSgArray[curIdx]).printNextProbabilisticStateMap(firedTran); } } } return nextStateArray; } // TODO: (original) add transition that fires to parameters public State fire(final StateGraph thisSg, final State curState, Transition firedTran){ // HashMap<LPNContinuousPair, IntervalPair> continuousValues, Zone z) { // public State fire(final StateGraph thisSg, final State curState, Transition firedTran, // ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues, Zone z) { // public State fire(final StateGraph thisSg, final State curState, Transition firedTran, // ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues, Zone z) { // Search for and return cached next state first. // if(this.nextStateMap.containsKey(curState) == true) // return (State)this.nextStateMap.get(curState); State nextState = thisSg.getNextState(curState, firedTran); if(nextState != null) return nextState; // If no cached next state exists, do regular firing. // Marking update int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0) curNewMarking = curOldMarking; else { curNewMarking = new int[curOldMarking.length]; curNewMarking = curOldMarking.clone(); for (int prep : this.lpn.getPresetIndex(firedTran.getLabel())) { curNewMarking[prep]=0; } for (int postp : this.lpn.getPostsetIndex(firedTran.getLabel())) { curNewMarking[postp]=1; } } // State vector update int[] newVectorArray = curState.getVector().clone(); int[] curVector = curState.getVector(); HashMap<String, String> currentValuesAsString = this.lpn.getAllVarsWithValuesAsString(curVector); for (String key : currentValuesAsString.keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getLabel(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getLabel(), key).evaluateExpr(currentValuesAsString); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getLabel(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getLabel(), key).evaluateExpr(currentValuesAsString); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } // // Update rates // final int OLD_ZERO = 0; // Case 0 in description. //// final int NEW_NON_ZERO = 1; // Case 1 in description. //// final int NEW_ZERO = 2; // Case 2 in description. //// final int OLD_NON_ZERO = 3; // Case 3 in description. //// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); //// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); //// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); //// newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // final int NEW_NON_ZERO = 1; // Case 1 in description. // final int NEW_ZERO = 2; // Case 2 in description. // final int OLD_NON_ZERO = 3; // Cade 3 in description. // if(Options.getTimingAnalysisFlag()){ // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // for(String key : this.lpn.getContVars()){ // // Get the pairing. // int lpnIndex = this.lpn.getLpnIndex(); // int contVarIndex = this.lpn.getContVarIndex(key); // // Package up the indecies. // LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); // //Integer newRate = null; // IntervalPair newRate = null; // IntervalPair newValue= null; // // Check if there is a new rate assignment. // if(this.lpn.getRateAssignTree(firedTran.getName(), key) != null){ // // Get the new value. // //IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key) // //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null); // newRate = this.lpn.getRateAssignTree(firedTran.getName(), key) // .evaluateExprBound(currentValuesAsString, z, null); //// // Get the pairing. //// int lpnIndex = this.lpn.getLpnIndex(); //// int contVarIndex = this.lpn.getContVarIndex(key); //// // Package up the indecies. //// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); // // Keep the current rate. // //newRate = newIntervalRate.get_LowerBound(); // //contVar.setCurrentRate(newIntervalRate.get_LowerBound()); // contVar.setCurrentRate(newRate.get_LowerBound()); //// continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR), //// z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar))); //// // Check if the new assignment gives rate zero. //// boolean newRateZero = newRate == 0; //// // Check if the variable was already rate zero. //// boolean oldRateZero = z.getCurrentRate(contVar) == 0; //// // Put the new value in the appropriate set. //// if(oldRateZero){ //// if(newRateZero){ //// // Old rate is zero and the new rate is zero. //// newAssignValues.get(OLD_ZERO).put(contVar, newValue); //// else{ //// // Old rate is zero and the new rate is non-zero. //// newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue); //// else{ //// if(newRateZero){ //// // Old rate is non-zero and the new rate is zero. //// newAssignValues.get(NEW_ZERO).put(contVar, newValue); //// else{ //// // Old rate is non-zero and the new rate is non-zero. //// newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue); // // Update continuous variables. // //for(String key : this.lpn.getContVars()){ // // Get the new assignments on the continuous variables and update inequalities. // if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { //// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); //// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; // // Get the new value. // newValue = this.lpn.getContAssignTree(firedTran.getName(), key) // //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null); // .evaluateExprBound(currentValuesAsString, z, null); //// // Get the pairing. //// int lpnIndex = this.lpn.getLpnIndex(); //// int contVarIndex = this.lpn.getContVarIndex(key); //// // Package up the indecies. //// LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); // if(newRate == null){ // // Keep the current rate. // contVar.setCurrentRate(z.getCurrentRate(contVar)); //// continuousValues.put(contVar, newValue); // // Get each inequality that involves the continuous variable. // ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities(); // // Update the inequalities. // for(InequalityVariable ineq : inequalities){ // int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName()); // HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>(); // continuousValues.putAll(newAssignValues.get(OLD_ZERO)); // continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO)); // continuousValues.putAll(newAssignValues.get(NEW_ZERO)); // continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO)); // newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues); // // If the value did not get assigned, put in the old value. // if(newValue == null){ // newValue = z.getContinuousBounds(contVar); // // Check if the new assignment gives rate zero. // //boolean newRateZero = newRate == 0; // boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false; // // Check if the variable was already rate zero. // boolean oldRateZero = z.getCurrentRate(contVar) == 0; // // Put the new value in the appropriate set. // if(oldRateZero){ // if(newRateZero){ // // Old rate is zero and the new rate is zero. // newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); // else{ // // Old rate is zero and the new rate is non-zero. // newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); // else{ // if(newRateZero){ // // Old rate is non-zero and the new rate is zero. // newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); // else{ // // Old rate is non-zero and the new rate is non-zero. // newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); /* for (VarExpr s : firedTran.getAssignments()) { int newValue = (int) s.getExpr().evaluate(curVector); newVectorArray[s.getVar().getIndex(curVector)] = newValue; } */ // Enabled transition vector update boolean[] newEnabledTranVector = updateEnabledTranVector(curState, curNewMarking, newVectorArray, firedTran); State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector)); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ thisSg.addStateTran(curState, firedTran, newState); //((ProbabilisticStateGraph) thisSg).printNextProbabilisticStateMap(firedTran); return newState; } public boolean[] updateEnabledTranVector(State curState, int[] newMarking, int[] newVectorArray, Transition firedTran) { boolean[] enabledTranAfterFiring = curState.getTranVector().clone(); // Disable the fired transition and all of its conflicting transitions. if (firedTran != null) { enabledTranAfterFiring[firedTran.getIndex()] = false; for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) { enabledTranAfterFiring[curConflictingTranIndex] = false; } } // find newly enabled transition(s) based on the updated markings and variables for (Transition tran : this.lpn.getAllTransitions()) { boolean needToUpdate = true; String tranName = tran.getLabel(); int tranIndex = tran.getIndex(); if (Options.getDebugMode()) { // System.out.println("Checking " + tranName); } if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { if (Options.getDebugMode()) { // System.out.println(tran.getName() + " " + "Enabling condition is false"); } if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent()) enabledTranAfterFiring[tranIndex] = false; continue; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { if (Options.getDebugMode()) { // System.out.println("Rate is zero"); } continue; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { for (int place : this.lpn.getPresetIndex(tranName)) { if (newMarking[place]==0) { if (Options.getDebugMode()) { // System.out.println(tran.getName() + " " + "Missing a preset token"); } needToUpdate = false; break; } } } if (needToUpdate) { enabledTranAfterFiring[tranIndex] = true; if (Options.getDebugMode()) { // System.out.println(tran.getName() + " is Enabled."); } } } return enabledTranAfterFiring; } /** * Updates the transition vector. * @param enabledTranBeforeFiring * The enabling before the transition firing. * @param newMarking * The new marking to check for transitions with. * @param newVectorArray * The new values of the boolean variables. * @param firedTran * The transition that fire. * @param newlyEnabled * A list to capture the newly enabled transitions. * @return * The newly enabled transitions. */ public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring, int[] newMarking, int[] newVectorArray, Transition firedTran, HashSet<LPNTransitionPair> newlyEnabled) { boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone(); // Disable fired transition if (firedTran != null) { enabledTranAfterFiring[firedTran.getIndex()] = false; for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) { enabledTranAfterFiring[curConflictingTranIndex] = false; } } // find newly enabled transition(s) based on the updated markings and variables if (Options.getDebugMode()) System.out.println("Finding newly enabled transitions at updateEnabledTranVector."); for (Transition tran : this.lpn.getAllTransitions()) { boolean needToUpdate = true; String tranName = tran.getLabel(); int tranIndex = tran.getIndex(); if (Options.getDebugMode()) System.out.println("Checking " + tranName); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { if (Options.getDebugMode()) System.out.println(tran.getLabel() + " " + "Enabling condition is false"); if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent()) enabledTranAfterFiring[tranIndex] = false; continue; } if (this.lpn.getTransitionRateTree(tranName) != null && this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) { if (Options.getDebugMode()) System.out.println("Rate is zero"); continue; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { for (int place : this.lpn.getPresetIndex(tranName)) { if (newMarking[place]==0) { if (Options.getDebugMode()) System.out.println(tran.getLabel() + " " + "Missing a preset token"); needToUpdate = false; break; } } } if (needToUpdate) { // if a transition is enabled and it is not recorded in the enabled transition vector enabledTranAfterFiring[tranIndex] = true; if (Options.getDebugMode()) System.out.println(tran.getLabel() + " is Enabled."); } if(newlyEnabled != null && enabledTranAfterFiring[tranIndex] && !enabledTranBeforeFiring[tranIndex]){ newlyEnabled.add(new LPNTransitionPair(tran.getLpn().getLpnIndex(), tranIndex)); } } return enabledTranAfterFiring; } public State constrFire(Transition firedTran, final State curState) { // Hao's original marking update. // // Marking update // int[] curOldMarking = curState.getMarking(); // int[] curNewMarking = null; // if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){ // curNewMarking = curOldMarking; // else { // curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length]; // int index = 0; // for (int i : curOldMarking) { // boolean existed = false; // for (int prep : this.lpn.getPresetIndex(firedTran.getName())) { // if (i == prep) { // existed = true; // break; // else if(prep > i){ // break; // if (existed == false) { // curNewMarking[index] = i; // index++; // for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) { // curNewMarking[index] = postp; // index++; int[] curOldMarking = curState.getMarking(); int[] curNewMarking = null; if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0) curNewMarking = curOldMarking; else { curNewMarking = new int[curOldMarking.length]; curNewMarking = curOldMarking.clone(); for (int prep : this.lpn.getPresetIndex(firedTran.getLabel())) { curNewMarking[prep]=0; } for (int postp : this.lpn.getPostsetIndex(firedTran.getLabel())) { curNewMarking[postp]=1; } } // State vector update int[] oldVector = curState.getVector(); int size = oldVector.length; int[] newVectorArray = new int[size]; System.arraycopy(oldVector, 0, newVectorArray, 0, size); int[] curVector = curState.getVector(); for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) { if (this.lpn.getBoolAssignTree(firedTran.getLabel(), key) != null) { int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getLabel(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } if (this.lpn.getIntAssignTree(firedTran.getLabel(), key) != null) { int newValue = (int)this.lpn.getIntAssignTree(firedTran.getLabel(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; } } // Enabled transition vector update /* Hao's code //boolean[] newEnabledTranArray = curState.getTranVector(); //newEnabledTranArray[firedTran.getIndex()] = false; //State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray); */ boolean[] newEnabledTranVector = updateEnabledTranVector(curState, curNewMarking, newVectorArray, firedTran); State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector); // TODO: (future) assertions in our LPN? /* int[] newVector = newState.getVector(); for(Expression e : assertions){ if(e.evaluate(newVector) == 0){ System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label); System.exit(1); } } */ return newState; } public void drawLocalStateGraph() { try { String graphFileName = null; if (Options.getPOR() == null) graphFileName = Options.getPrjSgPath() + getLpn().getLabel() + "_local_sg.dot"; else graphFileName = Options.getPrjSgPath() + getLpn().getLabel() + "POR_"+ Options.getCycleClosingMthd() + "_local_sg.dot"; int size = this.lpn.getVarIndexMap().size(); String varNames = ""; for(int i = 0; i < size; i++) { varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i); } varNames = varNames.replaceFirst(", ", ""); BufferedWriter out = new BufferedWriter(new FileWriter(graphFileName)); out.write("digraph G {\n"); out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n"); for (State curState : nextStateMap.keySet()) { String markings = intArrayToString("markings", curState); String vars = intArrayToString("vars", curState); String enabledTrans = boolArrayToString("enabledTrans", curState); String curStateName = "S" + curState.getIndex(); out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n"); } for (State curState : nextStateMap.keySet()) { HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState); for (Transition curTran : stateTransitionPair.keySet()) { String curStateName = "S" + curState.getIndex(); String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex(); String curTranName = curTran.getLabel(); if (curTran.isFail() && !curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n"); else if (!curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n"); else if (curTran.isFail() && curTran.isPersistent()) out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n"); else out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n"); } } out.write("}"); out.close(); } catch (Exception e) { e.printStackTrace(); System.err.println("Error producing local state graph as dot file."); } } protected String intArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("markings")) { for (int i=0; i< curState.getMarking().length; i++) { if (curState.getMarking()[i] == 1) { arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ","; } // String tranName = curState.getLpn().getAllTransitions()[i].getName(); // if (curState.getTranVector()[i]) // System.out.println(tranName + " " + "Enabled"); // else // System.out.println(tranName + " " + "Not Enabled"); } arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } else if (type.equals("vars")) { for (int i=0; i< curState.getVector().length; i++) { arrayStr = arrayStr + curState.getVector()[i] + ","; } if (arrayStr.contains(",")) arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } protected String boolArrayToString(String type, State curState) { String arrayStr = ""; if (type.equals("enabledTrans")) { for (int i=0; i< curState.getTranVector().length; i++) { if (curState.getTranVector()[i]) { arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getLabel() + ","; } } if (arrayStr != "") arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(",")); } return arrayStr; } // private void printTransitionSet(LpnTranList transitionSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + " "); // if (transitionSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { // Transition tranInDisable = curTranIter.next(); // System.out.print(tranInDisable.getName() + " "); // System.out.print("\n"); // private static void printAmpleSet(LpnTranList transitionSet, String setName) { // if (!setName.isEmpty()) // System.out.print(setName + " "); // if (transitionSet.isEmpty()) { // System.out.println("empty"); // else { // for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) { // Transition tranInDisable = curTranIter.next(); // System.out.print(tranInDisable.getName() + " "); // System.out.print("\n"); // public HashMap<State,LpnTranList> copyEnabledSetTbl() { // HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>(); // for (State s : enabledSetTbl.keySet()) { // LpnTranList tranList = enabledSetTbl.get(s).clone(); // copyEnabledSetTbl.put(s.clone(), tranList); // return copyEnabledSetTbl; // public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) { // this.enabledSetTbl = enabledSetTbl; public HashMap<State, LpnTranList> getEnabledSetTbl() { return this.enabledSetTbl; } public HashMap<State, HashMap<Transition, State>> getNextStateMap() { return this.nextStateMap; } /** * Fires a transition for the timed code. * @param curSgArray * The current information on the all local states. * @param currentPrjState * The current state. * @param firedTran * The transition to fire. * @return * The new states. */ public TimedPrjState fire(final StateGraph[] curSgArray, final PrjState currentPrjState, Transition firedTran){ TimedPrjState currentTimedPrjState; // Check that this is a timed state. if(currentPrjState instanceof TimedPrjState){ currentTimedPrjState = (TimedPrjState) currentPrjState; } else{ throw new IllegalArgumentException("Attempted to use the " + "fire(StateGraph[],PrjState,Transition)" + "without a TimedPrjState stored in the PrjState " + "variable. This method is meant for TimedPrjStates."); } // Extract relevant information from the current project state. State[] curStateArray = currentTimedPrjState.toStateArray(); Zone[] currentZones = currentTimedPrjState.toZoneArray(); // Zone[] newZones = new Zone[curStateArray.length]; Zone[] newZones = new Zone[1]; //HashMap<LPNContinuousPair, IntervalPair> newContValues = new HashMap<LPNContinuousPair, IntervalPair>(); // ArrayList<HashMap<LPNContinuousPair, IntervalPair>> newAssignValues = // new ArrayList<HashMap<LPNContinuousPair, IntervalPair>>(); /* * This ArrayList contains four separate maps that store the * rate and continuous variables assignments. */ // ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues = // new ArrayList<HashMap<LPNContAndRate, IntervalPair>>(); // Get the new un-timed local states. State[] newStates = fire(curSgArray, curStateArray, firedTran); // currentTimedPrjState.get_zones()[0]); // State[] newStates = fire(curSgArray, curStateArray, firedTran, newAssignValues, // currentTimedPrjState.get_zones()[0]); // Get the new values from rate assignments and continuous variable // assignments. Also fix the enabled transition markings. // Convert the values of the current marking to strings. This is needed for the evaluator. // HashMap<String, String> valuesAsString = // this.lpn.getAllVarsWithValuesAsString(curStateArray[this.lpn.getLpnIndex()].getVector()); // ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues = // updateContinuousState(currentTimedPrjState.get_zones()[0], valuesAsString, curStateArray, firedTran); ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues = updateContinuousState(currentTimedPrjState.get_zones()[0], curStateArray, newStates, firedTran); LpnTranList enabledTransitions = new LpnTranList(); for(int i=0; i<newStates.length; i++) { // enabledTransitions = getEnabled(newStates[i]); // The stategraph has to be used to call getEnabled // since it is being passed implicitly. LpnTranList localEnabledTransitions = curSgArray[i].getEnabled(newStates[i]); for(int j=0; j<localEnabledTransitions.size(); j++){ enabledTransitions.add(localEnabledTransitions.get(j)); } // newZones[i] = currentZones[i].fire(firedTran, // enabledTransitions, newStates); // Update any continuous variable assignments. // for (this.lpn.get) { // if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) { //// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); //// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; // for(String contVar : this.lpn.getContVars()){ // // Get the new range. // InveralRange range = // this.lpn.getContAssignTree(firedTran.getName(), contVar) // .evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z) } // newZones[0] = currentZones[0].fire(firedTran, // enabledTransitions, newContValues, newStates); newZones[0] = currentZones[0].fire(firedTran, enabledTransitions, newAssignValues, newStates); // ContinuousUtilities.updateInequalities(newZones[0], // newStates[firedTran.getLpn().getLpnIndex()]); // Warp the zone. //newZones[0].dbmWarp(currentTimedPrjState.get_zones()[0]); return new TimedPrjState(newStates, newZones); } /** * Fires a list of events. This list can either contain a single transition * or a set of inequalities. * @param curSgArray * The current information on the all local states. * @param currentPrjState * The current state. * @param eventSets * The set of events to fire. * @return * The new state. */ public TimedPrjState fire(final StateGraph[] curSgArray, final PrjState currentPrjState, EventSet eventSet){ TimedPrjState currentTimedPrjState; // Check that this is a timed state. if(currentPrjState instanceof TimedPrjState){ currentTimedPrjState = (TimedPrjState) currentPrjState; } else{ throw new IllegalArgumentException("Attempted to use the " + "fire(StateGraph[],PrjState,Transition)" + "without a TimedPrjState stored in the PrjState " + "variable. This method is meant for TimedPrjStates."); } // Determine if the list of events represents a list of inequalities. if(eventSet.isInequalities()){ // Create a copy of the current states. State[] oldStates = currentTimedPrjState.getStateArray(); State[] states = new State[oldStates.length]; for(int i=0; i<oldStates.length; i++){ states[i] = oldStates[i].clone(); } // Get the variable index map for getting the indecies // of the variables. DualHashMap<String, Integer> map = lpn.getVarIndexMap(); for(Event e : eventSet){ // Extract inequality variable. InequalityVariable iv = e.getInequalityVariable(); // Get the index to change the value. int variableIndex = map.getValue(iv.getName()); // Flip the value of the inequality. int[] vector = states[this.lpn.getLpnIndex()].getVector(); vector[variableIndex] = vector[variableIndex] == 0 ? 1 : 0; } HashSet<LPNTransitionPair> newlyEnabled = new HashSet<LPNTransitionPair>(); // Update the enabled transitions according to inequalities that have changed. for(int i=0; i<states.length; i++){ boolean[] newEnabledTranVector = updateEnabledTranVector(states[i].getTranVector(), states[i].marking, states[i].vector, null, newlyEnabled); State newState = curSgArray[i].addState(new State(this.lpn, states[i].marking, states[i].vector, newEnabledTranVector)); states[i] = newState; } // Get a new zone that has been restricted according to the inequalities firing. Zone z = currentTimedPrjState.get_zones()[0].getContinuousRestrictedZone(eventSet); // Add any new transitions. z = z.addTransition(newlyEnabled, states); // return new TimedPrjState(states, currentTimedPrjState.get_zones()); return new TimedPrjState(states, new Zone[]{z}); } return fire(curSgArray, currentPrjState, eventSet.getTransition()); } /** * This method handles the extracting of the new rate and continuous variable assignments. * @param z * The previous zone. * @param currentValuesAsString * The current values of the Boolean varaibles converted to strings. * @param oldStates * The current states. * @param firedTran * The fired transition. * @return * The continuous variable and rate assignments. */ // public ArrayList<HashMap<LPNContAndRate, IntervalPair>> // updateContinuousState(Zone z, HashMap<String, String> currentValuesAsString, // State[] states, Transition firedTran){ private ArrayList<HashMap<LPNContAndRate, IntervalPair>> updateContinuousState(Zone z, State[] oldStates, State[] newStates, Transition firedTran){ // Convert the current values of Boolean variables to strings for use in the // Evaluator. HashMap<String, String> currentValuesAsString = this.lpn.getAllVarsWithValuesAsString(oldStates[this.lpn.getLpnIndex()].getVector()); // Accumulates a set of all transitions that need their enabling conditions // re-evaluated. HashSet<Transition> needUpdating = new HashSet<Transition>(); HashSet<InequalityVariable> ineqNeedUpdating= new HashSet<InequalityVariable>(); // Accumulates the new assignment information. ArrayList<HashMap<LPNContAndRate, IntervalPair>> newAssignValues = new ArrayList<HashMap<LPNContAndRate, IntervalPair>>(); // Update rates final int OLD_ZERO = 0; // Case 0 in description. // final int NEW_NON_ZERO = 1; // Case 1 in description. // final int NEW_ZERO = 2; // Case 2 in description. // final int OLD_NON_ZERO = 3; // Case 3 in description. // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); // newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); final int NEW_NON_ZERO = 1; // Case 1 in description. final int NEW_ZERO = 2; // Case 2 in description. final int OLD_NON_ZERO = 3; // Cade 3 in description. if(Options.getTimingAnalysisFlag()){ newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); newAssignValues.add(new HashMap<LPNContAndRate, IntervalPair>()); } for(String key : this.lpn.getContVars()){ // Get the pairing. int lpnIndex = this.lpn.getLpnIndex(); int contVarIndex = this.lpn.getContVarIndex(key); // Package up the indecies. LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); //Integer newRate = null; IntervalPair newRate = null; IntervalPair newValue= null; // Check if there is a new rate assignment. if(this.lpn.getRateAssignTree(firedTran.getLabel(), key) != null){ // Get the new value. //IntervalPair newIntervalRate = this.lpn.getRateAssignTree(firedTran.getName(), key) //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null); newRate = this.lpn.getRateAssignTree(firedTran.getLabel(), key) .evaluateExprBound(currentValuesAsString, z, null); // // Get the pairing. // int lpnIndex = this.lpn.getLpnIndex(); // int contVarIndex = this.lpn.getContVarIndex(key); // // Package up the indecies. // LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); // Keep the current rate. //newRate = newIntervalRate.get_LowerBound(); //contVar.setCurrentRate(newIntervalRate.get_LowerBound()); contVar.setCurrentRate(newRate.get_LowerBound()); // continuousValues.put(contVar, new IntervalPair(z.getDbmEntryByPair(contVar, LPNTransitionPair.ZERO_TIMER_PAIR), // z.getDbmEntryByPair(LPNTransitionPair.ZERO_TIMER_PAIR, contVar))); // // Check if the new assignment gives rate zero. // boolean newRateZero = newRate == 0; // // Check if the variable was already rate zero. // boolean oldRateZero = z.getCurrentRate(contVar) == 0; // // Put the new value in the appropriate set. // if(oldRateZero){ // if(newRateZero){ // // Old rate is zero and the new rate is zero. // newAssignValues.get(OLD_ZERO).put(contVar, newValue); // else{ // // Old rate is zero and the new rate is non-zero. // newAssignValues.get(NEW_NON_ZERO).put(contVar, newValue); // else{ // if(newRateZero){ // // Old rate is non-zero and the new rate is zero. // newAssignValues.get(NEW_ZERO).put(contVar, newValue); // else{ // // Old rate is non-zero and the new rate is non-zero. // newAssignValues.get(OLD_NON_ZERO).put(contVar, newValue); } // Update continuous variables. //for(String key : this.lpn.getContVars()){ // Get the new assignments on the continuous variables and update inequalities. if (this.lpn.getContAssignTree(firedTran.getLabel(), key) != null) { // int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector)); // newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue; // Get the new value. newValue = this.lpn.getContAssignTree(firedTran.getLabel(), key) //.evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z, null); .evaluateExprBound(currentValuesAsString, z, null); // // Get the pairing. // int lpnIndex = this.lpn.getLpnIndex(); // int contVarIndex = this.lpn.getContVarIndex(key); // // Package up the indecies. // LPNContinuousPair contVar = new LPNContinuousPair(lpnIndex, contVarIndex); if(newRate == null){ // Keep the current rate. contVar.setCurrentRate(z.getCurrentRate(contVar)); newRate = z.getRateBounds(contVar); } // continuousValues.put(contVar, newValue); // Get each inequality that involves the continuous variable. ArrayList<InequalityVariable> inequalities = this.lpn.getContVar(contVarIndex).getInequalities(); /* If inequalities is null, create and size size list */ if(inequalities == null){ inequalities = new ArrayList<InequalityVariable>(); } ineqNeedUpdating.addAll(inequalities); // // Update the inequalities. // for(InequalityVariable ineq : inequalities){ // int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName()); // // Add the transitions that this inequality affects. // needUpdating.addAll(ineq.getTransitions()); // HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>(); // continuousValues.putAll(newAssignValues.get(OLD_ZERO)); // continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO)); // continuousValues.putAll(newAssignValues.get(NEW_ZERO)); // continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO)); // // Adjust state vector values for the inequality variables. // int[] newVectorArray = states[this.lpn.getLpnIndex()].getVector(); // newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues); //// newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, null); } if(newValue == null && newRate == null){ // If nothing was set, then nothing needs to be done. continue; } // If the value did not get assigned, put in the old value. if(newValue == null){ newValue = z.getContinuousBounds(contVar); } // If a new rate has not been assigned, put in the old rate. // if(newRate == null){ // newRate = z.getRateBounds(contVar); // Check if the new assignment gives rate zero. //boolean newRateZero = newRate == 0; boolean newRateZero = newRate.singleValue() ? newRate.get_LowerBound() == 0 : false; // Check if the variable was already rate zero. boolean oldRateZero = z.getCurrentRate(contVar) == 0; // Put the new value in the appropriate set. if(oldRateZero){ if(newRateZero){ // Old rate is zero and the new rate is zero. newAssignValues.get(OLD_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); } else{ // Old rate is zero and the new rate is non-zero. newAssignValues.get(NEW_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); } } else{ if(newRateZero){ // Old rate is non-zero and the new rate is zero. newAssignValues.get(NEW_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); } else{ // Old rate is non-zero and the new rate is non-zero. newAssignValues.get(OLD_NON_ZERO).put(new LPNContAndRate(contVar, newRate), newValue); } } } // Update the inequalities. for(InequalityVariable ineq : ineqNeedUpdating){ int ineqIndex = this.lpn.getVarIndexMap().get(ineq.getName()); // Add the transitions that this inequality affects. needUpdating.addAll(ineq.getTransitions()); HashMap<LPNContAndRate, IntervalPair> continuousValues = new HashMap<LPNContAndRate, IntervalPair>(); continuousValues.putAll(newAssignValues.get(OLD_ZERO)); continuousValues.putAll(newAssignValues.get(NEW_NON_ZERO)); continuousValues.putAll(newAssignValues.get(NEW_ZERO)); continuousValues.putAll(newAssignValues.get(OLD_NON_ZERO)); // Adjust state vector values for the inequality variables. // int[] newVectorArray = oldStates[this.lpn.getLpnIndex()].getVector(); int[] newVectorArray = newStates[this.lpn.getLpnIndex()].getVector(); newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, continuousValues); // newVectorArray[ineqIndex] = ineq.evaluate(newVectorArray, z, null); } // Do the re-evaluating of the transitions. for(Transition t : needUpdating){ // Get the index of the LPN and the index of the transition. int lpnIndex = t.getLpn().getLpnIndex(); int tranIndex = t.getIndex(); // Get the enabled vector from the appropriate state. int[] vector = newStates[lpnIndex].getVector(); int[] marking = newStates[lpnIndex].getMarking(); boolean[] previouslyEnabled = newStates[lpnIndex].getTranVector(); // Set the (possibly) new value. // vector[tranIndex] = t.getEnablingTree(). // evaluateExprBound(currentValuesAsString, z, null).get_LowerBound(); boolean needToUpdate = true; String tranName = t.getLabel(); if (this.lpn.getEnablingTree(tranName) != null && this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(vector)) == 0.0) { if (previouslyEnabled[tranIndex] && !t.isPersistent()) previouslyEnabled[tranIndex] = false; continue; } if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) { for (int place : this.lpn.getPresetIndex(tranName)) { if (marking[place]==0) { needToUpdate = false; break; } } } if (needToUpdate) { // if a transition is enabled and it is not recorded in the enabled transition vector previouslyEnabled[tranIndex] = true; } } return newAssignValues; } @Override public String toString() { return "StateGraph [lpn=" + lpn + "]"; } }
package org.intermine.bio.dataconversion; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.SingletonResults; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.util.SAXParser; import org.intermine.util.StringUtil; import org.intermine.xml.full.FullRenderer; import org.intermine.xml.full.Item; import org.intermine.xml.full.ItemFactory; import org.flymine.model.genomic.Publication; import java.io.*; import java.net.URL; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.helpers.DefaultHandler; /** * Class to fill in all publication information from pubmed * @author Mark Woodbridge */ public class EntrezPublicationsRetriever { protected static final Logger LOG = Logger.getLogger(EntrezPublicationsRetriever.class); protected static final String ENDL = System.getProperty("line.separator"); protected static final String ESUMMARY_URL = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?tool=flymine&db=pubmed&id="; // number of summaries to retrieve per request protected static final int BATCH_SIZE = 50; private String osAlias = null; private String outputFile = null; static final String TARGET_NS = "http://www.flymine.org/model/genomic /** * Set the ObjectStore alias. * @param osAlias The ObjectStore alias */ public void setOsAlias(String osAlias) { this.osAlias = osAlias; } /** * Set the output file name * @param outputFile The output file name */ public void setOutputFile(String outputFile) { this.outputFile = outputFile; } /** * Synchronize publications with pubmed using pmid * @throws Exception if an error occurs */ public void execute() throws Exception { // Needed so that STAX can find it's implementation classes ClassLoader cl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); if (osAlias == null) { throw new BuildException("osAlias attribute is not set"); } if (outputFile == null) { throw new BuildException("outputFile attribute is not set"); } LOG.info("Starting EntrezPublicationsRetriever"); Writer writer = null; try { writer = new FileWriter(outputFile); ObjectStore os = ObjectStoreFactory.getObjectStore(osAlias); Set pubMedIds = new HashSet(); Set toStore = new HashSet(); ItemFactory itemFactory = new ItemFactory(os.getModel(), "-1_"); writer.write(FullRenderer.getHeader() + ENDL); for (Iterator i = getPublications(os).iterator(); i.hasNext();) { pubMedIds.add(((Publication) i.next()).getPubMedId()); if (pubMedIds.size() == BATCH_SIZE || !i.hasNext()) { SAXParser.parse(new InputSource(getReader(pubMedIds)), new Handler(toStore, itemFactory)); for (Iterator j = toStore.iterator(); j.hasNext();) { writer.write(FullRenderer.render((Item) j.next())); } pubMedIds.clear(); toStore.clear(); } } writer.write(FullRenderer.getFooter() + ENDL); writer.flush(); writer.close(); } finally { Thread.currentThread().setContextClassLoader(cl); } } /** * Retrieve the publications to be updated * @param os The ObjectStore to read from * @return a List of publications */ protected List getPublications(ObjectStore os) { Query q = new Query(); QueryClass qc = new QueryClass(Publication.class); q.addFrom(qc); q.addToSelect(qc); return new SingletonResults(q, os, os.getSequence()); } /** * Obtain the pubmed esummary information for the publications * @param ids the pubMedIds of the publications * @return a Reader for the information * @throws Exception if an error occurs */ protected Reader getReader(Set ids) throws Exception { String urlString = ESUMMARY_URL + StringUtil.join(ids, ","); System. err.println("retrieving: " + urlString); return new BufferedReader(new InputStreamReader(new URL(urlString).openStream())); } /** * Extension of DefaultHandler to handle an esummary for a publication */ class Handler extends DefaultHandler { Set toStore; Item publication; String name; StringBuffer characters; ItemFactory itemFactory; /** * Constructor * @param toStore a set in which the new publication items are stored * @param itemFactory the factory */ public Handler(Set toStore, ItemFactory itemFactory) { this.toStore = toStore; this.itemFactory = itemFactory; } /** * @see DefaultHandler#startElement(String, String, String, Attributes) */ public void startElement(String uri, String localName, String qName, Attributes attrs) { if ("ERROR".equals(qName)) { name = qName; } else if ("Id".equals(qName)) { name = "Id"; } else { name = attrs.getValue("Name"); } characters = new StringBuffer(); } /** * @see DefaultHandler#characters(char[], int, int) */ public void characters(char[] ch, int start, int length) { characters.append(new String(ch, start, length)); } /** * @see DefaultHandler#endElement(String, String, String) */ public void endElement(String uri, String localName, String qName) { if ("ERROR".equals(name)) { LOG.error("Unable to retrieve pubmed record: " + characters); } else if ("Id".equals(name)) { publication = itemFactory.makeItemForClass(TARGET_NS + "Publication"); toStore.add(publication); publication.setAttribute("pubMedId", characters.toString()); } else if ("PubDate".equals(name)) { String year = characters.toString().split(" ")[0]; try { Integer.parseInt(year); publication.setAttribute("year", year); } catch (NumberFormatException e) { LOG.warn("Publication: " + publication + " has a year that cannot be parsed" + " to an Integer: " + year); } } else if ("Source".equals(name)) { publication.setAttribute("journal", characters.toString()); } else if ("Title".equals(name)) { publication.setAttribute("title", characters.toString()); } else if ("Volume".equals(name)) { publication.setAttribute("volume", characters.toString()); } else if ("Issue".equals(name)) { publication.setAttribute("issue", characters.toString()); } else if ("Pages".equals(name)) { publication.setAttribute("pages", characters.toString()); } else if ("Author".equals(name)) { Item author = itemFactory.makeItemForClass(TARGET_NS + "Author"); toStore.add(author); String authorString = characters.toString(); author.setAttribute("name", authorString); author.addToCollection("publications", publication); publication.addToCollection("authors", author); if (!publication.hasAttribute("firstAuthor")) { publication.setAttribute("firstAuthor", authorString); } } name = null; } } }
package org.pentaho.di.ui.spoon.trans; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.StringTokenizer; import java.util.Timer; import java.util.TimerTask; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabItem; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.MouseTrackListener; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Canvas; 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.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.eclipse.swt.widgets.Widget; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.Props; import org.pentaho.di.core.dnd.DragAndDropContainer; import org.pentaho.di.core.dnd.XMLTransfer; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.gui.AreaOwner; import org.pentaho.di.core.gui.BasePainter; import org.pentaho.di.core.gui.GCInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.Redrawable; import org.pentaho.di.core.gui.SnapAllignDistribute; import org.pentaho.di.core.logging.CentralLogStore; import org.pentaho.di.core.logging.HasLogChannelInterface; import org.pentaho.di.core.logging.Log4jKettleLayout; import org.pentaho.di.core.logging.LogChannelInterface; import org.pentaho.di.core.logging.LogParentProvidedInterface; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.core.logging.LoggingRegistry; import org.pentaho.di.core.plugins.PluginInterface; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.core.plugins.StepPluginType; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.lineage.TransDataLineage; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryLock; import org.pentaho.di.repository.RepositoryObjectType; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransExecutionConfiguration; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransListener; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransPainter; import org.pentaho.di.trans.debug.BreakPointListener; import org.pentaho.di.trans.debug.StepDebugMeta; import org.pentaho.di.trans.debug.TransDebugMeta; import org.pentaho.di.trans.step.RemoteStep; import org.pentaho.di.trans.step.RowListener; import org.pentaho.di.trans.step.StepErrorMeta; import org.pentaho.di.trans.step.StepIOMetaInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.errorhandling.Stream; import org.pentaho.di.trans.step.errorhandling.StreamIcon; import org.pentaho.di.trans.step.errorhandling.StreamInterface; import org.pentaho.di.trans.step.errorhandling.StreamInterface.StreamType; import org.pentaho.di.trans.steps.mapping.MappingMeta; import org.pentaho.di.trans.steps.tableinput.TableInputMeta; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.dialog.EnterNumberDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.dialog.PreviewRowsDialog; import org.pentaho.di.ui.core.dialog.StepFieldsDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.widget.CheckBoxToolTip; import org.pentaho.di.ui.core.widget.CheckBoxToolTipListener; import org.pentaho.di.ui.repository.dialog.RepositoryExplorerDialog; import org.pentaho.di.ui.repository.dialog.RepositoryRevisionBrowserDialogInterface; import org.pentaho.di.ui.spoon.AbstractChangedWarningDialog; import org.pentaho.di.ui.spoon.AbstractGraph; import org.pentaho.di.ui.spoon.ChangedWarningInterface; import org.pentaho.di.ui.spoon.SWTGC; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.spoon.SpoonPluginManager; import org.pentaho.di.ui.spoon.SwtScrollBar; import org.pentaho.di.ui.spoon.TabItemInterface; import org.pentaho.di.ui.spoon.XulSpoonResourceBundle; import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox; import org.pentaho.di.ui.spoon.dialog.EnterPreviewRowsDialog; import org.pentaho.di.ui.spoon.dialog.NotePadDialog; import org.pentaho.di.ui.spoon.dialog.SearchFieldsProgressDialog; import org.pentaho.di.ui.trans.dialog.TransDialog; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.XulException; import org.pentaho.ui.xul.XulLoader; import org.pentaho.ui.xul.components.XulMenuitem; import org.pentaho.ui.xul.components.XulToolbarbutton; import org.pentaho.ui.xul.containers.XulMenu; import org.pentaho.ui.xul.containers.XulMenupopup; import org.pentaho.ui.xul.containers.XulToolbar; import org.pentaho.ui.xul.dom.Document; import org.pentaho.ui.xul.impl.XulEventHandler; import org.pentaho.ui.xul.swt.SwtXulLoader; /** * This class handles the display of the transformations in a graphical way using icons, arrows, etc. * One transformation is handled per TransGraph * * @author Matt * @since 17-mei-2003 * */ public class TransGraph extends AbstractGraph implements XulEventHandler, Redrawable, TabItemInterface, LogParentProvidedInterface, MouseListener, MouseMoveListener, MouseTrackListener, MouseWheelListener, KeyListener { private static Class<?> PKG = Spoon.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private LogChannelInterface log; private static final int HOP_SEL_MARGIN = 9; private static final String XUL_FILE_TRANS_TOOLBAR = "ui/trans-toolbar.xul"; //$NON-NLS-1$ public final static String START_TEXT = BaseMessages.getString(PKG, "TransLog.Button.StartTransformation"); //$NON-NLS-1$ public final static String PAUSE_TEXT = BaseMessages.getString(PKG, "TransLog.Button.PauseTransformation"); //$NON-NLS-1$ public final static String RESUME_TEXT = BaseMessages.getString(PKG, "TransLog.Button.ResumeTransformation"); //$NON-NLS-1$ public final static String STOP_TEXT = BaseMessages.getString(PKG, "TransLog.Button.StopTransformation"); //$NON-NLS-1$ private TransMeta transMeta; public Trans trans; private Shell shell; private Composite mainComposite; private DefaultToolTip toolTip; private CheckBoxToolTip helpTip; private XulToolbar toolbar; private int iconsize; private Point lastclick; private Point lastMove; private Point previous_step_locations[]; private Point previous_note_locations[]; private List<StepMeta> selectedSteps; private StepMeta selectedStep; private List<StepMeta> mouseOverSteps; private List<NotePadMeta> selectedNotes; private NotePadMeta selectedNote; private TransHopMeta candidate; private Point drop_candidate; private Spoon spoon; // public boolean shift, control; private boolean split_hop; private int lastButton; private TransHopMeta last_hop_split; private org.pentaho.di.core.gui.Rectangle selectionRegion; /** * A list of remarks on the current Transformation... */ private List<CheckResultInterface> remarks; /** * A list of impacts of the current transformation on the used databases. */ private List<DatabaseImpact> impact; /** * Indicates whether or not an impact analysis has already run. */ private boolean impactFinished; private TransHistoryRefresher spoonHistoryRefresher; private TransDebugMeta lastTransDebugMeta; private Map<String, XulMenupopup> menuMap = new HashMap<String, XulMenupopup>(); protected int currentMouseX = 0; protected int currentMouseY = 0; protected NotePadMeta ni = null; protected TransHopMeta currentHop; protected StepMeta currentStep; private List<AreaOwner> areaOwners; // private Text filenameLabel; private SashForm sashForm; public Composite extraViewComposite; public CTabFolder extraViewTabFolder; private boolean initialized; private boolean running; private boolean halted; private boolean halting; private boolean debug; private boolean pausing; public TransLogDelegate transLogDelegate; public TransGridDelegate transGridDelegate; public TransHistoryDelegate transHistoryDelegate; public TransPerfDelegate transPerfDelegate; /** A map that keeps track of which log line was written by which step */ private Map<StepMeta, String> stepLogMap; private StepMeta startHopStep; private Point endHopLocation; private boolean startErrorHopStep; private StepMeta noInputStep; private StepMeta endHopStep; private StreamType candidateHopType; private Map<StepMeta, DelayTimer> delayTimers; private StepMeta showTargetStreamsStep; private XulDomContainer xulDomContainer; public void setCurrentNote(NotePadMeta ni) { this.ni = ni; } public NotePadMeta getCurrentNote() { return ni; } public TransHopMeta getCurrentHop() { return currentHop; } public void setCurrentHop(TransHopMeta currentHop) { this.currentHop = currentHop; } public StepMeta getCurrentStep() { return currentStep; } public void setCurrentStep(StepMeta currentStep) { this.currentStep = currentStep; } public TransGraph(Composite parent, final Spoon spoon, final TransMeta transMeta) { super(parent, SWT.NONE); this.shell = parent.getShell(); this.spoon = spoon; this.transMeta = transMeta; this.areaOwners = new ArrayList<AreaOwner>(); this.log = spoon.getLog(); this.mouseOverSteps = new ArrayList<StepMeta>(); this.delayTimers = new HashMap<StepMeta, DelayTimer>(); transLogDelegate = new TransLogDelegate(spoon, this); transGridDelegate = new TransGridDelegate(spoon, this); transHistoryDelegate = new TransHistoryDelegate(spoon, this); transPerfDelegate = new TransPerfDelegate(spoon, this); try { XulLoader loader = new SwtXulLoader(); ResourceBundle bundle = new XulSpoonResourceBundle(Spoon.class); XulDomContainer container = loader.loadXul(XUL_FILE_TRANS_TOOLBAR, bundle); container.addEventHandler(this); SpoonPluginManager.getInstance().applyPluginsForContainer("trans-graph", xulDomContainer); setXulDomContainer(container); } catch (XulException e1) { log.logError(toString(), Const.getStackTracker(e1)); } setLayout(new FormLayout()); setLayoutData(new GridData(GridData.FILL_BOTH)); // Add a tool-bar at the top of the tab // The form-data is set on the native widget automatically addToolBar(); setControlStates(); // enable / disable the icons in the toolbar too. // The main composite contains the graph view, but if needed also // a view with an extra tab containing log, etc. mainComposite = new Composite(this, SWT.NONE); mainComposite.setLayout(new FillLayout()); Control toolbarControl = (Control) toolbar.getManagedObject(); FormData toolbarFd = new FormData(); toolbarFd.left = new FormAttachment(0, 0); toolbarFd.right = new FormAttachment(100, 0); toolbarControl.setLayoutData(toolbarFd); toolbarControl.setParent(this); FormData fdMainComposite = new FormData(); fdMainComposite.left = new FormAttachment(0, 0); fdMainComposite.top = new FormAttachment((Control) toolbar.getManagedObject(), 0); fdMainComposite.right = new FormAttachment(100, 0); fdMainComposite.bottom = new FormAttachment(100, 0); mainComposite.setLayoutData(fdMainComposite); // To allow for a splitter later on, we will add the splitter here... sashForm = new SashForm(mainComposite, SWT.VERTICAL); // Add a canvas below it, use up all space initially canvas = new Canvas(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER); sashForm.setWeights(new int[] { 100, }); try { // first get the XML document menuMap.put("trans-graph-hop", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-hop")); //$NON-NLS-1$ //$NON-NLS-2$ menuMap.put("trans-graph-entry", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-entry")); //$NON-NLS-1$//$NON-NLS-2$ menuMap.put("trans-graph-background", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-background")); //$NON-NLS-1$//$NON-NLS-2$ menuMap.put("trans-graph-note", (XulMenupopup) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-note")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Throwable t) { // TODO log this t.printStackTrace(); } toolTip = new DefaultToolTip(canvas, ToolTip.NO_RECREATE, true); toolTip.setRespectMonitorBounds(true); toolTip.setRespectDisplayBounds(true); toolTip.setPopupDelay(350); toolTip.setShift(new org.eclipse.swt.graphics.Point(ConstUI.TOOLTIP_OFFSET, ConstUI.TOOLTIP_OFFSET)); helpTip = new CheckBoxToolTip(canvas); helpTip.addCheckBoxToolTipListener(new CheckBoxToolTipListener() { public void checkBoxSelected(boolean enabled) { spoon.props.setShowingHelpToolTips(enabled); } }); iconsize = spoon.props.getIconSize(); clearSettings(); remarks = new ArrayList<CheckResultInterface>(); impact = new ArrayList<DatabaseImpact>(); impactFinished = false; hori = canvas.getHorizontalBar(); vert = canvas.getVerticalBar(); hori.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { redraw(); } }); vert.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { redraw(); } }); hori.setThumb(100); vert.setThumb(100); hori.setVisible(true); vert.setVisible(true); setVisible(true); newProps(); canvas.setBackground(GUIResource.getInstance().getColorBackground()); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (!spoon.isStopped()) TransGraph.this.paintControl(e); } }); selectedSteps = null; lastclick = null; /* * Handle the mouse... */ canvas.addMouseListener(this); canvas.addMouseMoveListener(this); canvas.addMouseTrackListener(this); canvas.addMouseWheelListener(this); canvas.addKeyListener(this); // Drag & Drop for steps Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() }; DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE); ddTarget.setTransfer(ttypes); ddTarget.addDropListener(new DropTargetListener() { public void dragEnter(DropTargetEvent event) { clearSettings(); drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y)); redraw(); } public void dragLeave(DropTargetEvent event) { drop_candidate = null; redraw(); } public void dragOperationChanged(DropTargetEvent event) { } public void dragOver(DropTargetEvent event) { drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y)); redraw(); } public void drop(DropTargetEvent event) { // no data to copy, indicate failure in event.detail if (event.data == null) { event.detail = DND.DROP_NONE; return; } // System.out.println("Dropping a step!!"); // What's the real drop position? Point p = getRealPosition(canvas, event.x, event.y); // We expect a Drag and Drop container... (encased in XML) try { DragAndDropContainer container = (DragAndDropContainer) event.data; StepMeta stepMeta = null; boolean newstep = false; switch (container.getType()) { // Put an existing one on the canvas. case DragAndDropContainer.TYPE_STEP: { // Drop hidden step onto canvas.... stepMeta = transMeta.findStep(container.getData()); if (stepMeta != null) { if (stepMeta.isDrawn() || transMeta.isStepUsedInTransHops(stepMeta)) { MessageBox mb = new MessageBox(shell, SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.StepIsAlreadyOnCanvas.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.StepIsAlreadyOnCanvas.Title")); //$NON-NLS-1$ mb.open(); return; } // This step gets the drawn attribute and position set below. } else { // Unknown step dropped: ignore this to be safe! return; } } break; // Create a new step case DragAndDropContainer.TYPE_BASE_STEP_TYPE: { // Not an existing step: data refers to the type of step to create String steptype = container.getData(); stepMeta = spoon.newStep(transMeta, steptype, steptype, false, true); if (stepMeta != null) { newstep = true; } else { return; // Cancelled pressed in dialog or unable to create step. } } break; // Create a new TableInput step using the selected connection... case DragAndDropContainer.TYPE_DATABASE_CONNECTION: { newstep = true; String connectionName = container.getData(); TableInputMeta tii = new TableInputMeta(); tii.setDatabaseMeta(transMeta.findDatabase(connectionName)); PluginRegistry registry = PluginRegistry.getInstance(); String stepID = registry.getPluginId(StepPluginType.class, tii); PluginInterface stepPlugin = registry.findPluginWithId(StepPluginType.class, stepID); String stepName = transMeta.getAlternativeStepname(stepPlugin.getName()); stepMeta = new StepMeta(stepID, stepName, tii); if (spoon.editStep(transMeta, stepMeta) != null) { transMeta.addStep(stepMeta); spoon.refreshTree(); spoon.refreshGraph(); } else { return; } } break; // Drag hop on the canvas: create a new Hop... case DragAndDropContainer.TYPE_TRANS_HOP: { newHop(); return; } default: { // Nothing we can use: give an error! MessageBox mb = new MessageBox(shell, SWT.OK); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Title")); //$NON-NLS-1$ mb.open(); return; } } transMeta.unselectAll(); StepMeta before = null; if (!newstep) { before= (StepMeta) stepMeta.clone(); } stepMeta.drawStep(); stepMeta.setSelected(true); PropsUI.setLocation(stepMeta, p.x, p.y); if (newstep) { spoon.addUndoNew(transMeta, new StepMeta[] { stepMeta }, new int[] { transMeta.indexOfStep(stepMeta) }); } else { spoon.addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { (StepMeta) stepMeta.clone() }, new int[] { transMeta.indexOfStep(stepMeta) }); } canvas.forceFocus(); redraw(); // See if we want to draw a tool tip explaining how to create new hops... if (newstep && transMeta.nrSteps() > 1 && transMeta.nrSteps() < 5 && spoon.props.isShowingHelpToolTips()) { showHelpTip(p.x, p.y, BaseMessages.getString(PKG, "TransGraph.HelpToolTip.CreatingHops.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "TransGraph.HelpToolTip.CreatingHops.Message")); //$NON-NLS-1$ } } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDroppingObject.Message"), //$NON-NLS-1$ BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDroppingObject.Title"), e); //$NON-NLS-1$ } } public void dropAccept(DropTargetEvent event) { } }); setBackground(GUIResource.getInstance().getColorBackground()); // Add a timer to set correct the state of the run/stop buttons every 2 seconds... final Timer timer = new Timer(); TimerTask timerTask = new TimerTask() { public void run() { setControlStates(); } }; timer.schedule(timerTask, 2000, 1000); // Make sure the timer stops when we close the tab... addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent arg0) { timer.cancel(); } }); } public void mouseDoubleClick(MouseEvent e) { clearSettings(); Point real = screen2real(e.x, e.y); // Hide the tooltip! hideToolTips(); StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null) { if (e.button == 1) { editStep(stepMeta); } else { editDescription(stepMeta); } } else { // Check if point lies on one of the many hop-lines... TransHopMeta online = findHop(real.x, real.y); if (online != null) { editHop(online); } else { NotePadMeta ni = transMeta.getNote(real.x, real.y); if (ni != null) { selectedNote = null; editNote(ni); } else { // See if the double click was in one of the area's... for (AreaOwner areaOwner : areaOwners) { if (areaOwner.contains(real.x, real.y)) { if (areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_PARTITIONING_CURRENT_STEP)) { StepMeta step = (StepMeta) areaOwner.getParent(); spoon.editPartitioning(transMeta, step); break; } } } } } } } public void mouseDown(MouseEvent e) { boolean alt = (e.stateMask & SWT.ALT) != 0; boolean control = (e.stateMask & SWT.CONTROL) != 0; boolean shift = (e.stateMask & SWT.SHIFT) != 0; lastButton = e.button; Point real = screen2real(e.x, e.y); lastclick = new Point(real.x, real.y); // Hide the tooltip! hideToolTips(); // Set the pop-up menu if (e.button == 3) { setMenu(real.x, real.y); return; } // A single left click on one of the area owners... if (e.button == 1) { AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y); if (areaOwner != null) { switch (areaOwner.getAreaType()) { case STEP_OUTPUT_HOP_ICON: // Click on the output icon means: start of drag // Action: We show the input icons on the other steps... { selectedStep = null; startHopStep = (StepMeta) areaOwner.getParent(); candidateHopType = null; startErrorHopStep = false; // stopStepMouseOverDelayTimer(startHopStep); } break; case STEP_INPUT_HOP_ICON: // Click on the input icon means: start to a new hop // In this case, we set the end hop step... { selectedStep = null; startHopStep = null; endHopStep = (StepMeta) areaOwner.getParent(); candidateHopType = null; startErrorHopStep = false; // stopStepMouseOverDelayTimer(endHopStep); } break; case HOP_ERROR_ICON: // Click on the error icon means: Edit error handling { StepMeta stepMeta = (StepMeta) areaOwner.getParent(); spoon.editStepErrorHandling(transMeta, stepMeta); } break; case STEP_TARGET_HOP_ICON_OPTION: // Below, see showStepTargetOptions() break; case STEP_EDIT_ICON: { clearSettings(); currentStep = (StepMeta) areaOwner.getParent(); stopStepMouseOverDelayTimer(currentStep); editStep(); } break; case STEP_MENU_ICON: clearSettings(); StepMeta stepMeta = (StepMeta) areaOwner.getParent(); setMenu(stepMeta.getLocation().x, stepMeta.getLocation().y); break; case STEP_ICON : stepMeta = (StepMeta) areaOwner.getOwner(); currentStep = stepMeta; if (candidate != null) { addCandidateAsHop(e.x, e.y); } // ALT-Click: edit error handling if (e.button == 1 && alt && stepMeta.supportsErrorHandling()) { spoon.editStepErrorHandling(transMeta, stepMeta); return; } // SHIFT CLICK is start of drag to create a new hop else if (e.button == 2 || (e.button == 1 && shift)) { startHopStep = stepMeta; } else { selectedSteps = transMeta.getSelectedSteps(); selectedStep = stepMeta; // When an icon is moved that is not selected, it gets // selected too late. // It is not captured here, but in the mouseMoveListener... previous_step_locations = transMeta.getSelectedStepLocations(); Point p = stepMeta.getLocation(); iconoffset = new Point(real.x - p.x, real.y - p.y); } redraw(); break; case NOTE: ni = (NotePadMeta) areaOwner.getOwner(); selectedNotes = transMeta.getSelectedNotes(); selectedNote = ni; Point loc = ni.getLocation(); previous_note_locations = transMeta.getSelectedNoteLocations(); noteoffset = new Point(real.x - loc.x, real.y - loc.y); redraw(); break; } } else { // No area-owner means: background: startHopStep = null; if (!control) { selectionRegion = new org.pentaho.di.core.gui.Rectangle(real.x, real.y, 0, 0); } redraw(); } } } public void mouseUp(MouseEvent e) { boolean control = (e.stateMask & SWT.CONTROL) != 0; if (iconoffset == null) iconoffset = new Point(0, 0); Point real = screen2real(e.x, e.y); Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y); AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y); // Quick new hop option? (drag from one step to another) if (candidate != null && areaOwner!=null) { switch(areaOwner.getAreaType()) { case STEP_ICON : currentStep = (StepMeta) areaOwner.getOwner(); break; case STEP_INPUT_HOP_ICON : currentStep = (StepMeta) areaOwner.getParent(); break; } addCandidateAsHop(e.x, e.y); redraw(); } // Did we select a region on the screen? Mark steps in region as // selected else { if (selectionRegion != null) { selectionRegion.width = real.x - selectionRegion.x; selectionRegion.height = real.y - selectionRegion.y; transMeta.unselectAll(); selectInRect(transMeta, selectionRegion); selectionRegion = null; stopStepMouseOverDelayTimers(); redraw(); } // Clicked on an icon? else { if (selectedStep != null && startHopStep==null) { if (e.button == 1) { Point realclick = screen2real(e.x, e.y); if (lastclick.x == realclick.x && lastclick.y == realclick.y) { // Flip selection when control is pressed! if (control) { selectedStep.flipSelected(); } else { // Otherwise, select only the icon clicked on! transMeta.unselectAll(); selectedStep.setSelected(true); } } else { // Find out which Steps & Notes are selected selectedSteps = transMeta.getSelectedSteps(); selectedNotes = transMeta.getSelectedNotes(); // We moved around some items: store undo info... boolean also = false; if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) { int indexes[] = transMeta.getNoteIndexes(selectedNotes); addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, transMeta .getSelectedNoteLocations(), also); also = selectedSteps != null && selectedSteps.size() > 0; } if (selectedSteps != null && previous_step_locations != null) { int indexes[] = transMeta.getStepIndexes(selectedSteps); addUndoPosition(selectedSteps.toArray(new StepMeta[selectedSteps.size()]), indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also); } } } // OK, we moved the step, did we move it across a hop? // If so, ask to split the hop! if (split_hop) { TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep); if (hi != null) { int id = 0; if (!spoon.props.getAutoSplit()) { MessageDialogWithToggle md = new MessageDialogWithToggle( shell, BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Title"), null, //$NON-NLS-1$ BaseMessages.getString(PKG, "TransGraph.Dialog.SplitHop.Message") + Const.CR + hi.toString(), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$ BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, 0, BaseMessages.getString(PKG, "TransGraph.Dialog.Option.SplitHop.DoNotAskAgain"), spoon.props.getAutoSplit()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ MessageDialogWithToggle.setDefaultImage(GUIResource.getInstance().getImageSpoon()); id = md.open(); spoon.props.setAutoSplit(md.getToggleState()); } if ((id & 0xFF) == 0) // Means: "Yes" button clicked! { // Only split A-->--B by putting C in between IF... // C-->--A or B-->--C don't exists... // A ==> hi.getFromStep() // B ==> hi.getToStep(); // C ==> selected_step if (transMeta.findTransHop(selectedStep, hi.getFromStep()) == null && transMeta.findTransHop(hi.getToStep(), selectedStep) == null) { TransHopMeta newhop1 = new TransHopMeta(hi.getFromStep(), selectedStep); transMeta.addTransHop(newhop1); spoon.addUndoNew(transMeta, new TransHopMeta[] { newhop1 }, new int[] { transMeta.indexOfTransHop(newhop1) }, true); TransHopMeta newhop2 = new TransHopMeta(selectedStep, hi.getToStep()); transMeta.addTransHop(newhop2); spoon.addUndoNew(transMeta, new TransHopMeta[] { newhop2 }, new int[] { transMeta.indexOfTransHop(newhop2) }, true); int idx = transMeta.indexOfTransHop(hi); spoon.addUndoDelete(transMeta, new TransHopMeta[] { hi }, new int[] { idx }, true); transMeta.removeTransHop(idx); spoon.refreshTree(); } else { // Silently discard this hop-split attempt. } } } split_hop = false; } selectedSteps = null; selectedNotes = null; selectedStep = null; selectedNote = null; startHopStep = null; endHopLocation = null; redraw(); } // Notes? else { if (selectedNote != null) { if (e.button == 1) { if (lastclick.x == e.x && lastclick.y == e.y) { // Flip selection when control is pressed! if (control) { selectedNote.flipSelected(); } else { // Otherwise, select only the note clicked on! transMeta.unselectAll(); selectedNote.setSelected(true); } } else { // Find out which Steps & Notes are selected selectedSteps = transMeta.getSelectedSteps(); selectedNotes = transMeta.getSelectedNotes(); // We moved around some items: store undo info... boolean also = false; if (selectedNotes != null && selectedNotes.size() > 0 && previous_note_locations != null) { int indexes[] = transMeta.getNoteIndexes(selectedNotes); addUndoPosition(selectedNotes.toArray(new NotePadMeta[selectedNotes.size()]), indexes, previous_note_locations, transMeta.getSelectedNoteLocations(), also); also = selectedSteps != null && selectedSteps.size() > 0; } if (selectedSteps != null && selectedSteps.size() > 0 && previous_step_locations != null) { int indexes[] = transMeta.getStepIndexes(selectedSteps); addUndoPosition(selectedSteps.toArray(new StepMeta[selectedSteps.size()]), indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also); } } } selectedNotes = null; selectedSteps = null; selectedStep = null; selectedNote = null; startHopStep = null; endHopLocation = null; } else { if (areaOwner==null && selectionRegion==null) { // Hit absolutely nothing: clear the settings clearSettings(); } } } } } lastButton = 0; } public void mouseMove(MouseEvent e) { boolean shift = (e.stateMask & SWT.SHIFT) != 0; noInputStep = null; // disable the tooltip toolTip.hide(); // Remember the last position of the mouse for paste with keyboard lastMove = new Point(e.x, e.y); Point real = screen2real(e.x, e.y); if (iconoffset == null) { iconoffset = new Point(0, 0); } Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y); if (noteoffset == null) { noteoffset = new Point(0, 0); } Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y); // Moved over an area? AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y); if (areaOwner!=null) { switch (areaOwner.getAreaType()) { case STEP_ICON : { StepMeta stepMeta = (StepMeta) areaOwner.getOwner(); resetDelayTimer(stepMeta); } break; case MINI_ICONS_BALLOON : // Give the timer a bit more time { StepMeta stepMeta = (StepMeta)areaOwner.getParent(); resetDelayTimer(stepMeta); } break; default: break; } } // First see if the icon we clicked on was selected. // If the icon was not selected, we should un-select all other // icons, selected and move only the one icon if (selectedStep != null && !selectedStep.isSelected()) { transMeta.unselectAll(); selectedStep.setSelected(true); selectedSteps = new ArrayList<StepMeta>(); selectedSteps.add(selectedStep); previous_step_locations = new Point[] { selectedStep.getLocation() }; redraw(); } else if (selectedNote != null && !selectedNote.isSelected()) { transMeta.unselectAll(); selectedNote.setSelected(true); selectedNotes = new ArrayList<NotePadMeta>(); selectedNotes.add(selectedNote); previous_note_locations = new Point[] { selectedNote.getLocation() }; redraw(); } // Did we select a region...? else if (selectionRegion != null && startHopStep==null) { selectionRegion.width = real.x - selectionRegion.x; selectionRegion.height = real.y - selectionRegion.y; redraw(); } // Move around steps & notes else if (selectedStep != null && lastButton == 1 && !shift && startHopStep==null) { /* * One or more icons are selected and moved around... * * new : new position of the ICON (not the mouse pointer) dx : difference with previous * position */ int dx = icon.x - selectedStep.getLocation().x; int dy = icon.y - selectedStep.getLocation().y; // See if we have a hop-split candidate TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selectedStep); if (hi != null) { // OK, we want to split the hop in 2 if (!hi.getFromStep().equals(selectedStep) && !hi.getToStep().equals(selectedStep)) { split_hop = true; last_hop_split = hi; hi.split = true; } } else { if (last_hop_split != null) { last_hop_split.split = false; last_hop_split = null; split_hop = false; } } selectedNotes = transMeta.getSelectedNotes(); selectedSteps = transMeta.getSelectedSteps(); // Adjust location of selected steps... if (selectedSteps != null) { for (int i = 0; i < selectedSteps.size(); i++) { StepMeta stepMeta = selectedSteps.get(i); PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy); stopStepMouseOverDelayTimer(stepMeta); } } // Adjust location of selected hops... if (selectedNotes != null) { for (int i = 0; i < selectedNotes.size(); i++) { NotePadMeta ni = selectedNotes.get(i); PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy); } } redraw(); } // Are we creating a new hop with the middle button or pressing SHIFT? else if ((startHopStep!=null && endHopStep==null) || (endHopStep!=null && startHopStep==null)) { StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); endHopLocation = new Point(real.x, real.y); if (stepMeta != null && ((startHopStep!=null && !startHopStep.equals(stepMeta)) || (endHopStep!=null && !endHopStep.equals(stepMeta))) ) { StepIOMetaInterface ioMeta = stepMeta.getStepMetaInterface().getStepIOMeta(); if (candidate == null) { // See if the step accepts input. If not, we can't create a new hop... if (startHopStep!=null) { if (ioMeta.isInputAcceptor()) { candidate = new TransHopMeta(startHopStep, stepMeta); endHopLocation=null; } else { noInputStep=stepMeta; toolTip.setImage(null); toolTip.setText("This step does not accept any input from other steps"); //$NON-NLS-1$ toolTip.show(new org.eclipse.swt.graphics.Point(real.x, real.y)); } } else if (endHopStep!=null) { if (ioMeta.isOutputProducer()) { candidate = new TransHopMeta(stepMeta, endHopStep); endHopLocation=null; } else { noInputStep=stepMeta; toolTip.setImage(null); toolTip.setText("This step doesn't pass any output to other steps. (except perhaps for targetted output)"); //$NON-NLS-1$ toolTip.show(new org.eclipse.swt.graphics.Point(real.x, real.y)); } } } } else { if (candidate != null) { candidate = null; redraw(); } } redraw(); } // Move around notes & steps if (selectedNote != null) { if (lastButton == 1 && !shift) { /* * One or more notes are selected and moved around... * * new : new position of the note (not the mouse pointer) dx : difference with previous * position */ int dx = note.x - selectedNote.getLocation().x; int dy = note.y - selectedNote.getLocation().y; selectedNotes = transMeta.getSelectedNotes(); selectedSteps = transMeta.getSelectedSteps(); // Adjust location of selected steps... if (selectedSteps != null) for (int i = 0; i < selectedSteps.size(); i++) { StepMeta stepMeta = selectedSteps.get(i); PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy); } // Adjust location of selected hops... if (selectedNotes != null) for (int i = 0; i < selectedNotes.size(); i++) { NotePadMeta ni = selectedNotes.get(i); PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy); } redraw(); } } } public void mouseHover(MouseEvent e) { boolean tip = true; toolTip.hide(); Point real = screen2real(e.x, e.y); AreaOwner areaOwner = getVisibleAreaOwner(real.x, real.y); if (areaOwner!=null) { switch (areaOwner.getAreaType()) { case STEP_ICON : StepMeta stepMeta = (StepMeta) areaOwner.getOwner(); if (!mouseOverSteps.contains(stepMeta)) { addStepMouseOverDelayTimer(stepMeta); redraw(); tip=false; } break; } } if (tip) { // Show a tool tip upon mouse-over of an object on the canvas if (!helpTip.isVisible()) { setToolTip(real.x, real.y, e.x, e.y); } } } public void mouseScrolled(MouseEvent e) { /* if (e.count == 3) { // scroll up zoomIn(); } else if (e.count == -3) { // scroll down zoomOut(); } } */ } private void addCandidateAsHop(int mouseX, int mouseY) { boolean forward = startHopStep!=null; StepMeta fromStep = candidate.getFromStep(); StepMeta toStep = candidate.getToStep(); // See what the options are. // - Does the source step has multiple stream options? // - Does the target step have multiple input stream options? List<StreamInterface> streams=new ArrayList<StreamInterface>(); StepIOMetaInterface fromIoMeta = fromStep.getStepMetaInterface().getStepIOMeta(); List<StreamInterface> targetStreams = fromIoMeta.getTargetStreams(); if (forward) { streams.addAll(targetStreams); } StepIOMetaInterface toIoMeta = toStep.getStepMetaInterface().getStepIOMeta(); List<StreamInterface> infoStreams = toIoMeta.getInfoStreams(); if (!forward) { streams.addAll(infoStreams); } if (forward) { if (fromIoMeta.isOutputProducer() && toStep.equals(currentStep)) { streams.add( new Stream(StreamType.OUTPUT, fromStep, "Main output of step", StreamIcon.OUTPUT, null) ); //$NON-NLS-1$ } if (fromStep.supportsErrorHandling() && toStep.equals(currentStep)) { streams.add( new Stream(StreamType.ERROR, fromStep, "Error handling of step", StreamIcon.ERROR, null) ); //$NON-NLS-1$ } } else { if (toIoMeta.isInputAcceptor() && fromStep.equals(currentStep)) { streams.add( new Stream(StreamType.INPUT, toStep, "Main input of step", StreamIcon.INPUT, null) ); //$NON-NLS-1$ } if (fromStep.supportsErrorHandling() && fromStep.equals(currentStep)) { streams.add( new Stream(StreamType.ERROR, fromStep, "Error handling of step", StreamIcon.ERROR, null) ); //$NON-NLS-1$ } } // Targets can be dynamically added to this step... if (forward) { streams.addAll( fromStep.getStepMetaInterface().getOptionalStreams() ); } else { streams.addAll( toStep.getStepMetaInterface().getOptionalStreams() ); } // Show a list of options on the canvas... if (streams.size()>1) { // Show a pop-up menu with all the possible options... Menu menu = new Menu(canvas); for (final StreamInterface stream : streams) { MenuItem item = new MenuItem(menu, SWT.NONE); item.setText(Const.NVL(stream.getDescription(), "")); //$NON-NLS-1$ item.setImage( SWTGC.getNativeImage(BasePainter.getStreamIconImage(stream.getStreamIcon())) ); item.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { addHop(stream); } }); } menu.setLocation(canvas.toDisplay(mouseX, mouseY)); menu.setVisible(true); return; } if (streams.size()==1) { addHop(streams.get(0)); } else { return; } /* if (transMeta.findTransHop(candidate) == null) { spoon.newHop(transMeta, candidate); } if (startErrorHopStep) { addErrorHop(); } if (startTargetHopStream != null) { // Auto-configure the target in the source step... // startTargetHopStream.setStepMeta(candidate.getToStep()); startTargetHopStream.setStepname(candidate.getToStep().getName()); startTargetHopStream = null; } */ candidate = null; selectedSteps = null; startHopStep = null; endHopLocation = null; startErrorHopStep = false; // redraw(); } protected void addHop(StreamInterface stream) { switch(stream.getStreamType()) { case ERROR : addErrorHop(); spoon.newHop(transMeta, candidate); break; case INPUT: spoon.newHop(transMeta, candidate); break; case OUTPUT : candidate.getFromStep().setStepErrorMeta(null); spoon.newHop(transMeta, candidate); break; case INFO : stream.setStepMeta(candidate.getFromStep()); candidate.getToStep().getStepMetaInterface().handleStreamSelection(stream); spoon.newHop(transMeta, candidate); break; case TARGET : // We connect a target of the source step to an output step... stream.setStepMeta(candidate.getToStep()); candidate.getFromStep().getStepMetaInterface().handleStreamSelection(stream); spoon.newHop(transMeta, candidate); break; } clearSettings(); } private void addErrorHop() { // Automatically configure the step error handling too! StepErrorMeta errorMeta = candidate.getFromStep().getStepErrorMeta(); if (errorMeta == null) { errorMeta = new StepErrorMeta(transMeta, candidate.getFromStep()); } errorMeta.setEnabled(true); errorMeta.setTargetStep(candidate.getToStep()); candidate.getFromStep().setStepErrorMeta(errorMeta); } private void resetDelayTimer(StepMeta stepMeta) { DelayTimer delayTimer = delayTimers.get(stepMeta); if (delayTimer!=null) { delayTimer.reset(); } } /* private void showStepTargetOptions(final StepMeta stepMeta, StepIOMetaInterface ioMeta, int x, int y) { if (!Const.isEmpty(ioMeta.getTargetStepnames())) { final Menu menu = new Menu(canvas); for (final StreamInterface stream : ioMeta.getTargetStreams()) { MenuItem menuItem = new MenuItem(menu, SWT.NONE); menuItem.setText(stream.getDescription()); menuItem.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { // Click on the target icon means: create a new target hop // if (startHopStep==null) { startHopStep = stepMeta; } menu.setVisible(false); menu.dispose(); redraw(); } }); } menu.setLocation(x, y); menu.setVisible(true); resetDelayTimer(stepMeta); //showTargetStreamsStep = stepMeta; } } */ public void mouseEnter(MouseEvent arg0) { } public void mouseExit(MouseEvent arg0) { } private synchronized void addStepMouseOverDelayTimer(final StepMeta stepMeta) { // Don't add the same mouse over delay timer twice... if (mouseOverSteps.contains(stepMeta)) return; mouseOverSteps.add(stepMeta); DelayTimer delayTimer = new DelayTimer(2500, new DelayListener() { public void expired() { mouseOverSteps.remove(stepMeta); delayTimers.remove(stepMeta); showTargetStreamsStep=null; asyncRedraw(); } }); new Thread(delayTimer).start(); delayTimers.put(stepMeta, delayTimer); } private void stopStepMouseOverDelayTimer(final StepMeta stepMeta) { DelayTimer delayTimer = delayTimers.get(stepMeta); if (delayTimer!=null) { delayTimer.stop(); } } private void stopStepMouseOverDelayTimers() { for (DelayTimer timer : delayTimers.values()) { timer.stop(); } } protected void asyncRedraw() { spoon.getDisplay().asyncExec(new Runnable() { public void run() { if (!TransGraph.this.isDisposed()) { TransGraph.this.redraw(); } } }); } private void addToolBar() { try { toolbar = (XulToolbar) getXulDomContainer().getDocumentRoot().getElementById("nav-toolbar"); //$NON-NLS-1$ ToolBar swtToolbar = (ToolBar) toolbar.getManagedObject(); swtToolbar.pack(); // Hack alert : more XUL limitations... // TODO: no longer a limitation use toolbaritem ToolItem sep = new ToolItem(swtToolbar, SWT.SEPARATOR); zoomLabel = new Combo(swtToolbar, SWT.DROP_DOWN); zoomLabel.setItems(TransPainter.magnificationDescriptions); zoomLabel.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { readMagnification(); } }); zoomLabel.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent event) { if (event.character == SWT.CR) { readMagnification(); } } }); setZoomLabel(); zoomLabel.pack(); sep.setWidth(80); sep.setControl(zoomLabel); swtToolbar.pack(); } catch (Throwable t) { log.logError(toString(), Const.getStackTracker(t)); new ErrorDialog(shell, BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_TOOLBAR), new Exception(t)); //$NON-NLS-1$ } } /** * Allows for magnifying to any percentage entered by the user... */ private void readMagnification(){ String possibleText = zoomLabel.getText(); possibleText = possibleText.replace("%", ""); //$NON-NLS-1$//$NON-NLS-2$ float possibleFloatMagnification; try { possibleFloatMagnification = Float.parseFloat(possibleText) / 100; magnification = possibleFloatMagnification; if (zoomLabel.getText().indexOf('%') < 0) { zoomLabel.setText(zoomLabel.getText().concat("%")); //$NON-NLS-1$ } } catch (Exception e) { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_ERROR); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Message", zoomLabel.getText())); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.InvalidZoomMeasurement.Title")); //$NON-NLS-1$ mb.open(); } redraw(); } protected void hideToolTips() { toolTip.hide(); helpTip.hide(); } private void showHelpTip(int x, int y, String tipTitle, String tipMessage) { helpTip.setTitle(tipTitle); helpTip.setMessage(tipMessage.replaceAll("\n", Const.CR)); //$NON-NLS-1$ helpTip.setCheckBoxMessage(BaseMessages.getString(PKG, "TransGraph.HelpToolTip.DoNotShowAnyMoreCheckBox.Message")); //$NON-NLS-1$ // helpTip.hide(); // int iconSize = spoon.props.getIconSize(); org.eclipse.swt.graphics.Point location = new org.eclipse.swt.graphics.Point(x - 5, y - 5); helpTip.show(location); } /** * Select all the steps in a certain (screen) rectangle * * @param rect The selection area as a rectangle */ public void selectInRect(TransMeta transMeta, org.pentaho.di.core.gui.Rectangle rect) { if (rect.height < 0 || rect.width < 0) { org.pentaho.di.core.gui.Rectangle rectified = new org.pentaho.di.core.gui.Rectangle(rect.x, rect.y, rect.width, rect.height); // Only for people not dragging from left top to right bottom if (rectified.height < 0) { rectified.y = rectified.y + rectified.height; rectified.height = -rectified.height; } if (rectified.width < 0) { rectified.x = rectified.x + rectified.width; rectified.width = -rectified.width; } rect = rectified; } for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta stepMeta = transMeta.getStep(i); Point a = stepMeta.getLocation(); if (rect.contains(a.x, a.y)) stepMeta.setSelected(true); } for (int i = 0; i < transMeta.nrNotes(); i++) { NotePadMeta ni = transMeta.getNote(i); Point a = ni.getLocation(); Point b = new Point(a.x + ni.width, a.y + ni.height); if (rect.contains(a.x, a.y) && rect.contains(b.x, b.y)) ni.setSelected(true); } } public void keyPressed(KeyEvent e) { if (e.keyCode == SWT.ESC) { clearSettings(); redraw(); } if (e.keyCode == SWT.DEL) { List<StepMeta> stepMeta = transMeta.getSelectedSteps(); if (stepMeta != null && stepMeta.size()> 0) { delSelected(null); } } if (e.keyCode == SWT.F1) { spoon.editOptions(); } if (e.keyCode == SWT.F2) { spoon.editKettlePropertiesFile(); } // CTRL-UP : allignTop(); if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0) { alligntop(); } // CTRL-DOWN : allignBottom(); if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0) { allignbottom(); } // CTRL-LEFT : allignleft(); if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0) { allignleft(); } // CTRL-RIGHT : allignRight(); if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0) { allignright(); } // ALT-RIGHT : distributeHorizontal(); if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0) { distributehorizontal(); } // ALT-UP : distributeVertical(); if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0) { distributevertical(); } // ALT-HOME : snap to grid if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0) { snaptogrid(ConstUI.GRID_SIZE); } if (e.character == 'E' && (e.stateMask & SWT.CTRL) != 0) { checkErrorVisuals(); } // SPACE : over a step: show output fields... if (e.character == ' ' && lastMove != null) { // TODO: debugging code, remove later on! dumpLoggingRegistry(); Point real = screen2real(lastMove.x, lastMove.y); // Hide the tooltip! hideToolTips(); // Set the pop-up menu StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null) { // OK, we found a step, show the output fields... inputOutputFields(stepMeta, false); } } // CTRL-W or CTRL-F4 : close tab if ((e.character=='w' && (e.stateMask & SWT.CONTROL) != 0 ) || (e.keyCode==SWT.F4 && (e.stateMask & SWT.CONTROL) != 0 ) ) { dispose(); } } public void keyReleased(KeyEvent e) { } public boolean setFocus() { return canvas.setFocus(); } public void renameStep(StepMeta stepMeta, String stepname) { String newname = stepname; StepMeta smeta = transMeta.findStep(newname, stepMeta); int nr = 2; while (smeta != null) { newname = stepname + " " + nr; //$NON-NLS-1$ smeta = transMeta.findStep(newname); nr++; } if (nr > 2) { stepname = newname; MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$ //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$ //$NON-NLS-1$ mb.open(); } stepMeta.setName(stepname); stepMeta.setChanged(); spoon.refreshTree(); // to reflect the new name spoon.refreshGraph(); } public void clearSettings() { selectedStep = null; noInputStep = null; selectedNote = null; selectedSteps = null; selectionRegion = null; candidate = null; last_hop_split = null; lastButton = 0; iconoffset = null; startHopStep = null; endHopStep = null; endHopLocation = null; mouseOverSteps.clear(); for (int i = 0; i < transMeta.nrTransHops(); i++) { transMeta.getTransHop(i).split = false; } stopStepMouseOverDelayTimers(); } public String[] getDropStrings(String str, String sep) { StringTokenizer strtok = new StringTokenizer(str, sep); String retval[] = new String[strtok.countTokens()]; int i = 0; while (strtok.hasMoreElements()) { retval[i] = strtok.nextToken(); i++; } return retval; } public Point getRealPosition(Composite canvas, int x, int y) { Point p = new Point(0, 0); Composite follow = canvas; while (follow != null) { org.eclipse.swt.graphics.Point loc = follow.getLocation(); Point xy = new Point(loc.x, loc.y); p.x += xy.x; p.y += xy.y; follow = follow.getParent(); } int offsetX = -16; int offsetY = -64; if (Const.isOSX()) { offsetX = -2; offsetY = -24; } p.x = x - p.x + offsetX; p.y = y - p.y + offsetY; return screen2real(p.x, p.y); } /** * See if location (x,y) is on a line between two steps: the hop! * @param x * @param y * @return the transformation hop on the specified location, otherwise: null */ private TransHopMeta findHop(int x, int y) { return findHop(x, y, null); } /** * See if location (x,y) is on a line between two steps: the hop! * @param x * @param y * @param exclude the step to exclude from the hops (from or to location). Specify null if no step is to be excluded. * @return the transformation hop on the specified location, otherwise: null */ private TransHopMeta findHop(int x, int y, StepMeta exclude) { int i; TransHopMeta online = null; for (i = 0; i < transMeta.nrTransHops(); i++) { TransHopMeta hi = transMeta.getTransHop(i); StepMeta fs = hi.getFromStep(); StepMeta ts = hi.getToStep(); if (fs == null || ts == null) return null; // If either the "from" or "to" step is excluded, skip this hop. if (exclude != null && (exclude.equals(fs) || exclude.equals(ts))) continue; int line[] = getLine(fs, ts); if (pointOnLine(x, y, line)) online = hi; } return online; } private int[] getLine(StepMeta fs, StepMeta ts) { Point from = fs.getLocation(); Point to = ts.getLocation(); offset = getOffset(); int x1 = from.x + iconsize / 2; int y1 = from.y + iconsize / 2; int x2 = to.x + iconsize / 2; int y2 = to.y + iconsize / 2; return new int[] { x1, y1, x2, y2 }; } public void hideStep() { for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta sti = transMeta.getStep(i); if (sti.isDrawn() && sti.isSelected()) { sti.hideStep(); spoon.refreshTree(); } } getCurrentStep().hideStep(); spoon.refreshTree(); redraw(); } public void checkSelectedSteps() { spoon.checkTrans(transMeta, true); } public void detachStep() { detach(getCurrentStep()); selectedSteps = null; } public void generateMappingToThisStep() { spoon.generateFieldMapping(transMeta, getCurrentStep()); } public void partitioning() { spoon.editPartitioning(transMeta, getCurrentStep()); } public void clustering() { List<StepMeta> selected = transMeta.getSelectedSteps(); if (selected!=null && selected.size()>0) { spoon.editClustering(transMeta, transMeta.getSelectedSteps()); } else { spoon.editClustering(transMeta, getCurrentStep()); } } public void errorHandling() { spoon.editStepErrorHandling(transMeta, getCurrentStep()); } public void newHopChoice() { selectedSteps = null; newHop(); } public void editStep() { selectedSteps = null; editStep(getCurrentStep()); } public void editDescription() { editDescription(getCurrentStep()); } public void setDistributes() { getCurrentStep().setDistributes(true); spoon.refreshGraph(); spoon.refreshTree(); } public void setCopies() { getCurrentStep().setDistributes(false); spoon.refreshGraph(); spoon.refreshTree(); } public void copies() { final boolean multipleOK = checkNumberOfCopies(transMeta, getCurrentStep()); selectedSteps = null; String tt = BaseMessages.getString(PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Title"); //$NON-NLS-1$ String mt = BaseMessages.getString(PKG, "TransGraph.Dialog.NrOfCopiesOfStep.Message"); //$NON-NLS-1$ EnterNumberDialog nd = new EnterNumberDialog(shell, getCurrentStep().getCopies(), tt, mt); int cop = nd.open(); if (cop >= 0) { if (cop == 0) cop = 1; if (!multipleOK) { cop = 1; MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Title")); //$NON-NLS-1$ mb.open(); } if (getCurrentStep().getCopies() != cop) { getCurrentStep().setCopies(cop); spoon.refreshGraph(); } } } public void dupeStep() { try { List<StepMeta> steps = transMeta.getSelectedSteps(); if (steps.size() <= 1) { spoon.dupeStep(transMeta, getCurrentStep()); } else { for (StepMeta stepMeta : steps) { spoon.dupeStep(transMeta, stepMeta); } } } catch (Exception ex) { new ErrorDialog( shell, BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.ErrorDuplicatingStep.Message"), ex); //$NON-NLS-1$ //$NON-NLS-2$ } } public void copyStep() { spoon.copySelected(transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes()); } public void delSelected() { delSelected(getCurrentStep()); } public void fieldsBefore() { selectedSteps = null; inputOutputFields(getCurrentStep(), true); } public void fieldsAfter() { selectedSteps = null; inputOutputFields(getCurrentStep(), false); } public void fieldsLineage() { TransDataLineage tdl = new TransDataLineage(transMeta); try { tdl.calculateLineage(); } catch(Exception e) { new ErrorDialog(shell, "Lineage error", "Unexpected lineage calculation error", e); //$NON-NLS-1$ //$NON-NLS-2$ } } public void editHop() { selectionRegion = null; editHop(getCurrentHop()); } public void flipHopDirection() { selectionRegion = null; TransHopMeta hi = getCurrentHop(); hi.flip(); if (transMeta.hasLoop(hi.getFromStep())) { spoon.refreshGraph(); MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopsAreNotAllowed.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopsAreNotAllowed.Title")); //$NON-NLS-1$ mb.open(); hi.flip(); spoon.refreshGraph(); } else { hi.setChanged(); spoon.refreshGraph(); spoon.refreshTree(); spoon.setShellText(); } } public void enableHop() { selectionRegion = null; TransHopMeta hi = getCurrentHop(); TransHopMeta before = (TransHopMeta) hi.clone(); hi.setEnabled(!hi.isEnabled()); if (transMeta.hasLoop(hi.getToStep())) { hi.setEnabled(!hi.isEnabled()); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopAfterHopEnabled.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.LoopAfterHopEnabled.Title")); //$NON-NLS-1$ mb.open(); } else { TransHopMeta after = (TransHopMeta) hi.clone(); spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta .indexOfTransHop(hi) }); spoon.refreshGraph(); spoon.refreshTree(); } } public void deleteHop() { selectionRegion = null; TransHopMeta hi = getCurrentHop(); int idx = transMeta.indexOfTransHop(hi); spoon.addUndoDelete(transMeta, new TransHopMeta[] { (TransHopMeta) hi.clone() }, new int[] { idx }); transMeta.removeTransHop(idx); spoon.refreshTree(); spoon.refreshGraph(); } public void editNote() { selectionRegion = null; editNote(getCurrentNote()); } public void deleteNote() { selectionRegion = null; int idx = transMeta.indexOfNote(ni); if (idx >= 0) { transMeta.removeNote(idx); spoon.addUndoDelete(transMeta, new NotePadMeta[] { (NotePadMeta) ni.clone() }, new int[] { idx }); redraw(); } } public void raiseNote() { selectionRegion = null; int idx = transMeta.indexOfNote(getCurrentNote()); if (idx >= 0) { transMeta.raiseNote(idx); //TBD: spoon.addUndoRaise(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} ); } redraw(); } public void lowerNote() { selectionRegion = null; int idx = transMeta.indexOfNote(getCurrentNote()); if (idx >= 0) { transMeta.lowerNote(idx); //TBD: spoon.addUndoLower(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} ); } redraw(); } public void newNote() { selectionRegion = null; String title = BaseMessages.getString(PKG, "TransGraph.Dialog.NoteEditor.Title"); //$NON-NLS-1$ NotePadDialog dd = new NotePadDialog(shell, title); //$NON-NLS-1$ NotePadMeta n = dd.open(); if (n != null) { NotePadMeta npi = new NotePadMeta(n.getNote(), lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE,n.getFontName(),n.getFontSize(), n.isFontBold(), n.isFontItalic(), n.getFontColorRed(),n.getFontColorGreen(),n.getFontColorBlue(), n.getBackGroundColorRed(), n.getBackGroundColorGreen(),n.getBackGroundColorBlue(), n.getBorderColorRed(), n.getBorderColorGreen(),n.getBorderColorBlue(), n.isDrawShadow()); transMeta.addNote(npi); spoon.addUndoNew(transMeta, new NotePadMeta[] { npi }, new int[] { transMeta.indexOfNote(npi) }); redraw(); } } public void paste() { final String clipcontent = spoon.fromClipboard(); Point loc = new Point(currentMouseX, currentMouseY); spoon.pasteXML(transMeta, clipcontent, loc); } public void settings() { editProperties(transMeta, spoon, spoon.getRepository(), true); } public void newStep(String description) { StepMeta stepMeta = spoon.newStep(transMeta, description, description, false, true); PropsUI.setLocation(stepMeta, currentMouseX, currentMouseY); stepMeta.setDraw(true); redraw(); } /** * This sets the popup-menu on the background of the canvas based on the xy coordinate of the mouse. This method is * called after a mouse-click. * * @param x X-coordinate on screen * @param y Y-coordinate on screen */ private synchronized void setMenu(int x, int y) { try { currentMouseX = x; currentMouseY = y; final StepMeta stepMeta = transMeta.getStep(x, y, iconsize); if (stepMeta != null) // We clicked on a Step! { setCurrentStep(stepMeta); XulMenupopup menu = menuMap.get("trans-graph-entry"); //$NON-NLS-1$ if (menu != null) { List<StepMeta> selection = transMeta.getSelectedSteps(); int sels = selection.size(); Document doc = getXulDomContainer().getDocumentRoot(); XulMenuitem item = (XulMenuitem) doc.getElementById("trans-graph-entry-newhop"); //$NON-NLS-1$ item.setDisabled(sels != 2); item = (XulMenuitem) doc.getElementById("trans-graph-entry-open-mapping"); //$NON-NLS-1$ item.setDisabled(!stepMeta.isMapping()); item = (XulMenuitem) doc.getElementById("trans-graph-entry-align-snap"); //$NON-NLS-1$ item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.SnapToGrid") + ConstUI.GRID_SIZE + ")\tALT-HOME"); //$NON-NLS-1$ //$NON-NLS-2$ XulMenu men = (XulMenu) doc.getElementById("trans-graph-entry-sniff"); men.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$ item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-input"); //$NON-NLS-1$ item.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$ item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-output"); //$NON-NLS-1$ item.setDisabled(trans==null || trans.isRunning() == false); //$NON-NLS-1$ item = (XulMenuitem) doc.getElementById("trans-graph-entry-sniff-error"); //$NON-NLS-1$ item.setDisabled(!(stepMeta.supportsErrorHandling() && stepMeta.getStepErrorMeta()!=null && stepMeta.getStepErrorMeta().getTargetStep()!=null && trans!=null && trans.isRunning())); XulMenu aMenu = (XulMenu) doc.getElementById("trans-graph-entry-align"); //$NON-NLS-1$ if (aMenu != null) { aMenu.setDisabled(sels < 2); } item = (XulMenuitem) doc.getElementById("trans-graph-entry-data-movement-distribute"); //$NON-NLS-1$ item.setSelected(stepMeta.isDistributes()); item = (XulMenuitem) doc.getElementById("trans-graph-entry-data-movement-copy"); //$NON-NLS-1$ item.setSelected(!stepMeta.isDistributes()); item = (XulMenuitem) doc.getElementById("trans-graph-entry-hide"); //$NON-NLS-1$ item.setDisabled(!(stepMeta.isDrawn() && !transMeta.isStepUsedInTransHops(stepMeta))); item = (XulMenuitem) doc.getElementById("trans-graph-entry-detach"); //$NON-NLS-1$ item.setDisabled(!transMeta.isStepUsedInTransHops(stepMeta)); item = (XulMenuitem) doc.getElementById("trans-graph-entry-errors"); //$NON-NLS-1$ item.setDisabled(!stepMeta.supportsErrorHandling()); ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas); } } else { final TransHopMeta hi = findHop(x, y); if (hi != null) // We clicked on a HOP! { XulMenupopup menu = menuMap.get("trans-graph-hop"); //$NON-NLS-1$ if (menu != null) { setCurrentHop(hi); XulMenuitem item = (XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-hop-enabled"); //$NON-NLS-1$ if (item != null) { if (hi.isEnabled()) { item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.DisableHop")); //$NON-NLS-1$ } else { item.setLabel(BaseMessages.getString(PKG, "TransGraph.PopupMenu.EnableHop")); //$NON-NLS-1$ } } ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas); } } else { // Clicked on the background: maybe we hit a note? final NotePadMeta ni = transMeta.getNote(x, y); setCurrentNote(ni); if (ni != null) { XulMenupopup menu = menuMap.get("trans-graph-note"); //$NON-NLS-1$ if (menu != null) { ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas); } } else { XulMenupopup menu = menuMap.get("trans-graph-background"); //$NON-NLS-1$ if (menu != null) { final String clipcontent = spoon.fromClipboard(); XulMenuitem item = (XulMenuitem) getXulDomContainer().getDocumentRoot().getElementById("trans-graph-background-paste"); //$NON-NLS-1$ if (item != null) { item.setDisabled(clipcontent == null); } ConstUI.displayMenu((Menu)menu.getManagedObject(), canvas); } } } } } catch (Throwable t) { // TODO: fix this: log somehow, is IGNORED for now. t.printStackTrace(); } } public void selectAll() { spoon.editSelectAll(); } public void clearSelection() { spoon.editUnselectAll(); } private boolean checkNumberOfCopies(TransMeta transMeta, StepMeta stepMeta) { boolean enabled = true; List<StepMeta> prevSteps = transMeta.findPreviousSteps(stepMeta); for (StepMeta prevStep : prevSteps) { // See what the target steps are. // If one of the target steps is our original step, we can't start multiple copies String[] targetSteps = prevStep.getStepMetaInterface().getStepIOMeta().getTargetStepnames(); if (targetSteps != null) { for (int t = 0; t < targetSteps.length && enabled; t++) { if (!Const.isEmpty(targetSteps[t]) && targetSteps[t].equalsIgnoreCase(stepMeta.getName())) enabled = false; } } } return enabled; } private AreaOwner setToolTip(int x, int y, int screenX, int screenY) { AreaOwner subject = null; if (!spoon.getProperties().showToolTips()) return subject; canvas.setToolTipText(null); String newTip = null; Image tipImage = null; final TransHopMeta hi = findHop(x, y); // check the area owner list... StringBuffer tip = new StringBuffer(); AreaOwner areaOwner = getVisibleAreaOwner(x, y); if (areaOwner!=null) { switch (areaOwner.getAreaType()) { case REMOTE_INPUT_STEP: StepMeta step = (StepMeta) areaOwner.getParent(); tip.append("Remote input steps:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$//$NON-NLS-2$ for (RemoteStep remoteStep : step.getRemoteInputSteps()) { tip.append(remoteStep.toString()).append(Const.CR); } break; case REMOTE_OUTPUT_STEP: step = (StepMeta) areaOwner.getParent(); tip.append("Remote output steps:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$ for (RemoteStep remoteStep : step.getRemoteOutputSteps()) { tip.append(remoteStep.toString()).append(Const.CR); } break; case STEP_PARTITIONING: step = (StepMeta) areaOwner.getParent(); tip.append("Step partitioning:").append(Const.CR).append("-----------------------").append(Const.CR); //$NON-NLS-1$ //$NON-NLS-2$ tip.append(step.getStepPartitioningMeta().toString()).append(Const.CR); if (step.getTargetStepPartitioningMeta() != null) { tip.append(Const.CR).append(Const.CR).append("TARGET: " + step.getTargetStepPartitioningMeta().toString()).append(Const.CR); //$NON-NLS-1$ } break; case STEP_ERROR_ICON: String log = (String) areaOwner.getParent(); tip.append(log); tipImage = GUIResource.getInstance().getImageStepError(); break; case HOP_COPY_ICON: step = (StepMeta) areaOwner.getParent(); tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeCopy", step.getName(), Const.CR)); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageCopyHop(); break; case HOP_INFO_ICON: StepMeta from = (StepMeta) areaOwner.getParent(); StepMeta to = (StepMeta) areaOwner.getOwner(); tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeInfo", to.getName(), from.getName(), Const.CR)); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageInfoHop(); break; case HOP_ERROR_ICON: from = (StepMeta) areaOwner.getParent(); to = (StepMeta) areaOwner.getOwner(); areaOwner.getOwner(); tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.HopTypeError", from.getName(), to.getName(), Const.CR)); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageErrorHop(); break; case HOP_INFO_STEP_COPIES_ERROR: from = (StepMeta) areaOwner.getParent(); to = (StepMeta) areaOwner.getOwner(); tip.append(BaseMessages.getString(PKG, "TransGraph.Hop.Tooltip.InfoStepCopies", from.getName(), to.getName(), Const.CR)); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageStepError(); break; case REPOSITORY_LOCK_IMAGE: RepositoryLock lock = (RepositoryLock) areaOwner.getOwner(); tip.append(BaseMessages.getString(PKG, "TransGraph.Locked.Tooltip", Const.CR, lock.getLogin(), lock.getUsername(), lock.getMessage(), XMLHandler.date2string(lock.getLockDate()))); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageLocked(); break; case STEP_INPUT_HOP_ICON: // StepMeta subjectStep = (StepMeta) (areaOwner.getParent()); tip.append(BaseMessages.getString(PKG, "TransGraph.StepInputConnector.Tooltip")); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageHopInput(); break; case STEP_OUTPUT_HOP_ICON: //subjectStep = (StepMeta) (areaOwner.getParent()); tip.append(BaseMessages.getString(PKG, "TransGraph.StepOutputConnector.Tooltip")); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageHopOutput(); break; case STEP_INFO_HOP_ICON: // subjectStep = (StepMeta) (areaOwner.getParent()); // StreamInterface stream = (StreamInterface) areaOwner.getOwner(); StepIOMetaInterface ioMeta = (StepIOMetaInterface) areaOwner.getOwner(); tip.append(BaseMessages.getString(PKG, "TransGraph.StepInfoConnector.Tooltip")+Const.CR+ioMeta.toString()); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageHopOutput(); break; case STEP_TARGET_HOP_ICON: StreamInterface stream = (StreamInterface) areaOwner.getOwner(); tip.append(stream.getDescription()); tipImage = GUIResource.getInstance().getImageHopOutput(); break; case STEP_ERROR_HOP_ICON: StepMeta stepMeta = (StepMeta)areaOwner.getParent(); if (stepMeta.supportsErrorHandling()) { tip.append(BaseMessages.getString(PKG, "TransGraph.StepSupportsErrorHandling.Tooltip")); //$NON-NLS-1$ } else { tip.append(BaseMessages.getString(PKG, "TransGraph.StepDoesNotSupportsErrorHandling.Tooltip")); //$NON-NLS-1$ } tipImage = GUIResource.getInstance().getImageHopOutput(); break; case STEP_EDIT_ICON: stepMeta = (StepMeta) (areaOwner.getParent()); tip.append(BaseMessages.getString(PKG, "TransGraph.EditStep.Tooltip")); //$NON-NLS-1$ tipImage = GUIResource.getInstance().getImageEdit(); break; } } if (hi != null) // We clicked on a HOP! { // Set the tooltip for the hop: tip.append(Const.CR).append("Hop information: ").append(newTip = hi.toString()).append(Const.CR); //$NON-NLS-1$ } if (tip.length() == 0) { newTip = null; } else { newTip = tip.toString(); } if (newTip == null) { toolTip.hide(); if (hi != null) // We clicked on a HOP! { // Set the tooltip for the hop: newTip = BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo") + Const.CR + BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.SourceStep") + " " + hi.getFromStep().getName() + Const.CR //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.TargetStep") + " " + hi.getToStep().getName() + Const.CR + BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Status") + " " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + (hi.isEnabled() ? BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Enable") : BaseMessages.getString(PKG, "TransGraph.Dialog.HopInfo.Disable")); //$NON-NLS-1$ //$NON-NLS-2$ toolTip.setText(newTip); if (hi.isEnabled()) toolTip.setImage(GUIResource.getInstance().getImageHop()); else toolTip.setImage(GUIResource.getInstance().getImageDisabledHop()); toolTip.show(new org.eclipse.swt.graphics.Point(screenX, screenY)); } else { newTip = null; } } else if (!newTip.equalsIgnoreCase(getToolTipText())) { if (tipImage != null) { toolTip.setImage(tipImage); } else { toolTip.setImage(GUIResource.getInstance().getImageSpoon()); } toolTip.setText(newTip); toolTip.hide(); toolTip.show(new org.eclipse.swt.graphics.Point(x, y)); } return subject; } public AreaOwner getVisibleAreaOwner(int x, int y) { for (int i=areaOwners.size()-1;i>=0;i AreaOwner areaOwner = areaOwners.get(i); if (areaOwner.contains(x, y)) { return areaOwner; } } return null; } public void delSelected(StepMeta stMeta) { List<StepMeta> selection = transMeta.getSelectedSteps(); if (selection.size() == 0) { spoon.delStep(transMeta, stMeta); return; } // Get the list of steps that would be deleted List<String> stepList = new ArrayList<String>(); for (int i = transMeta.nrSteps() - 1; i >= 0; i StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) { stepList.add(stepMeta.getName()); } } // Create and display the delete confirmation dialog MessageBox mb = new DeleteMessageBox(shell, BaseMessages.getString(PKG, "TransGraph.Dialog.Warning.DeleteSteps.Message"), //$NON-NLS-1$ stepList); int result = mb.open(); if (result == SWT.YES) { // Delete the steps for (int i = transMeta.nrSteps() - 1; i >= 0; i StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) { spoon.delStep(transMeta, stepMeta); } } } } public void editDescription(StepMeta stepMeta) { String title = BaseMessages.getString(PKG, "TransGraph.Dialog.StepDescription.Title"); //$NON-NLS-1$ String message = BaseMessages.getString(PKG, "TransGraph.Dialog.StepDescription.Message"); //$NON-NLS-1$ EnterTextDialog dd = new EnterTextDialog(shell, title, message, stepMeta.getDescription()); String d = dd.open(); if (d != null) stepMeta.setDescription(d); } /** * Display the input- or outputfields for a step. * * @param stepMeta The step (it's metadata) to query * @param before set to true if you want to have the fields going INTO the step, false if you want to see all the * fields that exit the step. */ private void inputOutputFields(StepMeta stepMeta, boolean before) { spoon.refreshGraph(); SearchFieldsProgressDialog op = new SearchFieldsProgressDialog(transMeta, stepMeta, before); try { final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell); // Run something in the background to cancel active database queries, forecably if needed! Runnable run = new Runnable() { public void run() { IProgressMonitor monitor = pmd.getProgressMonitor(); while (pmd.getShell() == null || (!pmd.getShell().isDisposed() && !monitor.isCanceled())) { try { Thread.sleep(250); } catch (InterruptedException e) { } ; } if (monitor.isCanceled()) // Disconnect and see what happens! { try { transMeta.cancelQueries(); } catch (Exception e) { } ; } } }; // Dump the cancel looker in the background! new Thread(run).start(); pmd.run(true, true, op); } catch (InvocationTargetException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Title"), BaseMessages.getString(PKG, "TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface fields = op.getFields(); if (fields != null && fields.size() > 0) { StepFieldsDialog sfd = new StepFieldsDialog(shell, transMeta, SWT.NONE, stepMeta.getName(), fields); String sn = (String) sfd.open(); if (sn != null) { StepMeta esi = transMeta.findStep(sn); if (esi != null) { editStep(esi); } } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(BaseMessages.getString(PKG, "TransGraph.Dialog.CouldntFindFields.Message")); //$NON-NLS-1$ mb.setText(BaseMessages.getString(PKG, "TransGraph.Dialog.CouldntFindFields.Title")); //$NON-NLS-1$ mb.open(); } } public void paintControl(PaintEvent e) { Point area = getArea(); if (area.x == 0 || area.y == 0) return; // nothing to do! Display disp = shell.getDisplay(); Image img = getTransformationImage(disp, area.x, area.y, magnification); e.gc.drawImage(img, 0, 0); img.dispose(); // spoon.setShellText(); } public Image getTransformationImage(Device device, int x, int y, float magnificationFactor) { GCInterface gc = new SWTGC(device, new Point(x, y), iconsize); TransPainter transPainter = new TransPainter( gc, transMeta, new Point(x, y), new SwtScrollBar(hori), new SwtScrollBar(vert), candidate, drop_candidate, selectionRegion, areaOwners, mouseOverSteps, PropsUI.getInstance().getIconSize(), PropsUI.getInstance().getLineWidth(), PropsUI.getInstance().getCanvasGridSize(), PropsUI.getInstance().getShadowSize(), PropsUI.getInstance().isAntiAliasingEnabled(), PropsUI.getInstance().getNoteFont().getName(), PropsUI.getInstance().getNoteFont().getHeight() ); transPainter.setMagnification(magnificationFactor); transPainter.setStepLogMap(stepLogMap); transPainter.setStartHopStep(startHopStep); transPainter.setEndHopLocation(endHopLocation); transPainter.setNoInputStep(noInputStep); transPainter.setEndHopStep(endHopStep); transPainter.setCandidateHopType(candidateHopType); transPainter.setStartErrorHopStep(startErrorHopStep); transPainter.setShowTargetStreamsStep(showTargetStreamsStep); transPainter.buildTransformationImage(); Image img = (Image)gc.getImage(); return img; } protected Point getOffset() { Point area = getArea(); Point max = transMeta.getMaximum(); Point thumb = getThumb(area, max); return getOffset(thumb, area); } private void editStep(StepMeta stepMeta) { spoon.editStep(transMeta, stepMeta); } private void editNote(NotePadMeta ni) { NotePadMeta before = (NotePadMeta) ni.clone(); String title = BaseMessages.getString(PKG, "TransGraph.Dialog.EditNote.Title"); //$NON-NLS-1$ NotePadDialog dd = new NotePadDialog(shell, title, ni); NotePadMeta n = dd.open(); if (n != null) { ni.setChanged(); ni.setNote(n.getNote()); ni.setFontName(n.getFontName()); ni.setFontSize(n.getFontSize()); ni.setFontBold(n.isFontBold()); ni.setFontItalic(n.isFontItalic()); // font color ni.setFontColorRed(n.getFontColorRed()); ni.setFontColorGreen(n.getFontColorGreen()); ni.setFontColorBlue(n.getFontColorBlue()); // background color ni.setBackGroundColorRed(n.getBackGroundColorRed()); ni.setBackGroundColorGreen(n.getBackGroundColorGreen()); ni.setBackGroundColorBlue(n.getBackGroundColorBlue()); // border color ni.setBorderColorRed(n.getBorderColorRed()); ni.setBorderColorGreen(n.getBorderColorGreen()); ni.setBorderColorBlue(n.getBorderColorBlue()); ni.setDrawShadow(n.isDrawShadow()); ni.width = ConstUI.NOTE_MIN_SIZE; ni.height = ConstUI.NOTE_MIN_SIZE; NotePadMeta after = (NotePadMeta) ni.clone(); spoon.addUndoChange(transMeta, new NotePadMeta[] { before }, new NotePadMeta[] { after }, new int[] { transMeta .indexOfNote(ni) }); spoon.refreshGraph(); } } private void editHop(TransHopMeta transHopMeta) { String name = transHopMeta.toString(); if(log.isDebug()) log.logDebug(BaseMessages.getString(PKG, "TransGraph.Logging.EditingHop") + name); //$NON-NLS-1$ spoon.editHop(transMeta, transHopMeta); } private void newHop() { List<StepMeta> selection = transMeta.getSelectedSteps(); if (selection.size()==2) { StepMeta fr = selection.get(0); StepMeta to = selection.get(1); spoon.newHop(transMeta, fr, to); } } private boolean pointOnLine(int x, int y, int line[]) { int dx, dy; int pm = HOP_SEL_MARGIN / 2; boolean retval = false; for (dx = -pm; dx <= pm && !retval; dx++) { for (dy = -pm; dy <= pm && !retval; dy++) { retval = pointOnThinLine(x + dx, y + dy, line); } } return retval; } private boolean pointOnThinLine(int x, int y, int line[]) { int x1 = line[0]; int y1 = line[1]; int x2 = line[2]; int y2 = line[3]; // Not in the square formed by these 2 points: ignore! if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1)))) return false; double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI; double angle_point = Math.atan2(y - y1, x - x1) + Math.PI; // Same angle, or close enough? if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01) return true; return false; } private SnapAllignDistribute createSnapAllignDistribute() { List<StepMeta> selection = transMeta.getSelectedSteps(); int[] indices = transMeta.getStepIndexes(selection); return new SnapAllignDistribute(transMeta, selection, indices, spoon, this); } public void snaptogrid() { snaptogrid(ConstUI.GRID_SIZE); } private void snaptogrid(int size) { createSnapAllignDistribute().snaptogrid(size); } public void allignleft() { createSnapAllignDistribute().allignleft(); } public void allignright() { createSnapAllignDistribute().allignright(); } public void alligntop() { createSnapAllignDistribute().alligntop(); } public void allignbottom() { createSnapAllignDistribute().allignbottom(); } public void distributehorizontal() { createSnapAllignDistribute().distributehorizontal(); } public void distributevertical() { createSnapAllignDistribute().distributevertical(); } private void detach(StepMeta stepMeta) { TransHopMeta hfrom = transMeta.findTransHopTo(stepMeta); TransHopMeta hto = transMeta.findTransHopFrom(stepMeta); if (hfrom != null && hto != null) { if (transMeta.findTransHop(hfrom.getFromStep(), hto.getToStep()) == null) { TransHopMeta hnew = new TransHopMeta(hfrom.getFromStep(), hto.getToStep()); transMeta.addTransHop(hnew); spoon.addUndoNew(transMeta, new TransHopMeta[] { hnew }, new int[] { transMeta.indexOfTransHop(hnew) }); spoon.refreshTree(); } } if (hfrom != null) { int fromidx = transMeta.indexOfTransHop(hfrom); if (fromidx >= 0) { transMeta.removeTransHop(fromidx); spoon.refreshTree(); } } if (hto != null) { int toidx = transMeta.indexOfTransHop(hto); if (toidx >= 0) { transMeta.removeTransHop(toidx); spoon.refreshTree(); } } spoon.refreshTree(); redraw(); } // Preview the selected steps... public void preview() { spoon.previewTransformation(); } public void newProps() { iconsize = spoon.props.getIconSize(); } public String toString() { return this.getClass().getName(); } public EngineMetaInterface getMeta() { return transMeta; } /** * @param transMeta the transMeta to set */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) { addUndoPosition(obj, pos, prev, curr, false); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) { // It's better to store the indexes of the objects, not the objects itself! transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso); spoon.setUndoMenu(transMeta); } public ChangedWarningInterface getChangedWarning() { ChangedWarningInterface retVal = new AbstractChangedWarningDialog() { @Override public String getSpoonPluginManagerContainerNamespace() { return "trans-graph-changed-warning-dialog"; //$NON-NLS-1$ } @Override public String getXulDialogId() { return "trans-graph-changed-warning-dialog"; //$NON-NLS-1$ } @Override public String getXulResource() { return "ui/trans-graph.xul"; //$NON-NLS-1$ } @Override public XulSpoonResourceBundle getXulResourceBundle() { return new XulSpoonResourceBundle(); } }; return retVal; } public boolean applyChanges() throws KettleException { return spoon.saveToFile(transMeta); } public boolean canBeClosed() { return !transMeta.hasChanged(); } public TransMeta getManagedObject() { return transMeta; } public boolean hasContentChanged() { return transMeta.hasChanged(); } public List<CheckResultInterface> getRemarks() { return remarks; } public void setRemarks(List<CheckResultInterface> remarks) { this.remarks = remarks; } public List<DatabaseImpact> getImpact() { return impact; } public void setImpact(List<DatabaseImpact> impact) { this.impact = impact; } public boolean isImpactFinished() { return impactFinished; } public void setImpactFinished(boolean impactHasRun) { this.impactFinished = impactHasRun; } /** * @return the lastMove */ public Point getLastMove() { return lastMove; } public static boolean editProperties(TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange) { return editProperties(transMeta, spoon, rep, allowDirectoryChange, null); } public static boolean editProperties(TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange, TransDialog.Tabs currentTab) { if (transMeta == null) return false; TransDialog tid = new TransDialog(spoon.getShell(), SWT.NONE, transMeta, rep, currentTab); tid.setDirectoryChangeAllowed(allowDirectoryChange); TransMeta ti = tid.open(); // Load shared objects if (tid.isSharedObjectsFileChanged()) { try { SharedObjects sharedObjects = rep!=null ? rep.readTransSharedObjects(transMeta) : transMeta.readSharedObjects(); spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch (KettleException e) { new ErrorDialog(spoon.getShell(), BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Title"), //$NON-NLS-1$ BaseMessages.getString(PKG, "Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.makeTabName(transMeta, true)), e); //$NON-NLS-1$ } // If we added properties, add them to the variables too, so that they appear in the CTRL-SPACE variable completion. spoon.setParametersAsVariablesInUI(transMeta, transMeta); spoon.refreshTree(); spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway } spoon.setShellText(); return ti != null; } public void openFile() { spoon.openFile(); } public void saveFile() throws KettleException { spoon.saveFile(); } public void saveFileAs() throws KettleException { spoon.saveFileAs(); } public void saveXMLFileToVfs() { spoon.saveXMLFileToVfs(); } public void printFile() { spoon.printFile(); } public void runTransformation() { spoon.runFile(); } public void pauseTransformation() { pauseResume(); } public void stopTransformation() { stop(); } public void previewFile() { spoon.previewFile(); } public void debugFile() { spoon.debugFile(); } public void transReplay() { spoon.replayTransformation(); } public void checkTrans() { spoon.checkTrans(); } public void analyseImpact() { spoon.analyseImpact(); } public void getSQL() { spoon.getSQL(); } public void exploreDatabase() { spoon.exploreDatabase(); } public boolean isExecutionResultsPaneVisible() { return extraViewComposite != null && !extraViewComposite.isDisposed(); } public void showExecutionResults() { if (isExecutionResultsPaneVisible()) { disposeExtraView(); } else { addAllTabs(); } } public void browseVersionHistory() { try { if (spoon.rep.exists(transMeta.getName(), transMeta.getRepositoryDirectory(), RepositoryObjectType.TRANSFORMATION)) { RepositoryRevisionBrowserDialogInterface dialog = RepositoryExplorerDialog.getVersionBrowserDialog(shell, spoon.rep, transMeta.getName(), transMeta.getRepositoryDirectory(), transMeta.getRepositoryElementType()); String versionLabel = dialog.open(); if (versionLabel!=null) { spoon.loadObjectFromRepository(transMeta.getName(), transMeta.getRepositoryElementType(), transMeta.getRepositoryDirectory(), versionLabel); } } else { MessageBox box = new MessageBox(shell, SWT.CLOSE | SWT.ICON_ERROR); box.setText("Sorry"); //$NON-NLS-1$ box.setMessage("Can't find this transformation in the repository"); //$NON-NLS-1$ box.open(); } } catch (Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.VersionBrowserException.Title"), BaseMessages.getString(PKG, "TransGraph.VersionBrowserException.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } /** * If the extra tab view at the bottom is empty, we close it. */ public void checkEmptyExtraView() { if (extraViewTabFolder.getItemCount() == 0) { disposeExtraView(); } } private void disposeExtraView() { extraViewComposite.dispose(); sashForm.layout(); sashForm.setWeights(new int[] { 100, }); XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("trans-show-results"); //$NON-NLS-1$ button.setTooltiptext(BaseMessages.getString(PKG, "Spoon.Tooltip.ShowExecutionResults")); //$NON-NLS-1$ ToolItem toolItem = (ToolItem) button.getManagedObject(); toolItem.setImage(GUIResource.getInstance().getImageShowResults()); } private void minMaxExtraView() { // What is the state? boolean maximized = sashForm.getMaximizedControl() != null; if (maximized) { // Minimize sashForm.setMaximizedControl(null); minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel()); minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); //$NON-NLS-1$ } else { // Maximize sashForm.setMaximizedControl(extraViewComposite); minMaxButton.setImage(GUIResource.getInstance().getImageMinimizePanel()); minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MinButton.Tooltip")); //$NON-NLS-1$ } } /** * @return the toolbar */ public XulToolbar getToolbar() { return toolbar; } /** * @param toolbar the toolbar to set */ public void setToolbar(XulToolbar toolbar) { this.toolbar = toolbar; } private Label closeButton; private Label minMaxButton; /** * Add an extra view to the main composite SashForm */ public void addExtraView() { extraViewComposite = new Composite(sashForm, SWT.NONE); FormLayout extraCompositeFormLayout = new FormLayout(); extraCompositeFormLayout.marginWidth = 2; extraCompositeFormLayout.marginHeight = 2; extraViewComposite.setLayout(extraCompositeFormLayout); // Put a close and max button to the upper right corner... closeButton = new Label(extraViewComposite, SWT.NONE); closeButton.setImage(GUIResource.getInstance().getImageClosePanel()); closeButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.CloseButton.Tooltip")); //$NON-NLS-1$ FormData fdClose = new FormData(); fdClose.right = new FormAttachment(100, 0); fdClose.top = new FormAttachment(0, 0); closeButton.setLayoutData(fdClose); closeButton.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { disposeExtraView(); } }); minMaxButton = new Label(extraViewComposite, SWT.NONE); minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel()); minMaxButton.setToolTipText(BaseMessages.getString(PKG, "TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); //$NON-NLS-1$ FormData fdMinMax = new FormData(); fdMinMax.right = new FormAttachment(closeButton, -Const.MARGIN); fdMinMax.top = new FormAttachment(0, 0); minMaxButton.setLayoutData(fdMinMax); minMaxButton.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { minMaxExtraView(); } }); // Add a label at the top: Results Label wResultsLabel = new Label(extraViewComposite, SWT.LEFT); wResultsLabel.setFont(GUIResource.getInstance().getFontMediumBold()); wResultsLabel.setBackground(GUIResource.getInstance().getColorLightGray()); wResultsLabel.setText(BaseMessages.getString(PKG, "TransLog.ResultsPanel.NameLabel")); //$NON-NLS-1$ FormData fdResultsLabel = new FormData(); fdResultsLabel.left = new FormAttachment(0, 0); fdResultsLabel.right = new FormAttachment(minMaxButton, -Const.MARGIN); fdResultsLabel.top = new FormAttachment(0, 0); wResultsLabel.setLayoutData(fdResultsLabel); // Add a tab folder ... extraViewTabFolder = new CTabFolder(extraViewComposite, SWT.MULTI); spoon.props.setLook(extraViewTabFolder, Props.WIDGET_STYLE_TAB); extraViewTabFolder.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent arg0) { if (sashForm.getMaximizedControl() == null) { sashForm.setMaximizedControl(extraViewComposite); } else { sashForm.setMaximizedControl(null); } } }); FormData fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0, 0); fdTabFolder.right = new FormAttachment(100, 0); fdTabFolder.top = new FormAttachment(wResultsLabel, Const.MARGIN); fdTabFolder.bottom = new FormAttachment(100, 0); extraViewTabFolder.setLayoutData(fdTabFolder); sashForm.setWeights(new int[] { 60, 40, }); } public void checkErrors() { if (trans != null) { if (!trans.isFinished()) { if (trans.getErrors() != 0) { trans.killAll(); } } } } public synchronized void start(TransExecutionConfiguration executionConfiguration) throws KettleException { if (!running) // Not running, start the transformation... { // Auto save feature... if (transMeta.hasChanged()) { if (spoon.props.getAutoSave()) { spoon.saveToFile(transMeta); } else { MessageDialogWithToggle md = new MessageDialogWithToggle( shell, BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged.Title"), //$NON-NLS-1$ null, BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged1.Message") + Const.CR + BaseMessages.getString(PKG, "TransLog.Dialog.FileHasChanged2.Message") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$ MessageDialog.QUESTION, new String[] { BaseMessages.getString(PKG, "System.Button.Yes"), BaseMessages.getString(PKG, "System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$ 0, BaseMessages.getString(PKG, "TransLog.Dialog.Option.AutoSaveTransformation"), //$NON-NLS-1$ spoon.props.getAutoSave()); int answer = md.open(); if ((answer & 0xFF) == 0) { spoon.saveToFile(transMeta); } spoon.props.setAutoSave(md.getToggleState()); } } if (((transMeta.getName() != null && spoon.rep != null) || // Repository available & name set (transMeta.getFilename() != null && spoon.rep == null) // No repository & filename set ) && !transMeta.hasChanged() // Didn't change ) { if (trans == null || (trans != null && trans.isFinished())) { try { // Set the requested logging level. LogWriter.getInstance().setLogLevel(executionConfiguration.getLogLevel()); transMeta.injectVariables(executionConfiguration.getVariables()); // Set the named parameters Map<String, String> paramMap = executionConfiguration.getParams(); Set<String> keys = paramMap.keySet(); for ( String key : keys ) { transMeta.setParameterValue(key, Const.NVL(paramMap.get(key), "")); //$NON-NLS-1$ } transMeta.activateParameters(); // Do we need to clear the log before running? if (executionConfiguration.isClearingLog()) { transLogDelegate.clearLog(); } // Also make sure to clear the log entries in the central log store & registry if (trans!=null) { CentralLogStore.discardLines(trans.getLogChannelId(), true); } // Important: even though transMeta is passed to the Trans constructor, it is not the same object as is in memory // To be able to completely test this, we need to run it as we would normally do in pan trans = new Trans(transMeta, spoon.rep, transMeta.getName(), transMeta.getRepositoryDirectory().getPath(), transMeta.getFilename()); trans.setReplayDate(executionConfiguration.getReplayDate()); trans.setRepository(executionConfiguration.getRepository()); trans.setMonitored(true); log.logBasic(BaseMessages.getString(PKG, "TransLog.Log.TransformationOpened")); //$NON-NLS-1$ } catch (KettleException e) { trans = null; new ErrorDialog( shell, BaseMessages.getString(PKG, "TransLog.Dialog.ErrorOpeningTransformation.Title"), BaseMessages.getString(PKG, "TransLog.Dialog.ErrorOpeningTransformation.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } if (trans != null) { Map<String, String> arguments = executionConfiguration.getArguments(); final String args[]; if (arguments != null) args = convertArguments(arguments); else args = null; log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.LaunchingTransformation") + trans.getTransMeta().getName() + "]..."); //$NON-NLS-1$ //$NON-NLS-2$ trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled()); // Launch the step preparation in a different thread. // That way Spoon doesn't block anymore and that way we can follow the progress of the initialization final Thread parentThread = Thread.currentThread(); shell.getDisplay().asyncExec(new Runnable() { public void run() { addAllTabs(); prepareTrans(parentThread, args); } }); log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.StartedExecutionOfTransformation")); //$NON-NLS-1$ setControlStates(); } } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoStartTransformationTwice.Title")); //$NON-NLS-1$ m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoStartTransformationTwice.Message")); //$NON-NLS-1$ m.open(); } } else { if (transMeta.hasChanged()) { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning.Title")); //$NON-NLS-1$ m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning.Message")); //$NON-NLS-1$ m.open(); } else if (spoon.rep != null && transMeta.getName() == null) { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.GiveTransformationANameBeforeRunning.Title")); //$NON-NLS-1$ m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.GiveTransformationANameBeforeRunning.Message")); //$NON-NLS-1$ m.open(); } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning2.Title")); //$NON-NLS-1$ m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.SaveTransformationBeforeRunning2.Message")); //$NON-NLS-1$ m.open(); } } } } public void addAllTabs() { CTabItem tabItemSelection = null; if (extraViewTabFolder!=null && !extraViewTabFolder.isDisposed()) { tabItemSelection = extraViewTabFolder.getSelection(); } transHistoryDelegate.addTransHistory(); transLogDelegate.addTransLog(); transGridDelegate.addTransGrid(); transPerfDelegate.addTransPerf(); if (tabItemSelection!=null) { extraViewTabFolder.setSelection(tabItemSelection); } else { extraViewTabFolder.setSelection(transGridDelegate.getTransGridTab()); } XulToolbarbutton button = (XulToolbarbutton) toolbar.getElementById("trans-show-results"); //$NON-NLS-1$ button.setTooltiptext("Spoon.Tooltip.HideExecutionResults"); //$NON-NLS-1$ ToolItem toolItem = (ToolItem) button.getManagedObject(); toolItem.setImage(GUIResource.getInstance().getImageHideResults()); } public synchronized void debug(TransExecutionConfiguration executionConfiguration, TransDebugMeta transDebugMeta) { if (!running) { try { this.lastTransDebugMeta = transDebugMeta; LogWriter.getInstance().setLogLevel(executionConfiguration.getLogLevel()); if(log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "TransLog.Log.DoPreview")); //$NON-NLS-1$ String[] args = null; Map<String, String> arguments = executionConfiguration.getArguments(); if (arguments != null) { args = convertArguments(arguments); } transMeta.injectVariables(executionConfiguration.getVariables()); // Set the named parameters Map<String, String> paramMap = executionConfiguration.getParams(); Set<String> keys = paramMap.keySet(); for ( String key : keys ) { transMeta.setParameterValue(key, Const.NVL(paramMap.get(key), "")); //$NON-NLS-1$ } transMeta.activateParameters(); // Do we need to clear the log before running? if (executionConfiguration.isClearingLog()) { transLogDelegate.clearLog(); } // Create a new transformation to execution trans = new Trans(transMeta); trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled()); trans.setPreview(true); trans.prepareExecution(args); // Add the row listeners to the allocated threads transDebugMeta.addRowListenersToTransformation(trans); // What method should we call back when a break-point is hit? transDebugMeta.addBreakPointListers(new BreakPointListener() { public void breakPointHit(TransDebugMeta transDebugMeta, StepDebugMeta stepDebugMeta, RowMetaInterface rowBufferMeta, List<Object[]> rowBuffer) { showPreview(transDebugMeta, stepDebugMeta, rowBufferMeta, rowBuffer); } }); // Start the threads for the steps... startThreads(); debug = true; // Show the execution results view... shell.getDisplay().asyncExec(new Runnable() { public void run() { addAllTabs(); } }); } catch (Exception e) { new ErrorDialog( shell, BaseMessages.getString(PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Title"), BaseMessages.getString(PKG, "TransLog.Dialog.UnexpectedErrorDuringPreview.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoPreviewWhileRunning.Title")); //$NON-NLS-1$ m.setMessage(BaseMessages.getString(PKG, "TransLog.Dialog.DoNoPreviewWhileRunning.Message")); //$NON-NLS-1$ m.open(); } checkErrorVisuals(); } public synchronized void showPreview(final TransDebugMeta transDebugMeta, final StepDebugMeta stepDebugMeta, final RowMetaInterface rowBufferMeta, final List<Object[]> rowBuffer) { shell.getDisplay().asyncExec(new Runnable() { public void run() { if (isDisposed()) return; spoon.enableMenus(); // The transformation is now paused, indicate this in the log dialog... pausing = true; setControlStates(); checkErrorVisuals(); PreviewRowsDialog previewRowsDialog = new PreviewRowsDialog(shell, transMeta, SWT.APPLICATION_MODAL, stepDebugMeta.getStepMeta().getName(), rowBufferMeta, rowBuffer); previewRowsDialog.setProposingToGetMoreRows(true); previewRowsDialog.setProposingToStop(true); previewRowsDialog.open(); if (previewRowsDialog.isAskingForMoreRows()) { // clear the row buffer. // That way if you click resume, you get the next N rows for the step :-) rowBuffer.clear(); // Resume running: find more rows... pauseResume(); } if (previewRowsDialog.isAskingToStop()) { // Stop running stop(); } } }); } private String[] convertArguments(Map<String, String> arguments) { String[] argumentNames = arguments.keySet().toArray(new String[arguments.size()]); Arrays.sort(argumentNames); String args[] = new String[argumentNames.length]; for (int i = 0; i < args.length; i++) { String argumentName = argumentNames[i]; args[i] = arguments.get(argumentName); } return args; } public void stop() { if (running && !halting) { halting = true; trans.stopAll(); log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.ProcessingOfTransformationStopped")); //$NON-NLS-1$ running = false; initialized = false; halted = false; halting = false; setControlStates(); transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping } } public synchronized void pauseResume() { if (running) { // Get the pause toolbar item if (!pausing) { pausing = true; trans.pauseRunning(); setControlStates(); } else { pausing = false; trans.resumeRunning(); setControlStates(); } } } private boolean controlDisposed(XulToolbarbutton button) { if (button.getManagedObject() instanceof Widget) { Widget widget = (Widget) button.getManagedObject(); return widget.isDisposed(); } return false; } public synchronized void setControlStates() { if (getDisplay().isDisposed()) return; if (((Control)toolbar.getManagedObject()).isDisposed()) return; getDisplay().asyncExec(new Runnable() { public void run() { // Start/Run button... XulToolbarbutton runButton = (XulToolbarbutton) toolbar.getElementById("process-run"); //$NON-NLS-1$ if (runButton != null && !controlDisposed(runButton)) { runButton.setDisabled(running); } // Pause button... XulToolbarbutton pauseButton = (XulToolbarbutton) toolbar.getElementById("trans-pause"); //$NON-NLS-1$ if (pauseButton != null && !controlDisposed(pauseButton)) { pauseButton.setDisabled(!running); pauseButton.setLabel(pausing ? RESUME_TEXT : PAUSE_TEXT); pauseButton.setTooltiptext(pausing ? BaseMessages.getString(PKG, "Spoon.Tooltip.ResumeTranformation") : BaseMessages //$NON-NLS-1$ .getString(PKG, "Spoon.Tooltip.PauseTranformation")); //$NON-NLS-1$ } // Stop button... XulToolbarbutton stopButton = (XulToolbarbutton) toolbar.getElementById("trans-stop"); //$NON-NLS-1$ if (stopButton != null && !controlDisposed(stopButton)) { stopButton.setDisabled(!running); } // Debug button... XulToolbarbutton debugButton = (XulToolbarbutton) toolbar.getElementById("trans-debug"); //$NON-NLS-1$ if (debugButton != null && !controlDisposed(debugButton)) { debugButton.setDisabled(running); } // Preview button... XulToolbarbutton previewButton = (XulToolbarbutton) toolbar.getElementById("trans-preview"); //$NON-NLS-1$ if (previewButton != null && !controlDisposed(previewButton)) { previewButton.setDisabled(running); } } }); } private synchronized void prepareTrans(final Thread parentThread, final String[] args) { Runnable runnable = new Runnable() { public void run() { try { trans.prepareExecution(args); initialized = true; } catch (KettleException e) { log.logError(trans.getName(), "Preparing transformation execution failed", e); //$NON-NLS-1$ initialized = false; checkErrorVisuals(); } halted = trans.hasHaltedSteps(); checkStartThreads();// After init, launch the threads. } }; Thread thread = new Thread(runnable); thread.start(); } private void checkStartThreads() { if (initialized && !running && trans != null) { startThreads(); } } private synchronized void startThreads() { running = true; try { // Add a listener to the transformation. // If the transformation is done, we want to do the end processing, etc. trans.addTransListener(new TransListener() { public void transFinished(Trans trans) { checkTransEnded(); // checkErrors(); } }); trans.startThreads(); setControlStates(); } catch (KettleException e) { log.logError("Error starting step threads", e); //$NON-NLS-1$ checkErrorVisuals(); } // See if we have to fire off the performance graph updater etc. getDisplay().asyncExec(new Runnable() { public void run() { if (transPerfDelegate.getTransPerfTab() != null) { // If there is a tab open, try to the correct content on there now transPerfDelegate.setupContent(); transPerfDelegate.layoutPerfComposite(); } } }); } private String lastLog; private void checkTransEnded() { if (trans != null) { if (trans.isFinished() && (running || halted)) { log.logMinimal(BaseMessages.getString(PKG, "TransLog.Log.TransformationHasFinished")); //$NON-NLS-1$ running = false; initialized = false; halted = false; halting = false; if (spoonHistoryRefresher != null) spoonHistoryRefresher.markRefreshNeeded(); setControlStates(); // OK, also see if we had a debugging session going on. // If so and we didn't hit a breakpoint yet, display the show // preview dialog... if (debug && lastTransDebugMeta != null && lastTransDebugMeta.getTotalNumberOfHits() == 0) { debug = false; showLastPreviewResults(); } debug = false; checkErrorVisuals(); shell.getDisplay().asyncExec(new Runnable() { public void run() { redraw(); } }); } } } private void checkErrorVisuals() { if (trans.getErrors()>0) { // Get the logging text and filter it out. Store it in the stepLogMap... stepLogMap = new HashMap<StepMeta, String>(); lastLog = null; shell.getDisplay().syncExec(new Runnable() { public void run() { lastLog = transLogDelegate.getLoggingText(); } }); if (!Const.isEmpty(lastLog)) { String lines[] = lastLog.split(Const.CR); for (int i=0;i<lines.length && i<30;i++) { if (lines[i].indexOf(Log4jKettleLayout.ERROR_STRING)>=0) { // This is an error line, log it! // Determine to which step it belongs! for (StepMeta stepMeta : transMeta.getSteps()) { if (lines[i].indexOf(stepMeta.getName())>=0) { String line = lines[i]; int index = lines[i].indexOf(") : "); // $NON-NLS-1$ TODO: define this as a more generic marker / constant value //$NON-NLS-1$ if (index>0) line=lines[i].substring(index+3); String str = stepLogMap.get(stepMeta); if (str==null) { stepLogMap.put(stepMeta, line); } else { stepLogMap.put(stepMeta, str+Const.CR+line); } } } } } } } else { stepLogMap = null; } // Redraw the canvas to show the error icons etc. shell.getDisplay().asyncExec(new Runnable() { public void run() { redraw(); } }); } public synchronized void showLastPreviewResults() { if (lastTransDebugMeta == null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty()) return; final List<String> stepnames = new ArrayList<String>(); final List<RowMetaInterface> rowMetas = new ArrayList<RowMetaInterface>(); final List<List<Object[]>> rowBuffers = new ArrayList<List<Object[]>>(); // Assemble the buffers etc in the old style... for (StepMeta stepMeta : lastTransDebugMeta.getStepDebugMetaMap().keySet()) { StepDebugMeta stepDebugMeta = lastTransDebugMeta.getStepDebugMetaMap().get(stepMeta); stepnames.add(stepMeta.getName()); rowMetas.add(stepDebugMeta.getRowBufferMeta()); rowBuffers.add(stepDebugMeta.getRowBuffer()); } getDisplay().asyncExec(new Runnable() { public void run() { EnterPreviewRowsDialog dialog = new EnterPreviewRowsDialog(shell, SWT.NONE, stepnames, rowMetas, rowBuffers); dialog.open(); } }); } /** * Open the transformation mentioned in the mapping... */ public void openMapping() { try { MappingMeta meta = (MappingMeta) this.currentStep.getStepMetaInterface(); TransMeta mappingMeta = MappingMeta.loadMappingMeta(meta.getFileName(), meta.getTransName(), meta.getDirectoryPath(), spoon.rep, transMeta); mappingMeta.clearChanged(); spoon.addTransGraph(mappingMeta); TransGraph subTransGraph = spoon.getActiveTransGraph(); attachActiveTrans(subTransGraph, this.currentStep); } catch(Exception e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "TransGraph.Exception.UnableToLoadMapping.Title"), BaseMessages.getString(PKG, "TransGraph.Exception.UnableToLoadMapping.Message"), e); //$NON-NLS-1$//$NON-NLS-2$ } } /** * Finds the last active transformation in the running job to the opened transMeta * * @param transGraph * @param jobEntryCopy */ private void attachActiveTrans(TransGraph transGraph, StepMeta stepMeta) { if (trans!=null && transGraph!=null) { Trans subTransformation = trans.getActiveSubtransformations().get(stepMeta.getName()); transGraph.setTrans(subTransformation); if (!transGraph.isExecutionResultsPaneVisible()) { transGraph.showExecutionResults(); } transGraph.setControlStates(); } } /** * @return the running */ public boolean isRunning() { return running; } /** * @param running the running to set */ public void setRunning(boolean running) { this.running = running; } /** * @return the lastTransDebugMeta */ public TransDebugMeta getLastTransDebugMeta() { return lastTransDebugMeta; } /** * @return the halting */ public boolean isHalting() { return halting; } /** * @param halting the halting to set */ public void setHalting(boolean halting) { this.halting = halting; } /** * @return the stepLogMap */ public Map<StepMeta, String> getStepLogMap() { return stepLogMap; } /** * @param stepLogMap * the stepLogMap to set */ public void setStepLogMap(Map<StepMeta, String> stepLogMap) { this.stepLogMap = stepLogMap; } public void dumpLoggingRegistry() { LoggingRegistry registry = LoggingRegistry.getInstance(); Map<String, LoggingObjectInterface> loggingMap = registry.getMap(); for (LoggingObjectInterface loggingObject : loggingMap.values()) { System.out.println(loggingObject.getLogChannelId()+" - "+loggingObject.getObjectName()+" - "+loggingObject.getObjectType()); //$NON-NLS-1$ //$NON-NLS-2$ } } public HasLogChannelInterface getLogChannelProvider() { return trans; } public synchronized void setTrans(Trans trans) { this.trans = trans; pausing = trans.isPaused(); initialized = trans.isInitializing(); running = trans.isRunning(); halted = trans.isStopped(); } public void sniffInput() { sniff(true, false, false); } public void sniffOutput() { sniff(false, true, false); } public void sniffError() { sniff(false, false, true); } public void sniff(final boolean input, final boolean output, final boolean error) { StepMeta stepMeta = getCurrentStep(); if(stepMeta == null || trans == null){ return; } final StepInterface runThread = trans.findRunThread(stepMeta.getName()); if (runThread!=null) { List<Object[]> rows = new ArrayList<Object[]>(); final PreviewRowsDialog dialog = new PreviewRowsDialog(shell, trans, SWT.NONE, stepMeta.getName(), null, rows); dialog.setDynamic(true); final RowListener rowListener = new RowListener() { public void rowReadEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException { if (input) { try { dialog.addDataRow(rowMeta, rowMeta.cloneRow(row)); } catch (KettleValueException e) { throw new KettleStepException(e); } } } public void rowWrittenEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException { if (output) { try { dialog.addDataRow(rowMeta, rowMeta.cloneRow(row)); } catch (KettleValueException e) { throw new KettleStepException(e); } } } public void errorRowWrittenEvent(RowMetaInterface rowMeta, Object[] row) throws KettleStepException { if (error) { try { dialog.addDataRow(rowMeta, rowMeta.cloneRow(row)); } catch (KettleValueException e) { throw new KettleStepException(e); } } } }; getDisplay().asyncExec(new Runnable() { public void run() { dialog.open(); // remove the listener when close is hit! runThread.removeRowListener(rowListener); } }); runThread.addRowListener(rowListener); } } /* (non-Javadoc) * @see org.pentaho.ui.xul.impl.XulEventHandler#getName() */ public String getName() { return "transgraph"; //$NON-NLS-1$ } /* (non-Javadoc) * @see org.pentaho.ui.xul.impl.XulEventHandler#getXulDomContainer() */ public XulDomContainer getXulDomContainer() { return xulDomContainer; } /* (non-Javadoc) * @see org.pentaho.ui.xul.impl.XulEventHandler#setName(java.lang.String) */ public void setName(String arg0) { } /* (non-Javadoc) * @see org.pentaho.ui.xul.impl.XulEventHandler#setXulDomContainer(org.pentaho.ui.xul.XulDomContainer) */ public void setXulDomContainer(XulDomContainer xulDomContainer) { this.xulDomContainer = xulDomContainer; } public boolean canHandleSave() { return true; } }
package ch.elexis.core.ui.documents.provider; import java.util.ArrayList; import java.util.List; import org.eclipse.jface.fieldassist.IContentProposal; import org.eclipse.jface.fieldassist.IContentProposalProvider; import ch.elexis.core.findings.util.ValueSetServiceHolder; public class ValueSetProposalProvider implements IContentProposalProvider { public static final String EPRDOCUMENT_CLASSCODE = "EprDocumentClassCode"; public static final String EPRDOCUMENT_PRACTICESETTINGCODE = "EprDocumentPracticeSettingCode"; private final String valueSetName; public ValueSetProposalProvider(String valueSetName){ this.valueSetName = valueSetName; } @Override public IContentProposal[] getProposals(String searchString, int position){ List<IContentProposal> ret = new ArrayList<IContentProposal>(); if (searchString != null && !searchString.isEmpty()) { return ValueSetServiceHolder.getIValueSetService() .getValueSetByName(valueSetName).stream() .filter( o -> o.getDisplay().toLowerCase().contains(searchString.trim().toLowerCase())) .map(o -> new CodingContentProposal(o.getDisplay(), o)) .toArray(e -> new IContentProposal[]{}); } return ret.toArray(new IContentProposal[ret.size()]); } }
// $Id: IpAddress.java,v 1.27 2005/08/26 10:18:48 belaban Exp $ package org.jgroups.stack; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jgroups.Address; import org.jgroups.Global; import java.io.*; import java.net.InetAddress; /** * Network-dependent address (Internet). Generated by the bottommost layer of the protocol * stack (UDP). Contains an InetAddress and port. * @author Bela Ban */ public class IpAddress implements Address { private InetAddress ip_addr=null; private int port=0; private byte[] additional_data=null; protected static final Log log=LogFactory.getLog(IpAddress.class); static boolean resolve_dns=false; transient int size=-1; static { try { resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); } catch (SecurityException ex){ resolve_dns=false; } } // Used only by Externalization public IpAddress() { } public IpAddress(String i, int p) { port=p; try { ip_addr=InetAddress.getByName(i); } catch(Exception e) { if(log.isWarnEnabled()) log.warn("failed to get " + i + ": " + e); } if(this.ip_addr == null) setAddressToLocalHost(); } public IpAddress(InetAddress i, int p) { ip_addr=i; port=p; if(this.ip_addr == null) setAddressToLocalHost(); } private void setAddressToLocalHost() { try { ip_addr=InetAddress.getLocalHost(); // get first NIC found (on multi-homed systems) // size=size(); } catch(Exception e) { if(log.isWarnEnabled()) log.warn("exception: " + e); } } public IpAddress(int port) { this(port, true); } public IpAddress(int port, boolean set_default_host) { this.port=port; if(set_default_host) setAddressToLocalHost(); } public InetAddress getIpAddress() {return ip_addr;} public int getPort() {return port;} public boolean isMulticastAddress() { return ip_addr != null && ip_addr.isMulticastAddress(); } /** * Returns the additional_data. * @return byte[] */ public byte[] getAdditionalData() { return additional_data; } /** * Sets the additional_data. * @param additional_data The additional_data to set */ public void setAdditionalData(byte[] additional_data) { this.additional_data = additional_data; size=size(); } /** * Establishes an order between 2 addresses. Assumes other contains non-null IpAddress. * Excludes channel_name from comparison. * @return 0 for equality, value less than 0 if smaller, greater than 0 if greater. */ public int compare(IpAddress other) { return compareTo(other); } /** * implements the java.lang.Comparable interface * @see java.lang.Comparable * @param o - the Object to be compared * @return a negative integer, zero, or a positive integer as this object is less than, * equal to, or greater than the specified object. * @exception java.lang.ClassCastException - if the specified object's type prevents it * from being compared to this Object. */ public int compareTo(Object o) { int h1, h2, rc; if ((o == null) || !(o instanceof IpAddress)) throw new ClassCastException("comparison between different classes: the other object is " + (o != null? o.getClass() : o)); IpAddress other = (IpAddress) o; if(ip_addr == null) if (other.ip_addr == null) return port < other.port ? -1 : (port > other.port ? 1 : 0); else return -1; h1=ip_addr.hashCode(); h2=other.ip_addr.hashCode(); rc=h1 < h2? -1 : h1 > h2? 1 : 0; return rc != 0 ? rc : port < other.port ? -1 : (port > other.port ? 1 : 0); } public boolean equals(Object obj) { if(obj == null) return false; return compareTo(obj) == 0 ? true : false; } public int hashCode() { return ip_addr != null ? ip_addr.hashCode() + port : port; } public String toString() { StringBuffer sb=new StringBuffer(); if(ip_addr == null) sb.append("<null>"); else { if(ip_addr.isMulticastAddress()) sb.append(ip_addr.getHostAddress()); else { String host_name=null; if(resolve_dns) host_name=ip_addr.getHostName(); else host_name=ip_addr.getHostAddress(); appendShortName(host_name, sb); } } sb.append(":" + port); if(additional_data != null) sb.append(" (additional data: ").append(additional_data.length).append(" bytes)"); return sb.toString(); } /** * Input: "daddy.nms.fnc.fujitsu.com", output: "daddy". Appends result to string buffer 'sb'. * @param hostname The hostname in long form. Guaranteed not to be null * @param sb The string buffer to which the result is to be appended */ private void appendShortName(String hostname, StringBuffer sb) { if(hostname == null) return; int index=hostname.indexOf('.'); if(index > 0 && !Character.isDigit(hostname.charAt(0))) sb.append(hostname.substring(0, index)); else sb.append(hostname); } public void writeExternal(ObjectOutput out) throws IOException { byte[] address = ip_addr.getAddress(); out.write(address); out.writeInt(port); if(additional_data != null) { out.writeInt(additional_data.length); out.write(additional_data, 0, additional_data.length); } else out.writeInt(0); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int len=0; //read the four bytes byte[] a = new byte[4]; //in theory readFully(byte[]) should be faster //than read(byte[]) since latter reads // 4 bytes one at a time in.readFully(a); //then read the port port = in.readInt(); //look up an instance in the cache this.ip_addr=InetAddress.getByAddress(a); len=in.readInt(); if(len > 0) { additional_data=new byte[len]; in.readFully(additional_data, 0, additional_data.length); } } public void writeTo(DataOutputStream out) throws IOException { byte[] address; if(ip_addr != null) { address=ip_addr.getAddress(); out.writeShort(address.length); // 2 bytes out.write(address, 0, address.length); } else { out.writeShort(0); } out.writeInt(port); if(additional_data != null) { out.writeBoolean(true); // 1 byte out.writeInt(additional_data.length); out.write(additional_data, 0, additional_data.length); } else { out.writeBoolean(false); } } public void readFrom(DataInputStream in) throws IOException { int len=in.readShort(); if(len > 0) { //read the four bytes byte[] a = new byte[len]; //in theory readFully(byte[]) should be faster //than read(byte[]) since latter reads // 4 bytes one at a time in.readFully(a); //look up an instance in the cache this.ip_addr=InetAddress.getByAddress(a); } //then read the port port=in.readInt(); if(in.readBoolean() == false) return; len=in.readInt(); if(len > 0) { additional_data=new byte[len]; in.readFully(additional_data, 0, additional_data.length); } } public int size() { if(size >= 0) return size; // length + 4 bytes for port + 1 for additional_data available int tmp_size=Global.SHORT_SIZE + Global.INT_SIZE + Global.BYTE_SIZE; if(ip_addr != null) tmp_size+=ip_addr.getAddress().length; // 4 bytes for IPv4 if(additional_data != null) tmp_size+=additional_data.length+Global.INT_SIZE; size=tmp_size; return tmp_size; } public Object clone() throws CloneNotSupportedException { IpAddress ret=new IpAddress(ip_addr, port); if(additional_data != null) { ret.additional_data=new byte[additional_data.length]; System.arraycopy(additional_data, 0, ret.additional_data, 0, additional_data.length); } return ret; } }
package org.pentaho.di.ui.spoon.trans; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.MessageDialogWithToggle; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.window.DefaultToolTip; import org.eclipse.jface.window.ToolTip; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.DropTargetListener; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.FocusAdapter; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.Props; import org.pentaho.di.core.dnd.DragAndDropContainer; import org.pentaho.di.core.dnd.XMLTransfer; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.Redrawable; import org.pentaho.di.core.gui.SnapAllignDistribute; import org.pentaho.di.core.gui.SpoonInterface; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.i18n.LanguageChoice; import org.pentaho.di.repository.Repository; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.DatabaseImpact; import org.pentaho.di.trans.StepLoader; import org.pentaho.di.trans.StepPlugin; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransExecutionConfiguration; import org.pentaho.di.trans.TransHopMeta; import org.pentaho.di.trans.TransListener; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.debug.BreakPointListener; import org.pentaho.di.trans.debug.StepDebugMeta; import org.pentaho.di.trans.debug.TransDebugMeta; import org.pentaho.di.trans.step.RemoteStep; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.steps.tableinput.TableInputMeta; import org.pentaho.di.ui.core.ConstUI; import org.pentaho.di.ui.core.PropsUI; import org.pentaho.di.ui.core.dialog.EnterNumberDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.dialog.PreviewRowsDialog; import org.pentaho.di.ui.core.dialog.StepFieldsDialog; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.core.gui.XulHelper; import org.pentaho.di.ui.core.widget.CheckBoxToolTip; import org.pentaho.di.ui.core.widget.CheckBoxToolTipListener; import org.pentaho.di.ui.spoon.AreaOwner; import org.pentaho.di.ui.spoon.Messages; import org.pentaho.di.ui.spoon.Spoon; import org.pentaho.di.ui.spoon.TabItemInterface; import org.pentaho.di.ui.spoon.TransPainter; import org.pentaho.di.ui.spoon.XulMessages; import org.pentaho.di.ui.spoon.dialog.DeleteMessageBox; import org.pentaho.di.ui.spoon.dialog.EnterPreviewRowsDialog; import org.pentaho.di.ui.spoon.dialog.SearchFieldsProgressDialog; import org.pentaho.di.ui.trans.dialog.TransDialog; import org.pentaho.xul.menu.XulMenu; import org.pentaho.xul.menu.XulMenuChoice; import org.pentaho.xul.menu.XulPopupMenu; import org.pentaho.xul.swt.menu.MenuChoice; import org.pentaho.xul.toolbar.XulToolbar; import org.pentaho.xul.toolbar.XulToolbarButton; /** * This class handles the display of the transformations in a graphical way using icons, arrows, etc. * One transformation is handled per TransGraph * * @author Matt * @since 17-mei-2003 * */ public class TransGraph extends Composite implements Redrawable, TabItemInterface { private static final LogWriter log = LogWriter.getInstance(); private static final int HOP_SEL_MARGIN = 9; private static final String XUL_FILE_TRANS_TOOLBAR = "ui/trans-toolbar.xul"; public static final String XUL_FILE_TRANS_TOOLBAR_PROPERTIES = "ui/trans-toolbar.properties"; public final static String START_TEXT = Messages.getString("TransLog.Button.StartTransformation"); //$NON-NLS-1$ public final static String PAUSE_TEXT = Messages.getString("TransLog.Button.PauseTransformation"); //$NON-NLS-1$ public final static String RESUME_TEXT = Messages.getString("TransLog.Button.ResumeTransformation"); //$NON-NLS-1$ public final static String STOP_TEXT = Messages.getString("TransLog.Button.StopTransformation"); //$NON-NLS-1$ private TransMeta transMeta; public Trans trans; private Shell shell; private Composite mainComposite; private Canvas canvas; private DefaultToolTip toolTip; private CheckBoxToolTip helpTip; private XulToolbar toolbar; private int iconsize; private Point lastclick; private Point lastMove; private Point previous_step_locations[]; private Point previous_note_locations[]; private StepMeta selected_steps[]; private StepMeta selected_step; private NotePadMeta selected_notes[]; private NotePadMeta selected_note; private TransHopMeta candidate; private Point drop_candidate; private Spoon spoon; private Point offset, iconoffset, noteoffset; private ScrollBar hori; private ScrollBar vert; // public boolean shift, control; private boolean split_hop; private int last_button; private TransHopMeta last_hop_split; private Rectangle selrect; /** * A list of remarks on the current Transformation... */ private List<CheckResultInterface> remarks; /** * A list of impacts of the current transformation on the used databases. */ private List<DatabaseImpact> impact; /** * Indicates whether or not an impact analysis has already run. */ private boolean impactFinished; private TransHistoryRefresher spoonHistoryRefresher; private TransDebugMeta lastTransDebugMeta; protected static Map<String, org.pentaho.xul.swt.menu.Menu> menuMap = new HashMap<String, org.pentaho.xul.swt.menu.Menu>(); protected int currentMouseX = 0; protected int currentMouseY = 0; protected NotePadMeta ni = null; protected TransHopMeta currentHop; protected StepMeta currentStep; private List<AreaOwner> areaOwners; // private Text filenameLabel; private SashForm sashForm; public Composite extraViewComposite; public CTabFolder extraViewTabFolder; private boolean initialized; private boolean running; private boolean halted; private boolean halting; private boolean debug; private boolean pausing; private int magnificationIndex=4; private float magnification = TransPainter.magnifications[magnificationIndex]; public TransLogDelegate transLogDelegate; public TransGridDelegate transGridDelegate; public TransHistoryDelegate transHistoryDelegate; public TransPerfDelegate transPerfDelegate; private Label zoomLabel; public void setCurrentNote( NotePadMeta ni ) { this.ni = ni; } public NotePadMeta getCurrentNote() { return ni; } public TransHopMeta getCurrentHop() { return currentHop; } public void setCurrentHop(TransHopMeta currentHop) { this.currentHop = currentHop; } public StepMeta getCurrentStep() { return currentStep; } public void setCurrentStep(StepMeta currentStep) { this.currentStep = currentStep; } public TransGraph(Composite parent, final Spoon spoon, final TransMeta transMeta) { super(parent, SWT.NONE); this.shell = parent.getShell(); this.spoon = spoon; this.transMeta = transMeta; this.areaOwners = new ArrayList<AreaOwner>(); transLogDelegate = new TransLogDelegate(spoon, this); transGridDelegate = new TransGridDelegate(spoon, this); transHistoryDelegate = new TransHistoryDelegate(spoon, this); transPerfDelegate = new TransPerfDelegate(spoon, this); setLayout(new FormLayout()); // Add a tool-bar at the top of the tab // The form-data is set on the native widget automatically addToolBar(); setControlStates(); // enable / disable the icons in the toolbar too. // The main composite contains the graph view, but if needed also // a view with an extra tab containing log, etc. mainComposite = new Composite(this, SWT.NONE); mainComposite.setLayout(new FillLayout()); FormData fdMainComposite = new FormData(); fdMainComposite.left = new FormAttachment(0,0); fdMainComposite.top = new FormAttachment((Control)toolbar.getNativeObject(),0); fdMainComposite.right = new FormAttachment(100,0); fdMainComposite.bottom= new FormAttachment(100,0); mainComposite.setLayoutData(fdMainComposite); // To allow for a splitter later on, we will add the splitter here... sashForm = new SashForm(mainComposite, SWT.VERTICAL ); // sashForm.setForeground(GUIResource.getInstance().getColorBlack()) // Add a canvas below it, use up all space initially canvas = new Canvas(sashForm, SWT.V_SCROLL | SWT.H_SCROLL | SWT.NO_BACKGROUND | SWT.BORDER ); sashForm.setWeights(new int[] { 100, } ); try { // first get the XML document menuMap = XulHelper.createPopupMenus(SpoonInterface.XUL_FILE_MENUS, shell, new XulMessages(),"trans-graph-hop", "trans-graph-entry" ,"trans-graph-background","trans-graph-note" ); } catch (Throwable t ) { // TODO log this t.printStackTrace(); } toolTip = new DefaultToolTip(canvas, ToolTip.NO_RECREATE, true); toolTip.setRespectMonitorBounds(true); toolTip.setRespectDisplayBounds(true); toolTip.setPopupDelay(350); toolTip.setShift(new org.eclipse.swt.graphics.Point(ConstUI.TOOLTIP_OFFSET,ConstUI.TOOLTIP_OFFSET)); helpTip = new CheckBoxToolTip(canvas); helpTip.addCheckBoxToolTipListener(new CheckBoxToolTipListener() { public void checkBoxSelected(boolean enabled) { spoon.props.setShowingHelpToolTips(enabled); } }); iconsize = spoon.props.getIconSize(); clearSettings(); remarks = new ArrayList<CheckResultInterface>(); impact = new ArrayList<DatabaseImpact>(); impactFinished = false; hori = canvas.getHorizontalBar(); vert = canvas.getVerticalBar(); hori.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { redraw(); } }); vert.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { redraw(); } }); hori.setThumb(100); vert.setThumb(100); hori.setVisible(true); vert.setVisible(true); setVisible(true); newProps(); canvas.setBackground(GUIResource.getInstance().getColorBackground()); canvas.addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { if (!spoon.isStopped()) TransGraph.this.paintControl(e); } }); selected_steps = null; lastclick = null; /* * Handle the mouse... */ canvas.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent e) { clearSettings(); Point real = screen2real(e.x, e.y); // Hide the tooltip! hideToolTips(); StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null) { if (e.button == 1) editStep(stepMeta); else editDescription(stepMeta); } else { // Check if point lies on one of the many hop-lines... TransHopMeta online = findHop(real.x, real.y); if (online != null) { editHop(online); } else { NotePadMeta ni = transMeta.getNote(real.x, real.y); if (ni != null) { selected_note = null; editNote(ni); } else { // See if the double click was in one of the area's... for (AreaOwner areaOwner : areaOwners) { if (areaOwner.contains(real.x, real.y)) { if ( areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_PARTITIONING_CURRENT_STEP) ) { StepMeta step = (StepMeta) areaOwner.getParent(); spoon.editPartitioning(transMeta, step); break; } } } } } } } public void mouseDown(MouseEvent e) { clearSettings(); boolean alt = (e.stateMask & SWT.ALT) != 0; boolean control = (e.stateMask & SWT.CONTROL) != 0; last_button = e.button; Point real = screen2real(e.x, e.y); lastclick = new Point(real.x, real.y); // Hide the tooltip! hideToolTips(); // Set the pop-up menu if (e.button==3) { setMenu(real.x, real.y); return; } // Did we click on a step? StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null) { // ALT-Click: edit error handling if (e.button==1 && alt && stepMeta.supportsErrorHandling()) { spoon.editStepErrorHandling(transMeta, stepMeta); return; } selected_steps = transMeta.getSelectedSteps(); selected_step = stepMeta; // When an icon is moved that is not selected, it gets // selected too late. // It is not captured here, but in the mouseMoveListener... previous_step_locations = transMeta.getSelectedStepLocations(); Point p = stepMeta.getLocation(); iconoffset = new Point(real.x - p.x, real.y - p.y); } else { // Dit we hit a note? NotePadMeta ni = transMeta.getNote(real.x, real.y); if (ni != null && last_button == 1) { selected_notes = transMeta.getSelectedNotes(); selected_note = ni; Point loc = ni.getLocation(); previous_note_locations = transMeta.getSelectedNoteLocations(); noteoffset = new Point(real.x - loc.x, real.y - loc.y); } else { if (!control) selrect = new Rectangle(real.x, real.y, 0, 0); } } redraw(); } public void mouseUp(MouseEvent e) { boolean control = (e.stateMask & SWT.CONTROL) != 0; if (iconoffset == null) iconoffset = new Point(0, 0); Point real = screen2real(e.x, e.y); Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y); // Quick new hop option? (drag from one step to another) if (candidate != null) { if (transMeta.findTransHop(candidate) == null) { spoon.newHop(transMeta, candidate); } candidate = null; selected_steps = null; redraw(); } // Did we select a region on the screen? Mark steps in region as // selected else { if (selrect != null) { selrect.width = real.x - selrect.x; selrect.height = real.y - selrect.y; transMeta.unselectAll(); selectInRect(transMeta,selrect); selrect = null; redraw(); } // Clicked on an icon? else { if (selected_step != null) { if (e.button == 1) { Point realclick = screen2real(e.x, e.y); if (lastclick.x == realclick.x && lastclick.y == realclick.y) { // Flip selection when control is pressed! if (control) { selected_step.flipSelected(); } else { // Otherwise, select only the icon clicked on! transMeta.unselectAll(); selected_step.setSelected(true); } } else { // Find out which Steps & Notes are selected selected_steps = transMeta.getSelectedSteps(); selected_notes = transMeta.getSelectedNotes(); // We moved around some items: store undo info... boolean also = false; if (selected_notes != null && previous_note_locations != null) { int indexes[] = transMeta.getNoteIndexes(selected_notes); addUndoPosition(selected_notes, indexes, previous_note_locations, transMeta.getSelectedNoteLocations(), also); also = selected_steps != null && selected_steps.length > 0; } if (selected_steps != null && previous_step_locations != null) { int indexes[] = transMeta.getStepIndexes(selected_steps); addUndoPosition(selected_steps, indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also); } } } // OK, we moved the step, did we move it across a hop? // If so, ask to split the hop! if (split_hop) { TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selected_step); if (hi != null) { int id = 0; if (!spoon.props.getAutoSplit()) { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("TransGraph.Dialog.SplitHop.Title"), null, //$NON-NLS-1$ Messages.getString("TransGraph.Dialog.SplitHop.Message") + Const.CR + hi.toString(), MessageDialog.QUESTION, new String[] { //$NON-NLS-1$ Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") }, 0, Messages.getString("TransGraph.Dialog.Option.SplitHop.DoNotAskAgain"), spoon.props.getAutoSplit()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ id = md.open(); spoon.props.setAutoSplit(md.getToggleState()); } if ( (id&0xFF) == 0) // Means: "Yes" button clicked! { // Only split A-->--B by putting C in between IF... // C-->--A or B-->--C don't exists... // A ==> hi.getFromStep() // B ==> hi.getToStep(); // C ==> selected_step if (transMeta.findTransHop(selected_step, hi.getFromStep())==null && transMeta.findTransHop(hi.getToStep(), selected_step)==null) { TransHopMeta newhop1 = new TransHopMeta(hi.getFromStep(), selected_step); transMeta.addTransHop(newhop1); spoon.addUndoNew(transMeta, new TransHopMeta[] { newhop1 }, new int[] { transMeta.indexOfTransHop(newhop1) }, true); TransHopMeta newhop2 = new TransHopMeta(selected_step, hi.getToStep()); transMeta.addTransHop(newhop2); spoon.addUndoNew(transMeta, new TransHopMeta[] { newhop2 }, new int[] { transMeta.indexOfTransHop(newhop2) }, true); int idx = transMeta.indexOfTransHop(hi); spoon.addUndoDelete(transMeta, new TransHopMeta[] { hi }, new int[] { idx }, true); transMeta.removeTransHop(idx); spoon.refreshTree(); } else { // Silently discard this hop-split attempt. } } } split_hop = false; } selected_steps = null; selected_notes = null; selected_step = null; selected_note = null; redraw(); } // Notes? else { if (selected_note != null) { if (e.button == 1) { if (lastclick.x == e.x && lastclick.y == e.y) { // Flip selection when control is pressed! if (control) { selected_note.flipSelected(); } else { // Otherwise, select only the note clicked on! transMeta.unselectAll(); selected_note.setSelected(true); } } else { // Find out which Steps & Notes are selected selected_steps = transMeta.getSelectedSteps(); selected_notes = transMeta.getSelectedNotes(); // We moved around some items: store undo info... boolean also = false; if (selected_notes != null && previous_note_locations != null) { int indexes[] = transMeta.getNoteIndexes(selected_notes); addUndoPosition(selected_notes, indexes, previous_note_locations, transMeta.getSelectedNoteLocations(), also); also = selected_steps != null && selected_steps.length > 0; } if (selected_steps != null && previous_step_locations != null) { int indexes[] = transMeta.getStepIndexes(selected_steps); addUndoPosition(selected_steps, indexes, previous_step_locations, transMeta.getSelectedStepLocations(), also); } } } selected_notes = null; selected_steps = null; selected_step = null; selected_note = null; } } } } last_button = 0; } }); canvas.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent e) { boolean shift = (e.stateMask & SWT.SHIFT) != 0; // disable the tooltip toolTip.hide(); // Remember the last position of the mouse for paste with keyboard lastMove = new Point(e.x, e.y); Point real = screen2real(e.x, e.y); if (iconoffset == null) iconoffset = new Point(0, 0); Point icon = new Point(real.x - iconoffset.x, real.y - iconoffset.y); if (noteoffset == null) noteoffset = new Point(0, 0); Point note = new Point(real.x - noteoffset.x, real.y - noteoffset.y); if (last_button==0 && !helpTip.isVisible()) setToolTip(real.x, real.y); // First see if the icon we clicked on was selected. // If the icon was not selected, we should unselect all other // icons, // selected and move only the one icon if (selected_step != null && !selected_step.isSelected()) { // System.out.println("STEPS: Unselected all"); transMeta.unselectAll(); selected_step.setSelected(true); selected_steps = new StepMeta[] { selected_step }; previous_step_locations = new Point[] { selected_step.getLocation() }; } if (selected_note != null && !selected_note.isSelected()) { // System.out.println("NOTES: Unselected all"); transMeta.unselectAll(); selected_note.setSelected(true); selected_notes = new NotePadMeta[] { selected_note }; previous_note_locations = new Point[] { selected_note.getLocation() }; } // Did we select a region...? if (selrect != null) { selrect.width = real.x - selrect.x; selrect.height = real.y - selrect.y; redraw(); } // Move around steps & notes else if (selected_step != null) { if (last_button == 1 && !shift) { /* * One or more icons are selected and moved around... * * new : new position of the ICON (not the mouse pointer) dx : difference with previous * position */ int dx = icon.x - selected_step.getLocation().x; int dy = icon.y - selected_step.getLocation().y; // See if we have a hop-split candidate TransHopMeta hi = findHop(icon.x + iconsize / 2, icon.y + iconsize / 2, selected_step); if (hi != null) { // OK, we want to split the hop in 2 if (!hi.getFromStep().equals(selected_step) && !hi.getToStep().equals(selected_step)) { split_hop = true; last_hop_split = hi; hi.split = true; } } else { if (last_hop_split != null) { last_hop_split.split = false; last_hop_split = null; split_hop = false; } } selected_notes = transMeta.getSelectedNotes(); selected_steps = transMeta.getSelectedSteps(); // Adjust location of selected steps... if (selected_steps != null) { for (int i = 0; i < selected_steps.length; i++) { StepMeta stepMeta = selected_steps[i]; PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy); } } // Adjust location of selected hops... if (selected_notes != null) { for (int i = 0; i < selected_notes.length; i++) { NotePadMeta ni = selected_notes[i]; PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy); } } redraw(); } // The middle button perhaps? else if (last_button == 2 || (last_button == 1 && shift)) { StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null && !selected_step.equals(stepMeta)) { if (candidate == null) { candidate = new TransHopMeta(selected_step, stepMeta); redraw(); } } else { if (candidate != null) { candidate = null; redraw(); } } } } // Move around notes & steps else if (selected_note != null) { if (last_button == 1 && !shift) { /* * One or more notes are selected and moved around... * * new : new position of the note (not the mouse pointer) dx : difference with previous * position */ int dx = note.x - selected_note.getLocation().x; int dy = note.y - selected_note.getLocation().y; selected_notes = transMeta.getSelectedNotes(); selected_steps = transMeta.getSelectedSteps(); // Adjust location of selected steps... if (selected_steps != null) for (int i = 0; i < selected_steps.length; i++) { StepMeta stepMeta = selected_steps[i]; PropsUI.setLocation(stepMeta, stepMeta.getLocation().x + dx, stepMeta.getLocation().y + dy); } // Adjust location of selected hops... if (selected_notes != null) for (int i = 0; i < selected_notes.length; i++) { NotePadMeta ni = selected_notes[i]; PropsUI.setLocation(ni, ni.getLocation().x + dx, ni.getLocation().y + dy); } redraw(); } } } }); // Drag & Drop for steps Transfer[] ttypes = new Transfer[] { XMLTransfer.getInstance() }; DropTarget ddTarget = new DropTarget(canvas, DND.DROP_MOVE); ddTarget.setTransfer(ttypes); ddTarget.addDropListener(new DropTargetListener() { public void dragEnter(DropTargetEvent event) { clearSettings(); drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y)); redraw(); } public void dragLeave(DropTargetEvent event) { drop_candidate = null; redraw(); } public void dragOperationChanged(DropTargetEvent event) { } public void dragOver(DropTargetEvent event) { drop_candidate = PropsUI.calculateGridPosition(getRealPosition(canvas, event.x, event.y)); redraw(); } public void drop(DropTargetEvent event) { // no data to copy, indicate failure in event.detail if (event.data == null) { event.detail = DND.DROP_NONE; return; } // System.out.println("Dropping a step!!"); // What's the real drop position? Point p = getRealPosition(canvas, event.x, event.y); // We expect a Drag and Drop container... (encased in XML) try { DragAndDropContainer container = (DragAndDropContainer)event.data; StepMeta stepMeta = null; boolean newstep = false; switch(container.getType()) { // Put an existing one on the canvas. case DragAndDropContainer.TYPE_STEP: { // Drop hidden step onto canvas.... stepMeta = transMeta.findStep(container.getData()); if (stepMeta!=null) { if (stepMeta.isDrawn() || transMeta.isStepUsedInTransHops(stepMeta)) { MessageBox mb = new MessageBox(shell, SWT.OK); mb.setMessage(Messages.getString("TransGraph.Dialog.StepIsAlreadyOnCanvas.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.StepIsAlreadyOnCanvas.Title")); //$NON-NLS-1$ mb.open(); return; } // This step gets the drawn attribute and position set below. } else { // Unknown step dropped: ignore this to be safe! return; } } break; // Create a new step case DragAndDropContainer.TYPE_BASE_STEP_TYPE: { // Not an existing step: data refers to the type of step to create String steptype = container.getData(); stepMeta = spoon.newStep(transMeta, steptype, steptype, false, true); if (stepMeta!=null) { newstep=true; } else { return; // Cancelled pressed in dialog or unable to create step. } } break; // Create a new TableInput step using the selected connection... case DragAndDropContainer.TYPE_DATABASE_CONNECTION: { newstep = true; String connectionName = container.getData(); TableInputMeta tii = new TableInputMeta(); tii.setDatabaseMeta(transMeta.findDatabase(connectionName)); StepLoader steploader = StepLoader.getInstance(); String stepID = steploader.getStepPluginID(tii); StepPlugin stepPlugin = steploader.findStepPluginWithID(stepID); String stepName = transMeta.getAlternativeStepname(stepPlugin.getDescription()); stepMeta = new StepMeta(stepID, stepName, tii); if (spoon.editStep(transMeta, stepMeta) != null) { transMeta.addStep(stepMeta); spoon.refreshTree(); spoon.refreshGraph(); } else { return; } } break; // Drag hop on the canvas: create a new Hop... case DragAndDropContainer.TYPE_TRANS_HOP: { newHop(); return; } default: { // Nothing we can use: give an error! MessageBox mb = new MessageBox(shell, SWT.OK); mb.setMessage(Messages.getString("TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.ItemCanNotBePlacedOnCanvas.Title")); //$NON-NLS-1$ mb.open(); return; } } transMeta.unselectAll(); StepMeta before = (StepMeta) stepMeta.clone(); stepMeta.drawStep(); stepMeta.setSelected(true); PropsUI.setLocation(stepMeta, p.x, p.y); if (newstep) { spoon.addUndoNew(transMeta, new StepMeta[] { stepMeta }, new int[] { transMeta.indexOfStep(stepMeta) }); } else { spoon.addUndoChange(transMeta, new StepMeta[] { before }, new StepMeta[] { (StepMeta) stepMeta.clone() }, new int[] { transMeta.indexOfStep(stepMeta) }); } canvas.forceFocus(); redraw(); // See if we want to draw a tool tip explaining how to create new hops... if (newstep && transMeta.nrSteps() > 1 && transMeta.nrSteps()<5 && spoon.props.isShowingHelpToolTips() ) { showHelpTip(p.x, p.y, Messages.getString("TransGraph.HelpToolTip.CreatingHops.Title"), Messages.getString("TransGraph.HelpToolTip.CreatingHops.Message")); } } catch(Exception e) { new ErrorDialog(shell, Messages.getString("TransGraph.Dialog.ErrorDroppingObject.Message"), Messages.getString("TransGraph.Dialog.ErrorDroppingObject.Title"), e); } } public void dropAccept(DropTargetEvent event) { } } ); // Keyboard shortcuts... addKeyListener(canvas); addKeyListener(this); // addKeyListener(filenameLabel); canvas.addKeyListener(spoon.defKeys); // filenameLabel.addKeyListener(spoon.defKeys); setBackground(GUIResource.getInstance().getColorBackground()); } private void addToolBar() { try { toolbar = XulHelper.createToolbar(XUL_FILE_TRANS_TOOLBAR, TransGraph.this, TransGraph.this, new XulMessages()); ToolBar toolBar = (ToolBar) toolbar.getNativeObject(); toolBar.pack(); int h = toolBar.getBounds().height; // Hack alert : more XUL limitations... ToolItem sep = new ToolItem(toolBar, SWT.SEPARATOR); Composite zoom = new Composite(toolBar, SWT.LEFT); zoom.setLayout(new FormLayout()); final Scale zoomScale = new Scale(zoom, SWT.HORIZONTAL); zoomScale.setMinimum(0); zoomScale.setMaximum(TransPainter.magnifications.length-1); zoomScale.setIncrement(1); zoomScale.setPageIncrement(1); zoomScale.setSelection(magnificationIndex); zoomScale.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent arg0) { magnificationIndex=zoomScale.getSelection(); magnification=TransPainter.magnifications[magnificationIndex]; redraw(); } }); zoomScale.addKeyListener(spoon.defKeys); zoomScale.setSize(150, h); FormData fdScale = new FormData(); fdScale.left=new FormAttachment(0,0); fdScale.right=new FormAttachment(50,0); fdScale.top = new FormAttachment(0,0); fdScale.bottom = new FormAttachment(100,0); zoomScale.setLayoutData(fdScale); zoomLabel = new Label(zoom, SWT.LEFT); setZoomLabel(); zoomLabel.pack(); FormData fdLabel = new FormData(); fdLabel.left=new FormAttachment(50,0); fdLabel.right=new FormAttachment(100,0); fdLabel.top = new FormAttachment(zoomScale,0,SWT.CENTER); zoomLabel.setLayoutData(fdLabel); zoom.setSize(100, h); zoom.layout(); sep.setWidth(100); sep.setControl(zoom); toolBar.pack(); // Add a few default key listeners toolBar.addKeyListener(spoon.defKeys); addToolBarListeners(); toolBar.layout(true, true); } catch (Throwable t ) { log.logError(toString(), Const.getStackTracker(t)); new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"), Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_TOOLBAR), new Exception(t)); } } private void setZoomLabel() { zoomLabel.setText(TransPainter.magnificationDescriptions[magnificationIndex]); } public void addToolBarListeners() { try { // first get the XML document URL url = XulHelper.getAndValidate(XUL_FILE_TRANS_TOOLBAR_PROPERTIES); Properties props = new Properties(); props.load(url.openStream()); String ids[] = toolbar.getMenuItemIds(); for (int i = 0; i < ids.length; i++) { String methodName = (String) props.get(ids[i]); if (methodName != null) { toolbar.addMenuListener(ids[i], this, methodName); } } } catch (Throwable t ) { t.printStackTrace(); new ErrorDialog(shell, Messages.getString("Spoon.Exception.ErrorReadingXULFile.Title"), Messages.getString("Spoon.Exception.ErrorReadingXULFile.Message", XUL_FILE_TRANS_TOOLBAR_PROPERTIES), new Exception(t)); } } protected void hideToolTips() { toolTip.hide(); helpTip.hide(); } private void showHelpTip(int x, int y, String tipTitle, String tipMessage) { helpTip.setTitle(tipTitle); helpTip.setMessage(tipMessage); helpTip.setCheckBoxMessage(Messages.getString("TransGraph.HelpToolTip.DoNotShowAnyMoreCheckBox.Message")); // helpTip.hide(); // int iconSize = spoon.props.getIconSize(); org.eclipse.swt.graphics.Point location = new org.eclipse.swt.graphics.Point(x-5, y-5); helpTip.show(location); } /** * Select all the steps in a certain (screen) rectangle * * @param rect The selection area as a rectangle */ public void selectInRect(TransMeta transMeta, Rectangle rect) { if ( rect.height < 0 || rect.width < 0 ) { Rectangle rectified = new Rectangle(rect.x, rect.y, rect.width, rect.height); // Only for people not dragging from left top to right bottom if ( rectified.height < 0 ) { rectified.y = rectified.y + rectified.height; rectified.height = -rectified.height; } if ( rectified.width < 0 ) { rectified.x = rectified.x + rectified.width; rectified.width = -rectified.width; } rect = rectified; } for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta stepMeta = transMeta.getStep(i); Point a = stepMeta.getLocation(); if (rect.contains(a.x, a.y)) stepMeta.setSelected(true); } for (int i = 0; i < transMeta.nrNotes(); i++) { NotePadMeta ni = transMeta.getNote(i); Point a = ni.getLocation(); Point b = new Point(a.x + ni.width, a.y + ni.height); if (rect.contains(a.x, a.y) && rect.contains(b.x, b.y)) ni.setSelected(true); } } private void addKeyListener(Control control) { KeyAdapter keyAdapter = new KeyAdapter() { public void keyPressed(KeyEvent e) { // F2 --> rename step if (e.keyCode == SWT.F2) { renameStep(); } if (e.character == 1) // CTRL-A { transMeta.selectAll(); redraw(); } if (e.keyCode == SWT.ESC) { transMeta.unselectAll(); clearSettings(); redraw(); } if (e.keyCode == SWT.DEL) { StepMeta stepMeta[] = transMeta.getSelectedSteps(); if (stepMeta != null && stepMeta.length > 0) { delSelected(null); } } // CTRL-UP : allignTop(); if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.CONTROL) != 0) { alligntop(); } // CTRL-DOWN : allignBottom(); if (e.keyCode == SWT.ARROW_DOWN && (e.stateMask & SWT.CONTROL) != 0) { allignbottom(); } // CTRL-LEFT : allignleft(); if (e.keyCode == SWT.ARROW_LEFT && (e.stateMask & SWT.CONTROL) != 0) { allignleft(); } // CTRL-RIGHT : allignRight(); if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.CONTROL) != 0) { allignright(); } // ALT-RIGHT : distributeHorizontal(); if (e.keyCode == SWT.ARROW_RIGHT && (e.stateMask & SWT.ALT) != 0) { distributehorizontal(); } // ALT-UP : distributeVertical(); if (e.keyCode == SWT.ARROW_UP && (e.stateMask & SWT.ALT) != 0) { distributevertical(); } // ALT-HOME : snap to grid if (e.keyCode == SWT.HOME && (e.stateMask & SWT.ALT) != 0) { snaptogrid(ConstUI.GRID_SIZE); } // SPACE : over a step: show output fields... if (e.character == ' ' && lastMove != null) { Point real = screen2real(lastMove.x, lastMove.y); // Hide the tooltip! hideToolTips(); // Set the pop-up menu StepMeta stepMeta = transMeta.getStep(real.x, real.y, iconsize); if (stepMeta != null) { // OK, we found a step, show the output fields... inputOutputFields(stepMeta, false); } } } }; control.addKeyListener(keyAdapter); } public void redraw() { canvas.redraw(); setZoomLabel(); } public boolean forceFocus() { return canvas.forceFocus(); } public boolean setFocus() { return canvas.setFocus(); } public void renameStep() { StepMeta[] selection = transMeta.getSelectedSteps(); if (selection!=null && selection.length==1) { final StepMeta stepMeta = selection[0]; // What is the location of the step? String name = stepMeta.getName(); Point stepLocation = stepMeta.getLocation(); Point realStepLocation = real2screen(stepLocation.x, stepLocation.y); // The location of the step name? GC gc = new GC(shell.getDisplay()); gc.setFont(GUIResource.getInstance().getFontGraph()); Point namePosition = TransPainter.getNamePosition(gc, name, realStepLocation, iconsize); int width = gc.textExtent(name).x + 30; gc.dispose(); // at this very point, create a new text widget... final Text text = new Text(this, SWT.SINGLE | SWT.BORDER); text.setText(name); FormData fdText = new FormData(); fdText.left = new FormAttachment(0, namePosition.x); fdText.right= new FormAttachment(0, namePosition.x+width); fdText.top = new FormAttachment(0, namePosition.y); text.setLayoutData(fdText); // Add a listener! // Catch the keys pressed when editing a Text-field... KeyListener lsKeyText = new KeyAdapter() { public void keyPressed(KeyEvent e) { // "ENTER": close the text editor and copy the data over if ( e.character == SWT.CR ) { String newName = text.getText(); text.dispose(); renameStep(stepMeta, newName); } if (e.keyCode == SWT.ESC) { text.dispose(); } } }; text.addKeyListener(lsKeyText); text.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent e) { String newName = text.getText(); text.dispose(); renameStep(stepMeta, newName); } } ); this.layout(true, true); text.setFocus(); text.setSelection(0, name.length()); } } public void renameStep(StepMeta stepMeta, String stepname) { String newname = stepname; StepMeta smeta = transMeta.findStep(newname, stepMeta); int nr = 2; while (smeta != null) { newname = stepname + " " + nr; smeta = transMeta.findStep(newname); nr++; } if (nr > 2) { stepname = newname; MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("Spoon.Dialog.StepnameExists.Message", stepname)); // $NON-NLS-1$ mb.setText(Messages.getString("Spoon.Dialog.StepnameExists.Title")); // $NON-NLS-1$ mb.open(); } stepMeta.setName(stepname); stepMeta.setChanged(); spoon.refreshTree(); // to reflect the new name spoon.refreshGraph(); } public void clearSettings() { selected_step = null; selected_note = null; selected_steps = null; selrect = null; candidate = null; last_hop_split = null; last_button = 0; iconoffset = null; for (int i = 0; i < transMeta.nrTransHops(); i++) transMeta.getTransHop(i).split = false; } public String[] getDropStrings(String str, String sep) { StringTokenizer strtok = new StringTokenizer(str, sep); String retval[] = new String[strtok.countTokens()]; int i = 0; while (strtok.hasMoreElements()) { retval[i] = strtok.nextToken(); i++; } return retval; } public Point screen2real(int x, int y) { offset = getOffset(); Point real; if (offset != null) { real = new Point(Math.round((x - offset.x)/magnification), Math.round((y - offset.y)/magnification)); } else { real = new Point(x, y); } return real; } public Point real2screen(int x, int y) { offset = getOffset(); Point screen = new Point(x + offset.x, y + offset.y); return screen; } public Point getRealPosition(Composite canvas, int x, int y) { Point p = new Point(0, 0); Composite follow = canvas; while (follow != null) { org.eclipse.swt.graphics.Point loc = follow.getLocation(); Point xy = new Point(loc.x, loc.y); p.x += xy.x; p.y += xy.y; follow = follow.getParent(); } int offsetX = -16; int offsetY = -64; if (Const.isOSX()) { offsetX=-2; offsetY=-24; } p.x = x - p.x + offsetX; p.y = y - p.y + offsetY; return screen2real(p.x, p.y); } /** * See if location (x,y) is on a line between two steps: the hop! * @param x * @param y * @return the transformation hop on the specified location, otherwise: null */ private TransHopMeta findHop(int x, int y) { return findHop(x, y, null); } /** * See if location (x,y) is on a line between two steps: the hop! * @param x * @param y * @param exclude the step to exclude from the hops (from or to location). Specify null if no step is to be excluded. * @return the transformation hop on the specified location, otherwise: null */ private TransHopMeta findHop(int x, int y, StepMeta exclude) { int i; TransHopMeta online = null; for (i = 0; i < transMeta.nrTransHops(); i++) { TransHopMeta hi = transMeta.getTransHop(i); StepMeta fs = hi.getFromStep(); StepMeta ts = hi.getToStep(); if (fs == null || ts == null) return null; // If either the "from" or "to" step is excluded, skip this hop. if (exclude!=null && ( exclude.equals(fs) || exclude.equals(ts))) continue; int line[] = getLine(fs, ts); if (pointOnLine(x, y, line)) online = hi; } return online; } private int[] getLine(StepMeta fs, StepMeta ts) { Point from = fs.getLocation(); Point to = ts.getLocation(); offset = getOffset(); int x1 = from.x + iconsize / 2; int y1 = from.y + iconsize / 2; int x2 = to.x + iconsize / 2; int y2 = to.y + iconsize / 2; return new int[] { x1, y1, x2, y2 }; } public void hideStep() { for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta sti = transMeta.getStep(i); if (sti.isDrawn() && sti.isSelected()) { sti.hideStep(); spoon.refreshTree(); } } getCurrentStep().hideStep(); spoon.refreshTree(); redraw(); } public void checkSelectedSteps() { spoon.checkTrans(transMeta, true); } public void detachStep() { detach(getCurrentStep()); selected_steps = null; } public void generateMappingToThisStep() { spoon.generateMapping(transMeta, getCurrentStep()); } public void partitioning() { spoon.editPartitioning(transMeta, getCurrentStep()); } public void clustering() { spoon.editClustering(transMeta, getCurrentStep()); } public void errorHandling() { spoon.editStepErrorHandling(transMeta, getCurrentStep()); } public void newHopChoice() { selected_steps = null; newHop(); } public void editStep() { selected_steps = null; editStep(getCurrentStep()); } public void editDescription() { editDescription(getCurrentStep()); } public void setDistributes() { getCurrentStep().setDistributes(true); spoon.refreshGraph(); spoon.refreshTree(); } public void setCopies() { getCurrentStep().setDistributes(false); spoon.refreshGraph(); spoon.refreshTree(); } public void copies() { final boolean multipleOK = checkNumberOfCopies(transMeta, getCurrentStep()); selected_steps = null; String tt = Messages.getString("TransGraph.Dialog.NrOfCopiesOfStep.Title"); //$NON-NLS-1$ String mt = Messages.getString("TransGraph.Dialog.NrOfCopiesOfStep.Message"); //$NON-NLS-1$ EnterNumberDialog nd = new EnterNumberDialog(shell, getCurrentStep().getCopies(), tt, mt); int cop = nd.open(); if (cop >= 0) { if (cop == 0) cop = 1; if (!multipleOK) { cop = 1; MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING); mb.setMessage(Messages.getString("TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.MultipleCopiesAreNotAllowedHere.Title")); //$NON-NLS-1$ mb.open(); } if (getCurrentStep().getCopies() != cop) { getCurrentStep().setCopies(cop); spoon.refreshGraph(); } } } public void dupeStep() { try { if (transMeta.nrSelectedSteps() <= 1) { spoon.dupeStep(transMeta, getCurrentStep()); } else { for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected()) { spoon.dupeStep(transMeta, stepMeta); } } } } catch(Exception ex) { new ErrorDialog(shell, Messages.getString("TransGraph.Dialog.ErrorDuplicatingStep.Title"), Messages.getString("TransGraph.Dialog.ErrorDuplicatingStep.Message"), ex); //$NON-NLS-1$ //$NON-NLS-2$ } } public void copyStep() { spoon.copySelected(transMeta, transMeta.getSelectedSteps(), transMeta.getSelectedNotes()); } public void delSelected() { delSelected(getCurrentStep()); } public void fieldsBefore() { selected_steps = null; inputOutputFields(getCurrentStep(), true); } public void fieldsAfter() { selected_steps = null; inputOutputFields(getCurrentStep(), false); } public void editHop() { selrect = null; editHop(getCurrentHop()); } public void flipHopDirection() { selrect = null; TransHopMeta hi = getCurrentHop(); hi.flip(); if (transMeta.hasLoop(hi.getFromStep())) { spoon.refreshGraph(); MessageBox mb = new MessageBox(shell, SWT.YES | SWT.ICON_WARNING); mb.setMessage(Messages.getString("TransGraph.Dialog.LoopsAreNotAllowed.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.LoopsAreNotAllowed.Title")); //$NON-NLS-1$ mb.open(); hi.flip(); spoon.refreshGraph(); } else { hi.setChanged(); spoon.refreshGraph(); spoon.refreshTree(); spoon.setShellText(); } } public void enableHop() { selrect = null; TransHopMeta hi = getCurrentHop(); TransHopMeta before = (TransHopMeta) hi.clone(); hi.setEnabled(!hi.isEnabled()); if (transMeta.hasLoop(hi.getToStep())) { hi.setEnabled(!hi.isEnabled()); MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); mb.setMessage(Messages.getString("TransGraph.Dialog.LoopAfterHopEnabled.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.LoopAfterHopEnabled.Title")); //$NON-NLS-1$ mb.open(); } else { TransHopMeta after = (TransHopMeta) hi.clone(); spoon.addUndoChange(transMeta, new TransHopMeta[] { before }, new TransHopMeta[] { after }, new int[] { transMeta.indexOfTransHop(hi) }); spoon.refreshGraph(); spoon.refreshTree(); } } public void deleteHop() { selrect = null; TransHopMeta hi = getCurrentHop(); int idx = transMeta.indexOfTransHop(hi); spoon.addUndoDelete(transMeta, new TransHopMeta[] { (TransHopMeta) hi.clone() }, new int[] { idx }); transMeta.removeTransHop(idx); spoon.refreshTree(); spoon.refreshGraph(); } public void editNote() { selrect=null; editNote( getCurrentNote() ); } public void deleteNote() { selrect = null; int idx = transMeta.indexOfNote(ni); if (idx >= 0) { transMeta.removeNote(idx); spoon.addUndoDelete(transMeta, new NotePadMeta[] { (NotePadMeta) ni.clone() }, new int[] { idx }); redraw(); } } public void raiseNote() { selrect=null; int idx = transMeta.indexOfNote(getCurrentNote()); if (idx>=0) { transMeta.raiseNote(idx); //TBD: spoon.addUndoRaise(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} ); } redraw(); } public void lowerNote() { selrect=null; int idx = transMeta.indexOfNote(getCurrentNote()); if (idx>=0) { transMeta.lowerNote(idx); //TBD: spoon.addUndoLower(transMeta, new NotePadMeta[] {getCurrentNote()}, new int[] {idx} ); } redraw(); } public void newNote() { selrect = null; String title = Messages.getString("TransGraph.Dialog.NoteEditor.Title"); //$NON-NLS-1$ String message = Messages.getString("TransGraph.Dialog.NoteEditor.Message"); //$NON-NLS-1$ EnterTextDialog dd = new EnterTextDialog(shell, title, message, ""); //$NON-NLS-1$ String n = dd.open(); if (n != null) { NotePadMeta npi = new NotePadMeta(n, lastclick.x, lastclick.y, ConstUI.NOTE_MIN_SIZE, ConstUI.NOTE_MIN_SIZE); transMeta.addNote(npi); spoon.addUndoNew(transMeta, new NotePadMeta[] { npi }, new int[] { transMeta.indexOfNote(npi) }); redraw(); } } public void paste() { final String clipcontent = spoon.fromClipboard(); Point loc = new Point(currentMouseX, currentMouseY); spoon.pasteXML(transMeta, clipcontent, loc); } public void settings() { editProperties( transMeta, spoon, spoon.getRepository(), true); } public void newStep( String description ) { StepMeta stepMeta = spoon.newStep(transMeta, description, description, false, true); PropsUI.setLocation(stepMeta, currentMouseX, currentMouseY); stepMeta.setDraw(true); redraw(); } /** * This sets the popup-menu on the background of the canvas based on the xy coordinate of the mouse. This method is * called after a mouse-click. * * @param x X-coordinate on screen * @param y Y-coordinate on screen */ private void setMenu(int x, int y) { try { currentMouseX = x; currentMouseY = y; final StepMeta stepMeta = transMeta.getStep(x, y, iconsize); if (stepMeta != null) // We clicked on a Step! { setCurrentStep( stepMeta ); XulPopupMenu menu = (XulPopupMenu) menuMap.get( "trans-graph-entry" ); //$NON-NLS-1$ if( menu != null ) { int sels = transMeta.nrSelectedSteps(); XulMenuChoice item = menu.getMenuItemById( "trans-graph-entry-newhop" ); //$NON-NLS-1$ menu.addMenuListener( "trans-graph-entry-newhop", this, TransGraph.class, "newHop" ); //$NON-NLS-1$ //$NON-NLS-2$ item.setEnabled( sels == 2 ); item = menu.getMenuItemById( "trans-graph-entry-align-snap" ); //$NON-NLS-1$ item.setText(Messages.getString("TransGraph.PopupMenu.SnapToGrid") + ConstUI.GRID_SIZE + ")\tALT-HOME"); XulMenu aMenu = menu.getMenuById( "trans-graph-entry-align" ); //$NON-NLS-1$ if( aMenu != null ) { aMenu.setEnabled( sels > 1 ); } menu.addMenuListener( "trans-graph-entry-align-left", this, "allignleft" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-right", this, "allignright" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-top", this, "alligntop" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-bottom", this, "allignbottom" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-horz", this, "distributehorizontal" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-vert", this, "distributevertical" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-align-snap", this, "snaptogrid" ); //$NON-NLS-1$ //$NON-NLS-2$ item = menu.getMenuItemById( "trans-graph-entry-data-movement-distribute" ); //$NON-NLS-1$ item.setChecked( stepMeta.isDistributes() ); item = menu.getMenuItemById( "trans-graph-entry-data-movement-copy" ); //$NON-NLS-1$ item.setChecked( !stepMeta.isDistributes() ); item = menu.getMenuItemById( "trans-graph-entry-hide" ); //$NON-NLS-1$ item.setEnabled( stepMeta.isDrawn() && !transMeta.isStepUsedInTransHops(stepMeta) ); item = menu.getMenuItemById( "trans-graph-entry-detach" ); //$NON-NLS-1$ item.setEnabled( transMeta.isStepUsedInTransHops(stepMeta) ); item = menu.getMenuItemById( "trans-graph-entry-errors" ); //$NON-NLS-1$ item.setEnabled( stepMeta.supportsErrorHandling() ); menu.addMenuListener( "trans-graph-entry-newhop", this, "newHopChoice" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-edit", this, "editStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-edit-description", this, "editDescription" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-data-movement-distribute", this, "setDistributes" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-data-movement-copy", this, "setCopies" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-copies", this, "copies" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-copy", this, "copyStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-duplicate", this, "dupeStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-delete", this, "delSelected" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-hide", this, "hideStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-detach", this, "detachStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-inputs", this, "fieldsBefore" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-outputs", this, "fieldsAfter" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-verify", this, "checkSelectedSteps" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-mapping", this, "generateMappingToThisStep" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-partitioning", this, "partitioning" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-clustering", this, "clustering" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-entry-errors", this, "errorHandling" ); //$NON-NLS-1$ //$NON-NLS-2$ displayMenu(menu, canvas); } } else { final TransHopMeta hi = findHop(x, y); if (hi != null) // We clicked on a HOP! { XulPopupMenu menu = (XulPopupMenu) menuMap.get( "trans-graph-hop" ); //$NON-NLS-1$ if( menu != null ) { setCurrentHop( hi ); XulMenuChoice item = menu.getMenuItemById( "trans-graph-hop-enabled" ); //$NON-NLS-1$ if( item != null ) { if (hi.isEnabled()) { item.setText(Messages.getString("TransGraph.PopupMenu.DisableHop")); //$NON-NLS-1$ } else { item.setText(Messages.getString("TransGraph.PopupMenu.EnableHop")); //$NON-NLS-1$ } } menu.addMenuListener( "trans-graph-hop-edit", this, "editHop" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-hop-flip", this, "flipHopDirection" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-hop-enabled", this, "enableHop" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-hop-delete", this, "deleteHop" ); //$NON-NLS-1$ //$NON-NLS-2$ displayMenu(menu, canvas); } } else { // Clicked on the background: maybe we hit a note? final NotePadMeta ni = transMeta.getNote(x, y); setCurrentNote( ni ); if (ni!=null) { XulPopupMenu menu = (XulPopupMenu) menuMap.get( "trans-graph-note" ); //$NON-NLS-1$ if( menu != null ) { menu.addMenuListener( "trans-graph-note-edit", this, "editNote" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-note-delete", this, "deleteNote" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-note-raise", this, "raiseNote" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-note-lower", this, "lowerNote" ); //$NON-NLS-1$ //$NON-NLS-2$ displayMenu(menu, canvas); } } else { XulPopupMenu menu = (XulPopupMenu) menuMap.get( "trans-graph-background" ); //$NON-NLS-1$ if( menu != null ) { menu.addMenuListener( "trans-graph-background-new-note", this, "newNote" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-background-paste", this, "paste" ); //$NON-NLS-1$ //$NON-NLS-2$ menu.addMenuListener( "trans-graph-background-settings", this, "settings" ); //$NON-NLS-1$ //$NON-NLS-2$ final String clipcontent = spoon.fromClipboard(); XulMenuChoice item = menu.getMenuItemById( "trans-graph-background-paste" ); //$NON-NLS-1$ if( item != null ) { item.setEnabled( clipcontent != null ); } String locale = LanguageChoice.getInstance().getDefaultLocale().toString().toLowerCase(); XulMenu subMenu = menu.getMenuById( "trans-graph-background-new-step" ); if( subMenu.getItemCount() == 0 ) { // group these by type so the menu doesn't stretch the height of the screen and to be friendly to testing tools StepLoader steploader = StepLoader.getInstance(); // get a list of the categories String basecat[] = steploader.getCategories(StepPlugin.TYPE_ALL, locale ); // get all the plugins StepPlugin basesteps[] = steploader.getStepsWithType(StepPlugin.TYPE_ALL); XulMessages xulMessages = new XulMessages(); for( int cat=0; cat<basecat.length; cat++ ) { // create a submenu for this category org.pentaho.xul.swt.menu.Menu catMenu = new org.pentaho.xul.swt.menu.Menu( (org.pentaho.xul.swt.menu.Menu) subMenu, basecat[cat], basecat[cat], null); for( int step=0; step<basesteps.length; step++ ) { // find the steps for this category if( basesteps[step].getCategory(locale).equalsIgnoreCase(basecat[cat])) { // create a menu option for this step final String name = basesteps[step].getDescription(); new MenuChoice( catMenu, name, name, null, null, MenuChoice.TYPE_PLAIN, xulMessages); menu.addMenuListener( name, this, "newStep" ); //$NON-NLS-1$ //$NON-NLS-2$ } } } } displayMenu(menu, canvas); } } } } } catch(Throwable t) { // TODO: fix this: log somehow, is IGNORED for now. t.printStackTrace(); } } private void displayMenu(XulPopupMenu menu, Control control) { Menu nativeMenu = (Menu)menu.getNativeObject(); Menu oldMenu = control.getMenu(); if (oldMenu!=null && oldMenu!=nativeMenu) { oldMenu.setVisible(false); } control.setMenu(nativeMenu); nativeMenu.setVisible(true); } private boolean checkNumberOfCopies(TransMeta transMeta, StepMeta stepMeta) { boolean enabled = true; StepMeta[] prevSteps = transMeta.getPrevSteps(stepMeta); for (int i=0;i<prevSteps.length && enabled;i++) { // See what the target steps are. // If one of the target steps is our original step, we can't start multiple copies String[] targetSteps = prevSteps[i].getStepMetaInterface().getTargetSteps(); if (targetSteps!=null) { for (int t=0;t<targetSteps.length && enabled;t++) { if (targetSteps[t].equalsIgnoreCase(stepMeta.getName())) enabled=false; } } } return enabled; } private void setToolTip(int x, int y) { if (!spoon.getProperties().showToolTips()) return; canvas.setToolTipText("'"); // Some stupid bug in GTK+ causes a phantom tool tip to pop up, even if the tip is null canvas.setToolTipText(null); String newTip = null; Image tipImage = null; final StepMeta stepMeta = transMeta.getStep(x, y, iconsize); if (stepMeta != null) // We clicked on a Step! { // Also: set the tooltip! if (stepMeta.getDescription() != null) { String desc = stepMeta.getDescription(); int le = desc.length() >= 200 ? 200 : desc.length(); newTip = desc.substring(0, le); } else { newTip=stepMeta.getName(); } // Add the steps description StepPlugin stepPlugin = StepLoader.getInstance().getStepPlugin(stepMeta.getStepMetaInterface()); if (stepPlugin!=null) { newTip+=Const.CR+Const.CR+stepPlugin.getTooltip(LanguageChoice.getInstance().getDefaultLocale().toString()); tipImage = GUIResource.getInstance().getImagesSteps().get(stepPlugin.getID()[0]); } else { System.out.println("WTF!!"); } // Add the partitioning info if (stepMeta.isPartitioned()) { newTip+=Const.CR+Const.CR+Messages.getString("TransGraph.Step.Tooltip.CurrentPartitioning")+stepMeta.getStepPartitioningMeta().toString(); } // Add the partitioning info if (stepMeta.getTargetStepPartitioningMeta()!=null) { newTip+=Const.CR+Const.CR+Messages.getString("TransGraph.Step.Tooltip.NextPartitioning")+stepMeta.getTargetStepPartitioningMeta().toString(); } } else { final TransHopMeta hi = findHop(x, y); if (hi != null) // We clicked on a HOP! { // Set the tooltip for the hop: newTip = hi.toString(); tipImage = GUIResource.getInstance().getImageHop(); } else { // check the area owner list... StringBuffer tip = new StringBuffer(); for (AreaOwner areaOwner : areaOwners) { if (areaOwner.contains(x, y)) { if ( areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_REMOTE_INPUT_STEPS) ) { StepMeta step = (StepMeta) areaOwner.getParent(); tip.append("Remote input steps:").append(Const.CR).append(" for (RemoteStep remoteStep : step.getRemoteInputSteps()) { tip.append(remoteStep.toString()).append(Const.CR); } } if ( areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_REMOTE_OUTPUT_STEPS) ) { StepMeta step = (StepMeta) areaOwner.getParent(); tip.append("Remote output steps:").append(Const.CR).append(" for (RemoteStep remoteStep : step.getRemoteOutputSteps()) { tip.append(remoteStep.toString()).append(Const.CR); } } if ( areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_PARTITIONING_CURRENT_STEP) ) { StepMeta step = (StepMeta) areaOwner.getParent(); tip.append("Step partitioning:").append(Const.CR).append(" tip.append(step.getStepPartitioningMeta().toString()).append(Const.CR); if (step.getTargetStepPartitioningMeta()!=null) { tip.append(Const.CR).append(Const.CR).append("TARGET: "+step.getTargetStepPartitioningMeta().toString()).append(Const.CR); } } if ( areaOwner.getParent() instanceof StepMeta && areaOwner.getOwner().equals(TransPainter.STRING_PARTITIONING_CURRENT_NEXT) ) { StepMeta step = (StepMeta) areaOwner.getParent(); tip.append("Target partitioning:").append(Const.CR).append(" tip.append(step.getStepPartitioningMeta().toString()).append(Const.CR); } } } if (tip.length()==0) { newTip = null; } else { newTip = tip.toString(); } } } if (newTip==null) { toolTip.hide(); } else if (!newTip.equalsIgnoreCase(getToolTipText())) { if (tipImage!=null) { toolTip.setImage(tipImage); } else { toolTip.setImage(GUIResource.getInstance().getImageSpoon()); } toolTip.setText(newTip); toolTip.hide(); toolTip.show(new org.eclipse.swt.graphics.Point(x,y)); } } public void delSelected(StepMeta stMeta) { if (transMeta.nrSelectedSteps() == 0) { spoon.delStep(transMeta, stMeta); return; } // Get the list of steps that would be deleted List<String> stepList = new ArrayList<String>(); for (int i = transMeta.nrSteps() - 1; i >= 0; i { StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) { stepList.add(stepMeta.getName()); } } // Create and display the delete confirmation dialog MessageBox mb = new DeleteMessageBox(shell, Messages.getString("TransGraph.Dialog.Warning.DeleteSteps.Message"), //$NON-NLS-1$ stepList); int result = mb.open(); if (result == SWT.YES) { // Delete the steps for (int i = transMeta.nrSteps() - 1; i >= 0; i { StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected() || (stMeta != null && stMeta.equals(stepMeta))) { spoon.delStep(transMeta, stepMeta); } } } } public void editDescription(StepMeta stepMeta) { String title = Messages.getString("TransGraph.Dialog.StepDescription.Title"); //$NON-NLS-1$ String message = Messages.getString("TransGraph.Dialog.StepDescription.Message"); //$NON-NLS-1$ EnterTextDialog dd = new EnterTextDialog(shell, title, message, stepMeta.getDescription()); String d = dd.open(); if (d != null) stepMeta.setDescription(d); } /** * Display the input- or outputfields for a step. * * @param stepMeta The step (it's metadata) to query * @param before set to true if you want to have the fields going INTO the step, false if you want to see all the * fields that exit the step. */ private void inputOutputFields(StepMeta stepMeta, boolean before) { spoon.refreshGraph(); SearchFieldsProgressDialog op = new SearchFieldsProgressDialog(transMeta, stepMeta, before); try { final ProgressMonitorDialog pmd = new ProgressMonitorDialog(shell); // Run something in the background to cancel active database queries, forecably if needed! Runnable run = new Runnable() { public void run() { IProgressMonitor monitor = pmd.getProgressMonitor(); while (pmd.getShell()==null || ( !pmd.getShell().isDisposed() && !monitor.isCanceled() )) { try { Thread.sleep(250); } catch(InterruptedException e) { }; } if (monitor.isCanceled()) // Disconnect and see what happens! { try { transMeta.cancelQueries(); } catch(Exception e) {}; } } }; // Dump the cancel looker in the background! new Thread(run).start(); pmd.run(true, true, op); } catch (InvocationTargetException e) { new ErrorDialog(shell, Messages.getString("TransGraph.Dialog.GettingFields.Title"), Messages.getString("TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { new ErrorDialog(shell, Messages.getString("TransGraph.Dialog.GettingFields.Title"), Messages.getString("TransGraph.Dialog.GettingFields.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface fields = op.getFields(); if (fields != null && fields.size() > 0) { StepFieldsDialog sfd = new StepFieldsDialog(shell, transMeta, SWT.NONE, stepMeta.getName(), fields); String sn = (String) sfd.open(); if (sn != null) { StepMeta esi = transMeta.findStep(sn); if (esi != null) { editStep(esi); } } } else { MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_INFORMATION); mb.setMessage(Messages.getString("TransGraph.Dialog.CouldntFindFields.Message")); //$NON-NLS-1$ mb.setText(Messages.getString("TransGraph.Dialog.CouldntFindFields.Title")); //$NON-NLS-1$ mb.open(); } } public void paintControl(PaintEvent e) { Point area = getArea(); if (area.x == 0 || area.y == 0) return; // nothing to do! Display disp = shell.getDisplay(); Image img = getTransformationImage(disp, area.x, area.y, true, magnification); e.gc.drawImage(img, 0, 0); img.dispose(); // spoon.setShellText(); } public Image getTransformationImage(Device device, int x, int y, boolean branded, float magnificationFactor) { TransPainter transPainter = new TransPainter(transMeta, new Point(x, y), hori, vert, candidate, drop_candidate, selrect, areaOwners); transPainter.setMagnification(magnificationFactor); Image img = transPainter.getTransformationImage(device, PropsUI.getInstance().isBrandingActive()); return img; } private Point getArea() { org.eclipse.swt.graphics.Rectangle rect = canvas.getClientArea(); Point area = new Point(rect.width, rect.height); return area; } private Point magnifyPoint(Point p) { return new Point(Math.round(p.x * magnification), Math.round(p.y*magnification)); } private Point getThumb(Point area, Point transMax) { Point resizedMax = magnifyPoint(transMax); Point thumb = new Point(0, 0); if (resizedMax.x <= area.x) thumb.x = 100; else thumb.x = 100 * area.x / resizedMax.x; if (resizedMax.y <= area.y) thumb.y = 100; else thumb.y = 100 * area.y / resizedMax.y; return thumb; } private Point getOffset() { Point area = getArea(); Point max = transMeta.getMaximum(); Point thumb = getThumb(area, max); return getOffset(thumb, area); } private Point getOffset(Point thumb, Point area) { Point p = new Point(0, 0); Point sel = new Point(hori.getSelection(), vert.getSelection()); if (thumb.x == 0 || thumb.y == 0) return p; p.x = -sel.x * area.x / thumb.x; p.y = -sel.y * area.y / thumb.y; return p; } public int sign(int n) { return n < 0 ? -1 : (n > 0 ? 1 : 1); } private void editStep(StepMeta stepMeta) { spoon.editStep(transMeta, stepMeta); } private void editNote(NotePadMeta ni) { NotePadMeta before = (NotePadMeta) ni.clone(); String title = Messages.getString("TransGraph.Dialog.EditNote.Title"); //$NON-NLS-1$ String message = Messages.getString("TransGraph.Dialog.EditNote.Message"); //$NON-NLS-1$ EnterTextDialog dd = new EnterTextDialog(shell, title, message, ni.getNote()); String n = dd.open(); if (n != null) { ni.setChanged(); ni.setNote(n); ni.width = ConstUI.NOTE_MIN_SIZE; ni.height = ConstUI.NOTE_MIN_SIZE; NotePadMeta after = (NotePadMeta) ni.clone(); spoon.addUndoChange(transMeta, new NotePadMeta[] { before }, new NotePadMeta[] { after }, new int[] { transMeta.indexOfNote(ni) }); spoon.refreshGraph(); } } private void editHop(TransHopMeta transHopMeta) { String name = transHopMeta.toString(); log.logDebug(toString(), Messages.getString("TransGraph.Logging.EditingHop") + name); //$NON-NLS-1$ spoon.editHop(transMeta, transHopMeta); } private void newHop() { StepMeta fr = transMeta.getSelectedStep(0); StepMeta to = transMeta.getSelectedStep(1); spoon.newHop(transMeta, fr, to); } private boolean pointOnLine(int x, int y, int line[]) { int dx, dy; int pm = HOP_SEL_MARGIN / 2; boolean retval = false; for (dx = -pm; dx <= pm && !retval; dx++) { for (dy = -pm; dy <= pm && !retval; dy++) { retval = pointOnThinLine(x + dx, y + dy, line); } } return retval; } private boolean pointOnThinLine(int x, int y, int line[]) { int x1 = line[0]; int y1 = line[1]; int x2 = line[2]; int y2 = line[3]; // Not in the square formed by these 2 points: ignore! if (!(((x >= x1 && x <= x2) || (x >= x2 && x <= x1)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1)))) return false; double angle_line = Math.atan2(y2 - y1, x2 - x1) + Math.PI; double angle_point = Math.atan2(y - y1, x - x1) + Math.PI; // Same angle, or close enough? if (angle_point >= angle_line - 0.01 && angle_point <= angle_line + 0.01) return true; return false; } private SnapAllignDistribute createSnapAllignDistribute() { List<GUIPositionInterface> elements = transMeta.getSelectedDrawnStepsList(); int[] indices = transMeta.getStepIndexes(elements.toArray(new StepMeta[elements.size()])); return new SnapAllignDistribute(transMeta, elements, indices, spoon, this); } public void snaptogrid() { snaptogrid( ConstUI.GRID_SIZE ); } private void snaptogrid(int size) { createSnapAllignDistribute().snaptogrid(size); } public void allignleft() { createSnapAllignDistribute().allignleft(); } public void allignright() { createSnapAllignDistribute().allignright(); } public void alligntop() { createSnapAllignDistribute().alligntop(); } public void allignbottom() { createSnapAllignDistribute().allignbottom(); } public void distributehorizontal() { createSnapAllignDistribute().distributehorizontal(); } public void distributevertical() { createSnapAllignDistribute().distributevertical(); } public void zoomIn() { if (magnificationIndex+1<TransPainter.magnifications.length) { magnification = TransPainter.magnifications[++magnificationIndex]; } redraw(); } public void zoomOut() { if (magnificationIndex>0) { magnification = TransPainter.magnifications[--magnificationIndex]; } redraw(); } public void zoom100Percent() { magnificationIndex=4; magnification = TransPainter.magnifications[magnificationIndex]; redraw(); } private void detach(StepMeta stepMeta) { TransHopMeta hfrom = transMeta.findTransHopTo(stepMeta); TransHopMeta hto = transMeta.findTransHopFrom(stepMeta); if (hfrom != null && hto != null) { if (transMeta.findTransHop(hfrom.getFromStep(), hto.getToStep()) == null) { TransHopMeta hnew = new TransHopMeta(hfrom.getFromStep(), hto.getToStep()); transMeta.addTransHop(hnew); spoon.addUndoNew(transMeta, new TransHopMeta[] { hnew }, new int[] { transMeta.indexOfTransHop(hnew) }); spoon.refreshTree(); } } if (hfrom != null) { int fromidx = transMeta.indexOfTransHop(hfrom); if (fromidx >= 0) { transMeta.removeTransHop(fromidx); spoon.refreshTree(); } } if (hto != null) { int toidx = transMeta.indexOfTransHop(hto); if (toidx >= 0) { transMeta.removeTransHop(toidx); spoon.refreshTree(); } } spoon.refreshTree(); redraw(); } // Preview the selected steps... public void preview() { // Create a new transformation TransMeta preview = new TransMeta(); // Copy the selected steps into it... for (int i = 0; i < transMeta.nrSteps(); i++) { StepMeta stepMeta = transMeta.getStep(i); if (stepMeta.isSelected()) { preview.addStep(stepMeta); } } // Copy the relevant TransHops into it... for (int i = 0; i < transMeta.nrTransHops(); i++) { TransHopMeta hi = transMeta.getTransHop(i); if (hi.isEnabled()) { StepMeta fr = hi.getFromStep(); StepMeta to = hi.getToStep(); if (fr.isSelected() && to.isSelected()) { preview.addTransHop(hi); } } } } public void newProps() { GUIResource.getInstance().reload(); iconsize = spoon.props.getIconSize(); } public String toString() { return this.getClass().getName(); } public EngineMetaInterface getMeta() { return transMeta; } /** * @param transMeta the transMeta to set */ public void setTransMeta(TransMeta transMeta) { this.transMeta = transMeta; } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[]) { addUndoPosition(obj, pos, prev, curr, false); } // Change of step, connection, hop or note... public void addUndoPosition(Object obj[], int pos[], Point prev[], Point curr[], boolean nextAlso) { // It's better to store the indexes of the objects, not the objects itself! transMeta.addUndo(obj, null, pos, prev, curr, TransMeta.TYPE_UNDO_POSITION, nextAlso); spoon.setUndoMenu(transMeta); } /* * Shows a 'model has changed' warning if required * @return true if nothing has changed or the changes are rejected by the user. */ public int showChangedWarning() { MessageBox mb = new MessageBox(shell, SWT.YES | SWT.NO | SWT.CANCEL | SWT.ICON_WARNING ); mb.setMessage(Messages.getString("Spoon.Dialog.PromptSave.Message", spoon.makeTransGraphTabName(transMeta)));//"This model has changed. Do you want to save it?" mb.setText(Messages.getString("Spoon.Dialog.PromptSave.Title")); return mb.open(); } public boolean applyChanges() { return spoon.saveToFile(transMeta); } public boolean canBeClosed() { return !transMeta.hasChanged(); } public TransMeta getManagedObject() { return transMeta; } public boolean hasContentChanged() { return transMeta.hasChanged(); } public List<CheckResultInterface> getRemarks() { return remarks; } public void setRemarks(List<CheckResultInterface> remarks) { this.remarks = remarks; } public List<DatabaseImpact> getImpact() { return impact; } public void setImpact(List<DatabaseImpact> impact) { this.impact = impact; } public boolean isImpactFinished() { return impactFinished; } public void setImpactFinished(boolean impactHasRun) { this.impactFinished = impactHasRun; } /** * @return the lastMove */ public Point getLastMove() { return lastMove; } public static boolean editProperties(TransMeta transMeta, Spoon spoon, Repository rep, boolean allowDirectoryChange) { if (transMeta==null) return false; TransDialog tid = new TransDialog(spoon.getShell(), SWT.NONE, transMeta, rep); tid.setDirectoryChangeAllowed(allowDirectoryChange); TransMeta ti = tid.open(); // In this case, load shared objects if (tid.isSharedObjectsFileChanged()) { try { SharedObjects sharedObjects = transMeta.readSharedObjects(rep); spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch(Exception e) { new ErrorDialog(spoon.getShell(), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.makeTransGraphTabName(transMeta)), e); } } if (tid.isSharedObjectsFileChanged() || ti!=null) { try { SharedObjects sharedObjects = transMeta.readSharedObjects(rep); spoon.sharedObjectsFileMap.put(sharedObjects.getFilename(), sharedObjects); } catch(KettleException e) { new ErrorDialog(spoon.getShell(), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Title"), Messages.getString("Spoon.Dialog.ErrorReadingSharedObjects.Message", spoon.makeTransGraphTabName(transMeta)), e); } spoon.refreshTree(); spoon.delegates.tabs.renameTabs(); // cheap operation, might as will do it anyway } spoon.setShellText(); return ti!=null; } public void newFileDropDown() { spoon.newFileDropDown(toolbar); } public void openFile() { spoon.openFile(); } public void saveFile() { spoon.saveFile(); } public void saveFileAs() { spoon.saveFileAs(); } public void saveXMLFileToVfs() { spoon.saveXMLFileToVfs(); } public void printFile() { spoon.printFile(); } public void runTransformation() { spoon.runFile(); } public void pauseTransformation() { pauseResume(); } public void stopTransformation() { stop(); } public void previewFile() { spoon.previewFile(); } public void debugFile() { spoon.debugFile(); } public void transReplay() { spoon.replayTransformation(); } public void checkTrans() { spoon.checkTrans(); } public void analyseImpact() { spoon.analyseImpact(); } public void getSQL() { spoon.getSQL(); } public void exploreDatabase() { spoon.exploreDatabase(); } public void showExecutionResults() { if (extraViewComposite==null || extraViewComposite.isDisposed()) { addAllTabs(); } else { disposeExtraView(); } } /** * If the extra tab view at the bottom is empty, we close it. */ public void checkEmptyExtraView() { if (extraViewTabFolder.getItemCount()==0) { disposeExtraView(); } } private void disposeExtraView() { extraViewComposite.dispose(); sashForm.layout(); sashForm.setWeights( new int[] { 100, }); } private void minMaxExtraView() { // What is the state? boolean maximized = sashForm.getMaximizedControl() != null; if (maximized) { // Minimize sashForm.setMaximizedControl(null); minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel()); minMaxButton.setToolTipText(Messages.getString("TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); } else { // Maximize sashForm.setMaximizedControl(extraViewComposite); minMaxButton.setImage(GUIResource.getInstance().getImageMinimizePanel()); minMaxButton.setToolTipText(Messages.getString("TransGraph.ExecutionResultsPanel.MinButton.Tooltip")); } } /** * @return the toolbar */ public XulToolbar getToolbar() { return toolbar; } /** * @param toolbar the toolbar to set */ public void setToolbar(XulToolbar toolbar) { this.toolbar = toolbar; } private Label closeButton; private Label minMaxButton; /** * Add an extra view to the main composite SashForm */ public void addExtraView() { extraViewComposite = new Composite(sashForm, SWT.NONE); FormLayout extraCompositeFormLayout = new FormLayout(); extraCompositeFormLayout.marginWidth=2; extraCompositeFormLayout.marginHeight=2; extraViewComposite.setLayout(extraCompositeFormLayout); // Put a close and max button to the upper right corner... closeButton = new Label(extraViewComposite, SWT.NONE); closeButton.setImage(GUIResource.getInstance().getImageClosePanel()); closeButton.setToolTipText(Messages.getString("TransGraph.ExecutionResultsPanel.CloseButton.Tooltip")); FormData fdClose = new FormData(); fdClose.right = new FormAttachment(100,0); fdClose.top = new FormAttachment(0,0); closeButton.setLayoutData(fdClose); closeButton.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { disposeExtraView(); }}); minMaxButton = new Label(extraViewComposite, SWT.NONE); minMaxButton.setImage(GUIResource.getInstance().getImageMaximizePanel()); minMaxButton.setToolTipText(Messages.getString("TransGraph.ExecutionResultsPanel.MaxButton.Tooltip")); FormData fdMinMax = new FormData(); fdMinMax.right = new FormAttachment(closeButton, -Const.MARGIN); fdMinMax.top = new FormAttachment(0,0); minMaxButton.setLayoutData(fdMinMax); minMaxButton.addMouseListener(new MouseAdapter() { public void mouseDown(MouseEvent e) { minMaxExtraView(); }}); // Add a label at the top: Results Label wResultsLabel = new Label(extraViewComposite, SWT.LEFT); wResultsLabel.setFont(GUIResource.getInstance().getFontMediumBold()); wResultsLabel.setBackground(GUIResource.getInstance().getColorLightGray()); wResultsLabel.setText(Messages.getString("TransLog.ResultsPanel.NameLabel")); FormData fdResultsLabel = new FormData(); fdResultsLabel.left = new FormAttachment(0,0); fdResultsLabel.right = new FormAttachment(minMaxButton,-Const.MARGIN); fdResultsLabel.top = new FormAttachment(0,0); wResultsLabel.setLayoutData(fdResultsLabel); // Add a tab folder ... extraViewTabFolder= new CTabFolder(extraViewComposite, SWT.MULTI); spoon.props.setLook(extraViewTabFolder, Props.WIDGET_STYLE_TAB); extraViewTabFolder.addMouseListener(new MouseAdapter() { @Override public void mouseDoubleClick(MouseEvent arg0) { if (sashForm.getMaximizedControl()==null) { sashForm.setMaximizedControl(extraViewComposite); } else { sashForm.setMaximizedControl(null); } } }); FormData fdTabFolder = new FormData(); fdTabFolder.left = new FormAttachment(0,0); fdTabFolder.right = new FormAttachment(100,0); fdTabFolder.top = new FormAttachment(wResultsLabel,Const.MARGIN); fdTabFolder.bottom = new FormAttachment(100,0); extraViewTabFolder.setLayoutData(fdTabFolder); sashForm.setWeights(new int[] { 60, 40, }); } public void checkErrors() { if (trans != null) { if (!trans.isFinished()) { if (trans.getErrors() != 0) { trans.killAll(); } } } } public synchronized void start(TransExecutionConfiguration executionConfiguration) { if (!running) // Not running, start the transformation... { // Auto save feature... if (transMeta.hasChanged()) { if (spoon.props.getAutoSave()) { spoon.saveToFile(transMeta); } else { MessageDialogWithToggle md = new MessageDialogWithToggle(shell, Messages.getString("TransLog.Dialog.FileHasChanged.Title"), //$NON-NLS-1$ null, Messages.getString("TransLog.Dialog.FileHasChanged1.Message") + Const.CR + Messages.getString("TransLog.Dialog.FileHasChanged2.Message") + Const.CR, //$NON-NLS-1$ //$NON-NLS-2$ MessageDialog.QUESTION, new String[] { Messages.getString("System.Button.Yes"), Messages.getString("System.Button.No") }, //$NON-NLS-1$ //$NON-NLS-2$ 0, Messages.getString("TransLog.Dialog.Option.AutoSaveTransformation"), //$NON-NLS-1$ spoon.props.getAutoSave()); int answer = md.open(); if ( (answer & 0xFF) == 0) { spoon.saveToFile(transMeta); } spoon.props.setAutoSave(md.getToggleState()); } } if (((transMeta.getName() != null && spoon.rep != null) || // Repository available & name set (transMeta.getFilename() != null && spoon.rep == null) // No repository & filename set ) && !transMeta.hasChanged() // Didn't change ) { if (trans == null || (trans != null && trans.isFinished())) { try { // Set the requested logging level. log.setLogLevel(executionConfiguration.getLogLevel()); transMeta.injectVariables(executionConfiguration.getVariables()); trans = new Trans(transMeta, spoon.rep, transMeta.getName(), transMeta.getDirectory().getPath(), transMeta.getFilename()); trans.setReplayDate(executionConfiguration.getReplayDate()); trans.setRepository(executionConfiguration.getRepository()); trans.setMonitored(true); log.logBasic(toString(), Messages.getString("TransLog.Log.TransformationOpened")); //$NON-NLS-1$ } catch (KettleException e) { trans = null; new ErrorDialog(shell, Messages.getString("TransLog.Dialog.ErrorOpeningTransformation.Title"), Messages.getString("TransLog.Dialog.ErrorOpeningTransformation.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } if (trans != null) { Map<String,String> arguments = executionConfiguration.getArguments(); final String args[]; if (arguments != null) args = convertArguments(arguments); else args = null; log.logMinimal(Spoon.APP_NAME, Messages.getString("TransLog.Log.LaunchingTransformation") + trans.getTransMeta().getName() + "]..."); //$NON-NLS-1$ //$NON-NLS-2$ trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled()); // Launch the step preparation in a different thread. // That way Spoon doesn't block anymore and that way we can follow the progress of the initialization final Thread parentThread = Thread.currentThread(); shell.getDisplay().asyncExec( new Runnable() { public void run() { addAllTabs(); prepareTrans(parentThread, args); } } ); log.logMinimal(Spoon.APP_NAME, Messages.getString("TransLog.Log.StartedExecutionOfTransformation")); //$NON-NLS-1$ setControlStates(); } } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(Messages.getString("TransLog.Dialog.DoNoStartTransformationTwice.Title")); //$NON-NLS-1$ m.setMessage(Messages.getString("TransLog.Dialog.DoNoStartTransformationTwice.Message")); //$NON-NLS-1$ m.open(); } } else { if (transMeta.hasChanged()) { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(Messages.getString("TransLog.Dialog.SaveTransformationBeforeRunning.Title")); //$NON-NLS-1$ m.setMessage(Messages.getString("TransLog.Dialog.SaveTransformationBeforeRunning.Message")); //$NON-NLS-1$ m.open(); } else if (spoon.rep != null && transMeta.getName() == null) { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(Messages.getString("TransLog.Dialog.GiveTransformationANameBeforeRunning.Title")); //$NON-NLS-1$ m.setMessage(Messages.getString("TransLog.Dialog.GiveTransformationANameBeforeRunning.Message")); //$NON-NLS-1$ m.open(); } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(Messages.getString("TransLog.Dialog.SaveTransformationBeforeRunning2.Title")); //$NON-NLS-1$ m.setMessage(Messages.getString("TransLog.Dialog.SaveTransformationBeforeRunning2.Message")); //$NON-NLS-1$ m.open(); } } } } public void addAllTabs() { transHistoryDelegate.addTransHistory(); transLogDelegate.addTransLog(); transGridDelegate.addTransGrid(); transPerfDelegate.addTransPerf(); extraViewTabFolder.setSelection(transGridDelegate.getTransGridTab()); // TODO: remember last selected? } public synchronized void debug(TransExecutionConfiguration executionConfiguration, TransDebugMeta transDebugMeta) { if (!running) { try { this.lastTransDebugMeta = transDebugMeta; log.setLogLevel(executionConfiguration.getLogLevel()); log.logDetailed(toString(), Messages.getString("TransLog.Log.DoPreview")); //$NON-NLS-1$ String[] args=null; Map<String,String> arguments = executionConfiguration.getArguments(); if (arguments != null) { args = convertArguments(arguments); } transMeta.injectVariables(executionConfiguration.getVariables()); // Create a new transformation to execution trans = new Trans(transMeta); trans.setSafeModeEnabled(executionConfiguration.isSafeModeEnabled()); trans.prepareExecution(args); // Add the row listeners to the allocated threads transDebugMeta.addRowListenersToTransformation(trans); // What method should we call back when a break-point is hit? transDebugMeta.addBreakPointListers(new BreakPointListener() { public void breakPointHit(TransDebugMeta transDebugMeta, StepDebugMeta stepDebugMeta, RowMetaInterface rowBufferMeta, List<Object[]> rowBuffer) { showPreview(transDebugMeta, stepDebugMeta, rowBufferMeta, rowBuffer); } } ); // Start the threads for the steps... startThreads(); debug=true; // Show the execution results view... shell.getDisplay().asyncExec( new Runnable() { public void run() { addAllTabs(); } } ); } catch (Exception e) { new ErrorDialog(shell, Messages.getString("TransLog.Dialog.UnexpectedErrorDuringPreview.Title"), Messages.getString("TransLog.Dialog.UnexpectedErrorDuringPreview.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } } else { MessageBox m = new MessageBox(shell, SWT.OK | SWT.ICON_WARNING); m.setText(Messages.getString("TransLog.Dialog.DoNoPreviewWhileRunning.Title")); //$NON-NLS-1$ m.setMessage(Messages.getString("TransLog.Dialog.DoNoPreviewWhileRunning.Message")); //$NON-NLS-1$ m.open(); } } public synchronized void showPreview(final TransDebugMeta transDebugMeta, final StepDebugMeta stepDebugMeta, final RowMetaInterface rowBufferMeta, final List<Object[]> rowBuffer) { shell.getDisplay().asyncExec(new Runnable() { public void run() { if (isDisposed()) return; spoon.enableMenus(); // The transformation is now paused, indicate this in the log dialog... pausing=true; setControlStates(); PreviewRowsDialog previewRowsDialog = new PreviewRowsDialog(shell, transMeta, SWT.APPLICATION_MODAL, stepDebugMeta.getStepMeta().getName(), rowBufferMeta, rowBuffer); previewRowsDialog.setProposingToGetMoreRows(true); previewRowsDialog.setProposingToStop(true); previewRowsDialog.open(); if (previewRowsDialog.isAskingForMoreRows()) { // clear the row buffer. // That way if you click resume, you get the next N rows for the step :-) rowBuffer.clear(); // Resume running: find more rows... pauseResume(); } if (previewRowsDialog.isAskingToStop()) { // Stop running stop(); } } }); } private String[] convertArguments(Map<String, String> arguments) { String[] argumentNames = arguments.keySet().toArray(new String[arguments.size()]); Arrays.sort(argumentNames); String args[] = new String[argumentNames.length]; for (int i = 0; i < args.length; i++) { String argumentName = argumentNames[i]; args[i] = arguments.get(argumentName); } return args; } public void stop() { if (running && !halting) { halting = true; trans.stopAll(); try { trans.endProcessing("stop"); //$NON-NLS-1$ log.logMinimal(Spoon.APP_NAME, Messages.getString("TransLog.Log.ProcessingOfTransformationStopped")); //$NON-NLS-1$ } catch (KettleException e) { new ErrorDialog(shell, Messages.getString("TransLog.Dialog.ErrorWritingLogRecord.Title"), Messages.getString("TransLog.Dialog.ErrorWritingLogRecord.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } running = false; initialized = false; halted = false; halting = false; setControlStates(); transMeta.setInternalKettleVariables(); // set the original vars back as they may be changed by a mapping } } public synchronized void pauseResume() { if (running) { // Get the pause toolbar item if (!pausing) { pausing = true; trans.pauseRunning(); setControlStates(); } else { pausing = false; trans.resumeRunning(); setControlStates(); } } } private void setControlStates() { getDisplay().asyncExec(new Runnable() { public void run() { // Start/Run button... XulToolbarButton runButton = toolbar.getButtonById("trans-run"); if (runButton!=null) { runButton.setEnable(!running); } // Pause button... XulToolbarButton pauseButton = toolbar.getButtonById("trans-pause"); if (pauseButton!=null) { pauseButton.setEnable(running); pauseButton.setText( pausing ? RESUME_TEXT : PAUSE_TEXT ); pauseButton.setHint( pausing ? Messages.getString("Spoon.Tooltip.ResumeTranformation") : Messages.getString("Spoon.Tooltip.PauseTranformation")); } // Stop button... XulToolbarButton stopButton = toolbar.getButtonById("trans-stop"); if (stopButton!=null) { stopButton.setEnable(running); } // Debug button... XulToolbarButton debugButton = toolbar.getButtonById("trans-debug"); if (debugButton!=null) { debugButton.setEnable(!running); } // Preview button... XulToolbarButton previewButton = toolbar.getButtonById("trans-preview"); if (previewButton!=null) { previewButton.setEnable(!running); } // TODO: enable/disable Transformation menu entries too } }); } private synchronized void prepareTrans(final Thread parentThread, final String[] args) { Runnable runnable = new Runnable() { public void run() { try { trans.prepareExecution(args); initialized = true; } catch (KettleException e) { initialized = false; } halted = trans.hasHaltedSteps(); checkStartThreads();// After init, launch the threads. } }; Thread thread = new Thread(runnable); thread.start(); } private void checkStartThreads() { if (initialized && !running && trans!=null) { startThreads(); } } private synchronized void startThreads() { running=true; try { // Add a listener to the transformation. // If the transformation is done, we want to do the end processing, etc. trans.addTransListener(new TransListener() { public void transFinished(Trans trans) { checkTransEnded(); // checkErrors(); } } ); trans.startThreads(); setControlStates(); } catch(KettleException e) { log.logError(toString(), "Error starting step threads", e); } // See if we have to fire off the performance graph updater etc. getDisplay().asyncExec(new Runnable() { public void run() { if (transPerfDelegate.getTransPerfTab()!=null ) { // If there is a tab open, try to the correct content on there now transPerfDelegate.setupContent(); transPerfDelegate.layoutPerfComposite(); } } }); } private void checkTransEnded() { if (trans != null) { if (trans.isFinished() && ( running || halted )) { log.logMinimal(Spoon.APP_NAME, Messages.getString("TransLog.Log.TransformationHasFinished")); //$NON-NLS-1$ running = false; initialized=false; halted = false; halting = false; try { trans.endProcessing("end"); //$NON-NLS-1$ if (spoonHistoryRefresher!=null) spoonHistoryRefresher.markRefreshNeeded(); } catch (KettleException e) { new ErrorDialog(shell, Messages.getString("TransLog.Dialog.ErrorWritingLogRecord.Title"), Messages.getString("TransLog.Dialog.ErrorWritingLogRecord.Message"), e); //$NON-NLS-1$ //$NON-NLS-2$ } setControlStates(); // OK, also see if we had a debugging session going on. // If so and we didn't hit a breakpoint yet, display the show preview dialog... if (debug && lastTransDebugMeta!=null && lastTransDebugMeta.getTotalNumberOfHits()==0) { debug=false; showLastPreviewResults(); } debug=false; } } } public synchronized void showLastPreviewResults() { if (lastTransDebugMeta==null || lastTransDebugMeta.getStepDebugMetaMap().isEmpty()) return; final List<String> stepnames = new ArrayList<String>(); final List<RowMetaInterface> rowMetas = new ArrayList<RowMetaInterface>(); final List<List<Object[]>> rowBuffers = new ArrayList<List<Object[]>>(); // Assemble the buffers etc in the old style... for (StepMeta stepMeta : lastTransDebugMeta.getStepDebugMetaMap().keySet() ) { StepDebugMeta stepDebugMeta = lastTransDebugMeta.getStepDebugMetaMap().get(stepMeta); stepnames.add(stepMeta.getName()); rowMetas.add(stepDebugMeta.getRowBufferMeta()); rowBuffers.add(stepDebugMeta.getRowBuffer()); } getDisplay().asyncExec(new Runnable() { public void run() { EnterPreviewRowsDialog dialog = new EnterPreviewRowsDialog(shell, SWT.NONE, stepnames, rowMetas, rowBuffers); dialog.open(); } }); } /** * @return the running */ public boolean isRunning() { return running; } /** * @param running the running to set */ public void setRunning(boolean running) { this.running = running; } /** * @return the lastTransDebugMeta */ public TransDebugMeta getLastTransDebugMeta() { return lastTransDebugMeta; } /** * @return the halting */ public boolean isHalting() { return halting; } /** * @param halting the halting to set */ public void setHalting(boolean halting) { this.halting = halting; } }
package org.ojalgo.random; import static org.ojalgo.function.PrimitiveFunction.*; import java.util.Arrays; import org.ojalgo.ProgrammingError; import org.ojalgo.access.Access1D; import org.ojalgo.array.PrimitiveArray; import org.ojalgo.constant.PrimitiveMath; public final class SampleSet implements Access1D<Double> { public static SampleSet make(final RandomNumber randomNumber, final int size) { final PrimitiveArray retVal = PrimitiveArray.make(size); final double[] tmpData = retVal.data; for (int i = 0; i < size; i++) { tmpData[i] = randomNumber.doubleValue(); } return new SampleSet(retVal); } public static SampleSet wrap(final Access1D<?> someSamples) { return new SampleSet(someSamples); } private transient double myMean = Double.NaN; private transient double myMedian = Double.NaN; private transient double myQuartile1 = Double.NaN; private transient double myQuartile3 = Double.NaN; private Access1D<?> mySamples; private transient double[] mySortedCopy = null; private transient double myVariance = Double.NaN; @SuppressWarnings("unused") private SampleSet() { this(null); ProgrammingError.throwForIllegalInvocation(); } SampleSet(final Access1D<?> samples) { super(); mySamples = samples; this.reset(); } public long count() { return mySamples.count(); } public double doubleValue(final long index) { return mySamples.doubleValue(index); } public Double get(final long index) { return mySamples.doubleValue(index); } public double getCorrelation(final SampleSet anotherSampleSet) { double retVal = PrimitiveMath.ZERO; final double tmpCovar = this.getCovariance(anotherSampleSet); if (tmpCovar != PrimitiveMath.ZERO) { final double tmpThisStdDev = this.getStandardDeviation(); final double tmpThatStdDev = anotherSampleSet.getStandardDeviation(); retVal = tmpCovar / (tmpThisStdDev * tmpThatStdDev); } return retVal; } public double getCovariance(final SampleSet anotherSampleSet) { double retVal = PrimitiveMath.ZERO; final double tmpThisMean = this.getMean(); final double tmpThatMean = anotherSampleSet.getMean(); final long tmpLimit = Math.min(mySamples.count(), anotherSampleSet.count()); final Access1D<?> tmpValues = anotherSampleSet.getSamples(); for (long i = 0L; i < tmpLimit; i++) { retVal += (mySamples.doubleValue(i) - tmpThisMean) * (tmpValues.doubleValue(i) - tmpThatMean); } retVal /= (tmpLimit - 1L); return retVal; } public double getFirst() { return mySamples.doubleValue(0); } public double getInterquartileRange() { return this.getQuartile3() - this.getQuartile1(); } /** * max(abs(value)) */ public double getLargest() { double retVal = PrimitiveMath.ZERO; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { retVal = MAX.invoke(retVal, ABS.invoke(mySamples.doubleValue(i))); } return retVal; } public double getLast() { return mySamples.doubleValue(mySamples.count() - 1L); } /** * max(value) */ public double getMaximum() { double retVal = PrimitiveMath.NEGATIVE_INFINITY; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { retVal = MAX.invoke(retVal, mySamples.doubleValue(i)); } return retVal; } public double getMean() { if (Double.isNaN(myMean)) { myMean = PrimitiveMath.ZERO; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { myMean += mySamples.doubleValue(i); } myMean /= mySamples.count(); } return myMean; } /** * Potentially expensive as it requires copying and sorting of the samples. */ public double getMedian() { if (Double.isNaN(myMedian)) { this.calculateQuartiles(); } return myMedian; } /** * min(value) */ public double getMinimum() { double retVal = PrimitiveMath.POSITIVE_INFINITY; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { retVal = MIN.invoke(retVal, mySamples.doubleValue(i)); } return retVal; } /** * Potentially expensive as it requires copying and sorting of the samples. */ public double getQuartile1() { if (Double.isNaN(myQuartile1)) { this.calculateQuartiles(); } return myQuartile1; } /** * Potentially expensive as it requires copying and sorting of the samples. */ public double getQuartile2() { return this.getMedian(); } /** * Potentially expensive as it requires copying and sorting of the samples. */ public double getQuartile3() { if (Double.isNaN(myQuartile3)) { this.calculateQuartiles(); } return myQuartile3; } /** * min(abs(value)) */ public double getSmallest() { double retVal = PrimitiveMath.POSITIVE_INFINITY; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { retVal = MIN.invoke(retVal, ABS.invoke(mySamples.doubleValue(i))); } return retVal; } public double getStandardDeviation() { return SQRT.invoke(this.getVariance()); } public double getStandardScore(final long index) { return (this.doubleValue(index) - this.getMean()) / this.getStandardDeviation(); } public double getSumOfSquares() { double retVal = PrimitiveMath.ZERO; final double tmpMean = this.getMean(); double tmpVal; final long tmpLimit = mySamples.count(); for (long i = 0L; i < tmpLimit; i++) { tmpVal = mySamples.doubleValue(i) - tmpMean; retVal += (tmpVal * tmpVal); } return retVal; } /** * @return A copy of the internal data (the samples). */ public double[] getValues() { return mySamples.toRawCopy1D(); } public double getVariance() { if (Double.isNaN(myVariance)) { myVariance = this.getCovariance(this); } return myVariance; } /** * If the underlying {@link Access1D} of samples is modified you must reset the sample set before using. */ public void reset() { myMean = Double.NaN; myVariance = Double.NaN; myQuartile1 = Double.NaN; myMedian = Double.NaN; myQuartile3 = Double.NaN; if (mySortedCopy != null) { Arrays.fill(mySortedCopy, Double.POSITIVE_INFINITY); } } public int size() { return (int) mySamples.count(); } /** * Replace the underlying samples and reset the sample set. */ public void swap(final Access1D<?> samples) { mySamples = samples; this.reset(); } @Override public String toString() { return "Sample set Size=" + this.count() + ", Mean=" + this.getMean() + ", Median=" + this.getMedian() + ", Var=" + this.getVariance() + ", StdDev=" + this.getStandardDeviation() + ", Min=" + this.getMinimum() + ", Max=" + this.getMaximum(); } private void calculateQuartiles() { final int tmpSize = (int) this.getSamples().count(); final double[] tmpSortedCopy = this.getSortedCopy(); final int n = tmpSize / 4; final int r = tmpSize % 4; switch (r) { case 1: myQuartile1 = (0.25 * tmpSortedCopy[n - 1]) + (0.75 * tmpSortedCopy[n]); myMedian = tmpSortedCopy[2 * n]; myQuartile3 = (0.75 * tmpSortedCopy[3 * n]) + (0.25 * tmpSortedCopy[(3 * n) + 1]); break; case 3: myQuartile1 = (0.75 * tmpSortedCopy[n]) + (0.25 * tmpSortedCopy[n + 1]); myMedian = tmpSortedCopy[(2 * n) + 1]; myQuartile3 = (0.25 * tmpSortedCopy[(3 * n) + 1]) + (0.75 * tmpSortedCopy[(3 * n) + 2]); break; default: myQuartile1 = tmpSortedCopy[n]; myMedian = (0.5 * tmpSortedCopy[2 * n]) + (0.5 * tmpSortedCopy[(2 * n) + 1]); myQuartile3 = tmpSortedCopy[(3 * n) + 1]; break; } } Access1D<?> getSamples() { return mySamples; } double[] getSortedCopy() { final Access1D<?> tmpSamples = this.getSamples(); final long tmpSamplesCount = tmpSamples.count(); if ((mySortedCopy == null) || (mySortedCopy.length < tmpSamplesCount)) { mySortedCopy = tmpSamples.toRawCopy1D(); Arrays.sort(mySortedCopy); } else if (mySortedCopy[0] == Double.POSITIVE_INFINITY) { for (int i = 0; i < tmpSamplesCount; i++) { mySortedCopy[i] = tmpSamples.doubleValue(i); } Arrays.sort(mySortedCopy); } return mySortedCopy; } }
package com.griddynamics.jagger.engine.e1.aggregator.workload; import com.griddynamics.jagger.coordinator.NodeId; import com.griddynamics.jagger.engine.e1.aggregator.session.model.TaskData; import com.griddynamics.jagger.engine.e1.aggregator.workload.model.TimeInvocationStatistics; import com.griddynamics.jagger.engine.e1.aggregator.workload.model.WorkloadProcessDescriptiveStatistics; import com.griddynamics.jagger.engine.e1.collector.DurationCollector; import com.griddynamics.jagger.engine.e1.scenario.WorkloadTask; import com.griddynamics.jagger.master.DistributionListener; import com.griddynamics.jagger.master.Master; import com.griddynamics.jagger.master.SessionIdProvider; import com.griddynamics.jagger.master.configuration.Task; import com.griddynamics.jagger.storage.fs.logging.*; import com.griddynamics.jagger.util.statistics.StatisticsCalculator; import org.hibernate.HibernateException; import org.hibernate.Session; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.orm.hibernate3.HibernateCallback; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class DurationLogProcessor extends LogProcessor implements DistributionListener { private static final Logger log = LoggerFactory.getLogger(Master.class); private LogAggregator logAggregator; private LogReader logReader; private SessionIdProvider sessionIdProvider; private int pointCount; @Required public void setLogReader(LogReader logReader) { this.logReader = logReader; } @Required public void setPointCount(int pointCount) { this.pointCount = pointCount; } @Required public void setSessionIdProvider(SessionIdProvider sessionIdProvider) { this.sessionIdProvider = sessionIdProvider; } @Required public void setLogAggregator(LogAggregator logAggregator) { this.logAggregator = logAggregator; } @Override public void onDistributionStarted(String sessionId, String taskId, Task task, Collection<NodeId> capableNodes) { // do nothing } @Override public void onTaskDistributionCompleted(String sessionId, String taskId, Task task) { if (task instanceof WorkloadTask) { processLog(sessionIdProvider.getSessionId(), taskId); } } private void processLog(String sessionId, String taskId) { try { String dir = sessionId + File.separatorChar + taskId + File.separatorChar + DurationCollector.DURATION_MARKER; String file = dir + File.separatorChar + "aggregated.dat"; AggregationInfo aggregationInfo = logAggregator.chronology(dir, file); if(aggregationInfo.getCount() == 0) { //no data collected return; } int intervalSize = (int) ((aggregationInfo.getMaxTime() - aggregationInfo.getMinTime()) / pointCount); if (intervalSize < 1) { intervalSize = 1; } TaskData taskData = getTaskData(taskId, sessionId); if (taskData == null) { log.error("TaskData not found by taskId: {}", taskId); return; } StatisticsGenerator statisticsGenerator = new StatisticsGenerator(file, aggregationInfo, intervalSize, taskData).generate(); final Collection<TimeInvocationStatistics> statistics = statisticsGenerator.getStatistics(); final WorkloadProcessDescriptiveStatistics workloadProcessDescriptiveStatistics = statisticsGenerator.getWorkloadProcessDescriptiveStatistics(); getHibernateTemplate().execute(new HibernateCallback<Void>() { @Override public Void doInHibernate(Session session) throws HibernateException, SQLException { for (TimeInvocationStatistics stat : statistics) { session.persist(stat); } session.persist(workloadProcessDescriptiveStatistics); session.flush(); return null; } }); } catch (Exception e) { log.error("Error during log processing", e); } } private class StatisticsGenerator { private String path; private AggregationInfo aggregationInfo; private int intervalSize; private TaskData taskData; private Collection<TimeInvocationStatistics> statistics; private WorkloadProcessDescriptiveStatistics workloadProcessDescriptiveStatistics; public StatisticsGenerator(String path, AggregationInfo aggregationInfo, int intervalSize, TaskData taskData) { this.path = path; this.aggregationInfo = aggregationInfo; this.intervalSize = intervalSize; this.taskData = taskData; } public Collection<TimeInvocationStatistics> getStatistics() { return statistics; } public WorkloadProcessDescriptiveStatistics getWorkloadProcessDescriptiveStatistics() { return workloadProcessDescriptiveStatistics; } public StatisticsGenerator generate() throws IOException { statistics = new ArrayList<TimeInvocationStatistics>(); long currentInterval = aggregationInfo.getMinTime() + intervalSize; long time = 0; int currentCount = 0; int extendedInterval = intervalSize; StatisticsCalculator windowStatisticsCalculator = new StatisticsCalculator(); StatisticsCalculator globalStatisticsCalculator = new StatisticsCalculator(); LogReader.FileReader<DurationLogEntry> fileReader = null; try { fileReader = logReader.read(path, DurationLogEntry.class); Iterator<DurationLogEntry> it = fileReader.iterator(); while (it.hasNext()) { DurationLogEntry logEntry = it.next(); log.debug("Log entry {} time", logEntry.getTime()); while (logEntry.getTime() > currentInterval) { log.debug("processing count {} interval {}", currentCount, intervalSize); if (currentCount > 0) { double throughput = (double) currentCount * 1000 / extendedInterval; statistics.add(assembleInvocationStatistics(time, windowStatisticsCalculator, throughput, taskData)); currentCount = 0; extendedInterval = 0; windowStatisticsCalculator.reset(); } time += intervalSize; extendedInterval += intervalSize; currentInterval += intervalSize; } currentCount++; windowStatisticsCalculator.addValue(logEntry.getDuration()); globalStatisticsCalculator.addValue(logEntry.getDuration()); } } finally { if (fileReader != null) { fileReader.close(); } } if (currentCount > 0) { double throughput = (double) currentCount * 1000 / intervalSize; statistics.add(assembleInvocationStatistics(time, windowStatisticsCalculator, throughput, taskData)); } workloadProcessDescriptiveStatistics = assembleDescriptiveScenarioStatistics(globalStatisticsCalculator, taskData); return this; } } }
package org.vitrivr.cineast.api; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.imageio.ImageIO; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.joml.Vector3f; import org.joml.Vector3i; import org.vitrivr.cineast.api.rest.RestfulAPI; import org.vitrivr.cineast.api.session.CredentialManager; import org.vitrivr.cineast.core.config.Config; import org.vitrivr.cineast.core.config.IngestConfig; import org.vitrivr.cineast.core.config.QueryConfig; import org.vitrivr.cineast.core.data.entities.MultimediaMetadataDescriptor; import org.vitrivr.cineast.core.data.m3d.Mesh; import org.vitrivr.cineast.core.data.score.SegmentScoreElement; import org.vitrivr.cineast.core.db.dao.reader.MultimediaMetadataReader; import org.vitrivr.cineast.core.evaluation.EvaluationConfig; import org.vitrivr.cineast.core.evaluation.EvaluationException; import org.vitrivr.cineast.core.evaluation.EvaluationRuntime; import org.vitrivr.cineast.core.features.codebook.CodebookGenerator; import org.vitrivr.cineast.core.features.listener.RetrievalResultCSVExporter; import org.vitrivr.cineast.core.features.retriever.RetrieverInitializer; import org.vitrivr.cineast.core.importer.DataImportHandler; import org.vitrivr.cineast.core.render.JOGLOffscreenRenderer; import org.vitrivr.cineast.core.run.ExtractionDispatcher; import org.vitrivr.cineast.core.setup.EntityCreator; import org.vitrivr.cineast.core.util.ContinuousRetrievalLogic; import org.vitrivr.cineast.core.util.ReflectionHelper; import com.google.common.collect.Ordering; /** * Entry point. * Has an executable main class which connects to the DB and opens a connection to the webserver * Ports and additional settings can be specified at cineast.properties */ public class API { private static final Logger LOGGER = LogManager.getLogger(); private static final RetrieverInitializer initializer = r -> r .init(Config.sharedConfig().getDatabase().getSelectorSupplier()); private static final Pattern inputSplitPattern = Pattern.compile("([^\"]\\S*|\".+?\")\\s*"); private static boolean running = true; /** * * @param args */ public static void main(String[] args) { CommandLine commandline = handleCommandLine(args); if (commandline != null) { if (commandline.hasOption("config")) { Config.loadConfig(commandline.getOptionValue("config")); } /* Handle --job; start handleExtraction. */ if (commandline.hasOption("job")) { handleExtraction(new File(commandline.getOptionValue("job"))); return; } /* Handle --3d; start handleExtraction. */ if (commandline.hasOption("3d")) { handle3Dtest(); return; } /* Handle -i; start CLI. */ if (Config.sharedConfig().getApi().getEnableCli() || commandline.hasOption('i')) { CineastCLI cli = new CineastCLI(); cli.start(); } /* Handle --setup; start database setup. */ if (commandline.hasOption("setup")) { HashMap<String, String> options = new HashMap<>(); String optionValue = commandline.getOptionValue("setup"); String[] flags = optionValue != null ? optionValue.split(";") : new String[0]; for (String flag : flags) { String[] pair = flag.split("="); if (pair.length == 2) { options.put(pair[0], pair[1]); } } handleSetup(options); return; } /* Start the RESTful API if it was configured. */ if (Config.sharedConfig().getApi().getEnableRest() || Config.sharedConfig().getApi().getEnableRestSecure() || Config.sharedConfig().getApi().getEnableWebsocket() || Config.sharedConfig().getApi().getEnableWebsocketSecure()) { handleHTTP(); } /* Start the Legacy API if it was configured. */ if (Config.sharedConfig().getApi().getEnableLegacy()) { handleLegacy(); } } else { LOGGER.fatal("Could not parse commandline arguments."); } } /** * Handles the database setup option (CLI and program-argument) */ private static void handleSetup(HashMap<String, String> options) { EntityCreator ec = Config.sharedConfig().getDatabase().getEntityCreatorSupplier().get(); if (ec != null) { ec.setup(options); } } /** * Starts the HTTP (RESTful / WebSocket) interface (CLI and program-argument) */ private static void handleHTTP() { System.out.println("Starting HTTP API..."); RestfulAPI.start(); System.out.println("HTTP API started!"); } /** * Starts the Legacy JSON interface (program-argument) */ private static void handleLegacy() { try { System.out.println("Starting Legacy API..."); ServerSocket ssocket = new ServerSocket(Config.sharedConfig().getApi().getLegacyPort()); while (running) { JSONAPIThread thread = new JSONAPIThread(ssocket.accept()); thread.start(); } ssocket.close(); } catch (IOException e) { System.err.println("Error occurred while listening on ServerSocket."); } } /** * Starts the codebook generation process (CLI only). A valid classname name, input/output path * and the number of words must be specified. * * @param name Name of the codebook generator class. Either a FQN oder the classes simple name. * @param input Path to the input folder containing the data to derive a codebook from (e.g. * images). * @param output Path to the output file for the codebook. * @param words The number of words in the codebook. */ private static void handleCodebook(String name, Path input, Path output, int words) { CodebookGenerator generator = ReflectionHelper.newCodebookGenerator(name); if (generator != null) { try { generator.generate(input, output, words); } catch (IOException e) { e.printStackTrace(); } } else { System.err .println(String.format("The specified codebook generator '%s' does not exist.", name)); } } /** * Starts the extraction process (CLI and program-argument). A valid configuration file (JSON) * must be provided in order to configure that extraction run. Refer to {@link IngestConfig} class for * structural information. * * @param file Configuration file for the extraction. * @see ExtractionDispatcher * @see IngestConfig */ private static void handleExtraction(File file) { ExtractionDispatcher dispatcher = new ExtractionDispatcher(); try { if (dispatcher.initialize(file)) { dispatcher.start(); } else { System.err.println(String.format( "Could not start handleExtraction with configuration file '%s'. Does the file exist?", file.toString())); } } catch (IOException e) { System.err.println(String.format( "Could not start handleExtraction with configuration file '%s' due to a IO error.", file.toString())); e.printStackTrace(); } } /** * Starts an evaluation process. A valid configuration file (JSON) must be provided in order * to configure that evaluation run. Refer to {@link EvaluationConfig} class for * structural information. * * @param path Path to the configuration file for the extraction. * @see EvaluationConfig */ private static void handleEvaluation(Path path) { try { EvaluationRuntime runtime = new EvaluationRuntime(path); runtime.call(); /* TODO: This is a quick & dirty solution. On the long run, API should probably have a dedicated ExecutorService for the different kinds of tasks it can dispatch. */ } catch (IOException e) { System.err.println(String.format("Could not start evaluation with configuration file '%s' due to a IO error.", path.toString())); e.printStackTrace(); } catch (EvaluationException e) { System.err.println(String.format("Something went wrong during the evaluation wiht '%s'.", path.toString())); e.printStackTrace(); } } /** * Starts the DataImportHandler for PROTO files. * * @param path Path to the file or folder that should be imported. * @param batchsize Batch size to use with the DataImportHandler */ private static void handleImport(Path path, int batchsize) { DataImportHandler handler = new DataImportHandler(2, batchsize); handler.importProto(path); handler.importJson(path); } /** * Performs a test of the JOGLOffscreenRenderer class. If the environment supports OpenGL * rendering, an image should be generated depicting two colored triangles on black background. If * OpenGL rendering is not supported, an exception will be thrown. */ private static void handle3Dtest() { System.out.println("Performing 3D test..."); Mesh mesh = new Mesh(2,6); mesh.addVertex(new Vector3f(1.0f, 0.0f, 0.0f), new Vector3f(1.0f, 0.0f, 0.0f)); mesh.addVertex(new Vector3f(0.0f, 1.0f, 0.0f), new Vector3f(0.0f, 1.0f, 0.0f)); mesh.addVertex(new Vector3f(0.0f, 0.0f, 1.0f), new Vector3f(0.0f, 0.0f, 1.0f)); mesh.addVertex(new Vector3f(-1.0f, 0.0f, 0.0f), new Vector3f(1.0f, 1.0f, 0.0f)); mesh.addVertex(new Vector3f(0.0f, -1.0f, 0.0f), new Vector3f(0.0f, 1.0f, 1.0f)); mesh.addVertex(new Vector3f(0.0f, 0.0f, 1.0f), new Vector3f(1.0f, 0.0f, 1.0f)); mesh.addFace(new Vector3i(1,2,3)); mesh.addFace(new Vector3i(4,5,6)); JOGLOffscreenRenderer renderer = new JOGLOffscreenRenderer(250, 250); renderer.retain(); renderer.positionCameraPolar(2.0f,0.0f,0.0f,0.0f,0.0f,0.0f); renderer.assemble(mesh); renderer.render(); BufferedImage image = renderer.obtain(); renderer.clear(); renderer.release(); try { ImageIO.write(image, "PNG", new File("cineast-3dtest.png")); System.out.println("3D test complete. Check for cineast-3dtest.png"); } catch (IOException e) { System.err.println("Could not save rendered image due to an IO error."); } } private static CommandLine handleCommandLine(String[] args) { Options options = new Options(); options.addOption("h", "help", false, "print this message"); options.addOption("i", "interactive", false, "enables the CLI independently of what is specified in the config"); options.addOption("3d", "test3d", false, "tests Cineast's off-screen 3D renderer. If test succeeds, an image should be exported"); Option configLocation = new Option(null, "config", true, "alternative config file, by default 'cineast.json' is used"); configLocation.setArgName("CONFIG_FILE"); options.addOption(configLocation); Option extractionJob = new Option(null, "job", true, "job file containing settings for handleExtraction"); extractionJob.setArgName("JOB_FILE"); options.addOption(extractionJob); options.addOption(Option.builder().longOpt("setup") .optionalArg(true) .numberOfArgs(1) .argName("FLAGS") .desc("initialize the underlying storage layer with optional <key=value> parameters").build()); CommandLineParser parser = new DefaultParser(); CommandLine line; try { line = parser.parse(options, args); } catch (ParseException e) { LOGGER.error("Error parsing command line arguments: {}", e.getMessage()); return null; } if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("cineast", options); } return line; } /** * @author rgasser * @version 1.0 * @created 22.01.17 */ private static class CineastCLI extends Thread { @Override public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Cineast CLI started."); String line = null; try { while ((line = reader.readLine()) != null) { line = line.trim(); if (line.isEmpty()) { continue; } Matcher matcher = inputSplitPattern.matcher(line); List<String> commands = new ArrayList<String>(); while (matcher.find()) { commands.add(matcher.group(1).replace("\"", "")); } if (commands.isEmpty()) { continue; } switch (commands.get(0).toLowerCase()) { case "extract": { if (commands.size() < 2) { System.err.println( "You must specify the path to the extraction configuration file (1 argument)."); break; } File file = new File(commands.get(1)); API.handleExtraction(file); break; } case "codebook": { if (commands.size() < 5) { System.err.println( "You must specify the name of the codebook generator, the source and destination path and the number of words for the codebook (4 arguments)."); break; } /* Parse information from input. */ String codebookGenerator = commands.get(1); Path src = Paths.get(commands.get(2)); Path dst = Paths.get(commands.get(3)); Integer words = Integer.parseInt(commands.get(4)); /* Start codebook generation. */ API.handleCodebook(codebookGenerator, src, dst, words); break; } case "import": { if (commands.size() < 2) { System.err.println("You must specify the path to data file/folder."); break; } Path path = Paths.get(commands.get(1)); int batchsize = 100; if (commands.size() == 3) { batchsize = Integer.parseInt(commands.get(2)); } handleImport(path, batchsize); break; } case "3d": case "test3d": { handle3Dtest(); break; } case "setup": { HashMap<String, String> options = new HashMap<>(); if (commands.size() > 1) { String[] flags = commands.get(1).split(";"); for (String flag : flags) { String[] pair = flag.split("="); if (pair.length == 2) { options.put(pair[0], pair[1]); } } } handleSetup(options); break; } // case "ws": // case "websocket": { // if (commands.size() < 2) { // System.err.println( // "You must specify whether you want to start or stop the websocket (1 argument)."); // break; // if (commands.get(1).toLowerCase().equals("start")) { // handleWebsocketStart(); // } else { // //handleWebsocketStop(); // break; case "retrieve": { if (commands.size() < 3) { System.err.println( "You must specify the segment id to be used as a query and the category of retrievers."); break; } String segmentId = commands.get(1); String category = commands.get(2); List<SegmentScoreElement> results = ContinuousRetrievalLogic .retrieve(segmentId, category, QueryConfig.newQueryConfigFromOther(Config.sharedConfig().getQuery())); System.out.println("results:"); for (SegmentScoreElement e : results) { System.out.print(e.getSegmentId()); System.out.print(": "); System.out.println(e.getScore()); } System.out.println(); break; } case "evaluation": case "evaluate": { if (commands.size() < 2) { System.err.println("You must specify the path to the evaluation configuration file (1 argument)."); break; } Path path = Paths.get(commands.get(1)); API.handleEvaluation(path); break; } case "exportresults": { ContinuousRetrievalLogic.addRetrievalResultListener( new RetrievalResultCSVExporter() ); System.out .println("added RetrievalResultCSVExporter to ContinuousRetrievalLogic"); break; } case "metadata": { if (commands.size() < 2) { System.err.println("You must specify at least one object id to lookup."); break; } List<String> ids = commands.subList(1, commands.size()); Ordering<MultimediaMetadataDescriptor> ordering = Ordering.explicit(ids).onResultOf(d -> d.getObjectId()); try (MultimediaMetadataReader r = new MultimediaMetadataReader()) { List<MultimediaMetadataDescriptor> descriptors = r.lookupMultimediaMetadata(ids); descriptors.sort(ordering); descriptors.forEach(System.out::println); } break; } case "adduser":{ if (commands.size() < 3) { System.err.println("You must specify username and password of the user to add"); break; } String username = commands.get(1); String password = commands.get(2); boolean admin = commands.size() >= 4 && commands.get(3).equalsIgnoreCase("admin"); CredentialManager.createUser(username, password, admin); break; } case "exit": case "quit": { System.exit(0); break; } case "help":{ System.out.println("3d\t\t\ttests the 3d rendering capabilities"); System.out.println("codebook\t\tgenerates a visual codebook from a folder containing images"); System.out.println("\t\t\t\t<generator> <source> <destination> <number of words>"); System.out.println("exit\t\t\texit cineast"); System.out.println("exportresults\t\tenables RetrievalResultCSVExporter for retrieval results"); System.out.println("help\t\t\tprints this message"); System.out.println("import\t\t\timports data from specified path into currently configured database"); System.out.println("\t\t\t\t<path>"); System.out.println("metadata\t\tshows all avalilable metadata for specified segment"); System.out.println("\t\t\t\t<segment id>"); System.out.println("quit\t\t\tsee 'exit'"); System.out.println("retrieve\t\tshows segments simiar to specified segment given the specified category"); System.out.println("\t\t\t\t<segment id> <category>"); System.out.println("setup\t\t\tinitializes database"); System.out.println("test3d\t\t\tsee '3d'"); System.out.println(); break; } default: System.err.println("unrecognized command: " + line); } } } catch (IOException e) { //ignore } } } public static RetrieverInitializer getInitializer() { return initializer; } }
package io.strimzi.operator.cluster.operator.assembly; import io.fabric8.kubernetes.api.model.Doneable; import io.fabric8.kubernetes.api.model.HasMetadata; import io.fabric8.kubernetes.api.model.KubernetesResourceList; import io.fabric8.kubernetes.api.model.ObjectMeta; import io.fabric8.kubernetes.api.model.Secret; import io.fabric8.kubernetes.client.KubernetesClient; import io.fabric8.kubernetes.client.KubernetesClientException; import io.fabric8.kubernetes.client.Watch; import io.fabric8.kubernetes.client.Watcher; import io.fabric8.kubernetes.client.dsl.Resource; import io.strimzi.certs.CertManager; import io.strimzi.certs.SecretCertProvider; import io.strimzi.certs.Subject; import io.strimzi.operator.cluster.InvalidConfigMapException; import io.strimzi.operator.cluster.Reconciliation; import io.strimzi.operator.cluster.model.AbstractModel; import io.strimzi.operator.cluster.model.AssemblyType; import io.strimzi.operator.cluster.model.Labels; import io.strimzi.operator.cluster.operator.resource.AbstractWatchableResourceOperator; import io.strimzi.operator.cluster.operator.resource.SecretOperator; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.shareddata.Lock; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.function.Consumer; import java.util.stream.Collectors; /** * <p>Abstract assembly creation, update, read, deletion, etc.</p> * * <p>An assembly is a collection of Kubernetes resources of various types * (e.g. Services, StatefulSets, Deployments etc) which operate together to provide some functionality.</p> * * <p>This class manages a per-assembly locking strategy so only one operation per assembly * can proceed at once.</p> */ public abstract class AbstractAssemblyOperator<C extends KubernetesClient, T extends HasMetadata, L extends KubernetesResourceList, D extends Doneable<T>, R extends Resource<T, D>> { private static final Logger log = LogManager.getLogger(AbstractAssemblyOperator.class.getName()); protected static final int LOCK_TIMEOUT_MS = 10000; protected static final int CERTS_EXPIRATION_DAYS = 365; protected final Vertx vertx; protected final boolean isOpenShift; protected final AssemblyType assemblyType; protected final AbstractWatchableResourceOperator<C, T, L, D, R> resourceOperator; protected final SecretOperator secretOperations; protected final CertManager certManager; private final String kind; /** * @param vertx The Vertx instance * @param isOpenShift True iff running on OpenShift * @param assemblyType Assembly type * @param resourceOperator For operating on the desired resource */ protected AbstractAssemblyOperator(Vertx vertx, boolean isOpenShift, AssemblyType assemblyType, CertManager certManager, AbstractWatchableResourceOperator<C, T, L, D, R> resourceOperator, SecretOperator secretOperations) { this.vertx = vertx; this.isOpenShift = isOpenShift; this.assemblyType = assemblyType; this.kind = assemblyType.name; this.resourceOperator = resourceOperator; this.certManager = certManager; this.secretOperations = secretOperations; } /** * Gets the name of the lock to be used for operating on the given {@code assemblyType}, {@code namespace} and * cluster {@code name} * @param assemblyType The type of cluster * @param namespace The namespace containing the cluster * @param name The name of the cluster */ protected final String getLockName(AssemblyType assemblyType, String namespace, String name) { return "lock::" + namespace + "::" + assemblyType + "::" + name; } /** * Subclasses implement this method to create or update the cluster. The implementation * should not assume that any resources are in any particular state (e.g. that the absence on * one resource means that all resources need to be created). * @param reconciliation Unique identification for the reconciliation * @param assemblyResource Resources with the desired cluster configuration. * @param assemblySecrets Secrets related to the cluster * @param handler Completion handler */ protected abstract void createOrUpdate(Reconciliation reconciliation, T assemblyResource, List<Secret> assemblySecrets, Handler<AsyncResult<Void>> handler); /** * Subclasses implement this method to delete the cluster. * @param handler Completion handler */ protected abstract void delete(Reconciliation reconciliation, Handler<AsyncResult<Void>> handler); /** * The name of the given {@code resource}, as read from its metadata. * @param resource The resource */ protected static String name(HasMetadata resource) { if (resource != null) { ObjectMeta metadata = resource.getMetadata(); if (metadata != null) { return metadata.getName(); } } return null; } private final void reconcileClusterCa(Reconciliation reconciliation, Handler<AsyncResult<Void>> handler) { vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking( future -> { String clusterCaName = AbstractModel.getClusterCaName(reconciliation.assemblyName()); if (secretOperations.get(reconciliation.namespace(), clusterCaName) == null) { log.debug("{}: Generating cluster CA certificate {}", reconciliation, clusterCaName); File clusterCAkeyFile = null; File clusterCAcertFile = null; try { clusterCAkeyFile = File.createTempFile("tls", "cluster-ca-key"); clusterCAcertFile = File.createTempFile("tls", "cluster-ca-cert"); Subject sbj = new Subject(); sbj.setOrganizationName("io.strimzi"); sbj.setCommonName("cluster-ca"); certManager.generateSelfSignedCert(clusterCAkeyFile, clusterCAcertFile, sbj, CERTS_EXPIRATION_DAYS); SecretCertProvider secretCertProvider = new SecretCertProvider(); Secret secret = secretCertProvider.createSecret(reconciliation.namespace(), clusterCaName, "cluster-ca.key", "cluster-ca.crt", clusterCAkeyFile, clusterCAcertFile, Collections.emptyMap()); secretOperations.reconcile(reconciliation.namespace(), clusterCaName, secret) .compose(future::complete, future); } catch (Throwable e) { future.fail(e); } finally { if (clusterCAkeyFile != null) clusterCAkeyFile.delete(); if (clusterCAcertFile != null) clusterCAcertFile.delete(); } log.debug("{}: End generating cluster CA {}", reconciliation, clusterCaName); } else { log.debug("{}: The cluster CA {} already exists", reconciliation, clusterCaName); future.complete(); } }, true, res -> { if (res.succeeded()) handler.handle(Future.succeededFuture()); else handler.handle(Future.failedFuture(res.cause())); } ); } private final void deleteClusterCa(Reconciliation reconciliation, Handler<AsyncResult<Void>> handler) { vertx.createSharedWorkerExecutor("kubernetes-ops-pool").executeBlocking( future -> { String clusterCaName = AbstractModel.getClusterCaName(reconciliation.assemblyName()); if (secretOperations.get(reconciliation.namespace(), clusterCaName) != null) { log.debug("{}: Deleting cluster CA certificate {}", reconciliation, clusterCaName); secretOperations.reconcile(reconciliation.namespace(), clusterCaName, null) .compose(future::complete, future); log.debug("{}: Cluster CA {} deleted", reconciliation, clusterCaName); } else { log.debug("{}: The cluster CA {} doesn't exist", reconciliation, clusterCaName); future.complete(); } }, true, res -> { if (res.succeeded()) handler.handle(Future.succeededFuture()); else handler.handle(Future.failedFuture(res.cause())); } ); } /** * Reconcile assembly resources in the given namespace having the given {@code assemblyName}. * Reconciliation works by getting the assembly resource (e.g. {@code KafkaAssembly}) in the given namespace with the given assemblyName and * comparing with the corresponding {@linkplain #getResources(String, Labels) resource}. * <ul> * <li>An assembly will be {@linkplain #createOrUpdate(Reconciliation, T, List, Handler) created or updated} if ConfigMap is without same-named resources</li> * <li>An assembly will be {@linkplain #delete(Reconciliation, Handler) deleted} if resources without same-named ConfigMap</li> * </ul> */ public final void reconcileAssembly(Reconciliation reconciliation, Handler<AsyncResult<Void>> handler) { String namespace = reconciliation.namespace(); String assemblyName = reconciliation.assemblyName(); final String lockName = getLockName(assemblyType, namespace, assemblyName); vertx.sharedData().getLockWithTimeout(lockName, LOCK_TIMEOUT_MS, res -> { if (res.succeeded()) { log.debug("{}: Lock {} acquired", reconciliation, lockName); Lock lock = res.result(); try { // get CustomResource and related resources for the specific cluster T cr = resourceOperator.get(namespace, assemblyName); if (cr != null) { log.info("{}: Assembly {} should be created or updated", reconciliation, assemblyName); reconcileClusterCa(reconciliation, certResult -> { Labels labels = Labels.forCluster(assemblyName); List<Secret> secrets = secretOperations.list(namespace, labels); secrets.add(secretOperations.get(namespace, AbstractModel.getClusterCaName(assemblyName))); if (certResult.succeeded()) { createOrUpdate(reconciliation, cr, secrets, createResult -> { lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); if (createResult.failed()) { if (createResult.cause() instanceof InvalidConfigMapException) { log.error(createResult.cause().getMessage()); } else { log.error("{}: createOrUpdate failed", reconciliation, createResult.cause()); } } else { handler.handle(createResult); } }); } else { log.error("{}: reconcileClusterCa failed", reconciliation, certResult.cause()); lock.release(); } }); } else { log.info("{}: Assembly {} should be deleted", reconciliation, assemblyName); delete(reconciliation, deleteResult -> { if (deleteResult.succeeded()) { log.info("{}: Assembly {} deleted", reconciliation, assemblyName); deleteClusterCa(reconciliation, caDeleteResult -> { lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); handler.handle(caDeleteResult); }); } else { log.error("{}: Deletion of assembly {} failed", reconciliation, assemblyName, deleteResult.cause()); lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); handler.handle(deleteResult); } }); } } catch (Throwable ex) { lock.release(); log.debug("{}: Lock {} released", reconciliation, lockName); handler.handle(Future.failedFuture(ex)); } } else { log.debug("{}: Failed to acquire lock {}.", reconciliation, lockName); } }); } /** * Reconcile assembly resources in the given namespace having the given selector. * Reconciliation works by getting the assembly ConfigMaps in the given namespace with the given selector and * comparing with the corresponding {@linkplain #getResources(String, Labels) resource}. * <ul> * <li>An assembly will be {@linkplain #createOrUpdate(Reconciliation, T, List, Handler) created} for all ConfigMaps without same-named resources</li> * <li>An assembly will be {@linkplain #delete(Reconciliation, Handler) deleted} for all resources without same-named ConfigMaps</li> * </ul> * * @param trigger A description of the triggering event (timer or watch), used for logging * @param namespace The namespace */ public final CountDownLatch reconcileAll(String trigger, String namespace) { // get ConfigMaps with kind=cluster&type=kafka (or connect, or connect-s2i) for the corresponding cluster type List<T> desiredResources = resourceOperator.list(namespace, Labels.EMPTY); Set<String> desiredNames = desiredResources.stream().map(cm -> cm.getMetadata().getName()).collect(Collectors.toSet()); log.debug("reconcileAll({}, {}): desired resources with labels {}: {}", assemblyType, trigger, Labels.EMPTY, desiredNames); // get resources with kind=cluster&type=kafka (or connect, or connect-s2i) Labels resourceSelector = Labels.EMPTY.withKind(assemblyType.name); List<? extends HasMetadata> resources = getResources(namespace, resourceSelector); // now extract the cluster name from those Set<String> resourceNames = resources.stream() .filter(r -> !r.getKind().equals(kind)) // exclude desired resource .map(Labels::cluster) .collect(Collectors.toSet()); log.debug("reconcileAll({}, {}): Other resources with labels {}: {}", assemblyType, trigger, resourceSelector, resourceNames); desiredNames.addAll(resourceNames); // We use a latch so that callers (specifically, test callers) know when the reconciliation is complete // Using futures would be more complex for no benefit CountDownLatch latch = new CountDownLatch(desiredNames.size()); for (String name: desiredNames) { Reconciliation reconciliation = new Reconciliation(trigger, assemblyType, namespace, name); reconcileAssembly(reconciliation, result -> { handleResult(reconciliation, result); latch.countDown(); }); } return latch; } /** * Gets all the assembly resources (for all assemblies) in the given namespace. * Assembly resources (e.g. the {@code KafkaAssembly} resource) may be included in the result. * @param namespace The namespace * @return The matching resources. */ protected abstract List<HasMetadata> getResources(String namespace, Labels selector); public Future<Watch> createWatch(String namespace, Consumer<KubernetesClientException> onClose) { Future<Watch> result = Future.future(); vertx.<Watch>executeBlocking( future -> { Watch watch = resourceOperator.watch(namespace, new Watcher<T>() { @Override public void eventReceived(Action action, T cm) { String name = cm.getMetadata().getName(); switch (action) { case ADDED: case DELETED: case MODIFIED: Reconciliation reconciliation = new Reconciliation("watch", assemblyType, namespace, name); log.info("{}: {} {} in namespace {} was {}", reconciliation, kind, name, namespace, action); reconcileAssembly(reconciliation, result -> { handleResult(reconciliation, result); }); break; case ERROR: log.error("Failed {} {} in namespace{} ", kind, name, namespace); reconcileAll("watch error", namespace); break; default: log.error("Unknown action: {} in namespace {}", name, namespace); reconcileAll("watch unknown", namespace); } } @Override public void onClose(KubernetesClientException e) { onClose.accept(e); } }); future.complete(watch); }, result.completer() ); return result; } /** * Log the reconciliation outcome. */ private void handleResult(Reconciliation reconciliation, AsyncResult<Void> result) { if (result.succeeded()) { log.info("{}: Assembly reconciled", reconciliation); } else { Throwable cause = result.cause(); if (cause instanceof InvalidConfigMapException) { log.warn("{}: Failed to reconcile {}", reconciliation, cause.getMessage()); } else { log.warn("{}: Failed to reconcile", reconciliation, cause); } } } }
package io.cattle.platform.iaas.api.credential; import io.cattle.platform.api.link.LinkHandler; import io.cattle.platform.core.constants.CredentialConstants; import io.cattle.platform.core.model.Credential; import io.github.ibuildthecloud.gdapi.context.ApiContext; import io.github.ibuildthecloud.gdapi.id.IdFormatter; import io.github.ibuildthecloud.gdapi.request.ApiRequest; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; public class SshKeyPemDownloadLinkHandler implements LinkHandler { @Override public String[] getTypes() { return new String[] { "sshKey" }; } @Override public boolean handles(String type, String id, String link, ApiRequest request) { return CredentialConstants.LINK_PEM_FILE.equalsIgnoreCase(link); } @Override public Object link(String name, Object obj, ApiRequest request) throws IOException { if ( obj instanceof Credential ) { String secretValue = ((Credential)obj).getSecretValue(); if ( secretValue == null ) { return null; } byte[] content = secretValue.getBytes("UTF-8"); HttpServletResponse response = request.getServletContext().getResponse(); response.setContentLength(content.length); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + getFilename((Credential)obj, request)); response.setHeader("Cache-Control", "private"); response.setHeader("Pragma", "private"); response.setHeader("Expires", "Wed 24 Feb 1982 18:42:00 GMT"); response.getOutputStream().write(content); return new Object(); } return null; } protected String getFilename(Credential cred, ApiRequest request) { String name = cred.getName(); if ( StringUtils.isBlank(name) ) { IdFormatter formatter = ApiContext.getContext().getIdFormatter(); Object id = formatter.formatId(cred.getKind(), cred.getId()); return "id_rsa_" + id + ".pem"; } else { return name.trim().replaceAll("[^a-zA-Z0-9]", "_") + ".pem"; } } }
package org.openforis.collect.designer.form.validator; import org.apache.commons.lang3.StringUtils; import org.openforis.idm.metamodel.NodeDefinition; import org.zkoss.bind.ValidationContext; import org.zkoss.util.resource.Labels; /** * @author S. Ricci * */ public class DistanceCheckFormValidator extends CheckFormValidator { private static final String SOURCE_POINT_EXPRESSION_FIELD = "sourcePointExpression"; private static final String DESTINATION_POINT_EXPRESSION_FIELD = "destinationPointExpression"; private static final String MIN_DISTANCE_FIELD = "minDistanceExpression"; private static final String MAX_DISTANCE_FIELD = "maxDistanceExpression"; private String MIN_OR_MAX_REQUIRED_MESSAGE_KEY = "survey.schema.node.check.distance.validation.min_or_max_distance_not_specified"; @Override protected void internalValidate(ValidationContext ctx) { super.internalValidate(ctx); NodeDefinition contextNode = getContextNode(ctx); if ( validateMinOrMaxExpressionRequireness(ctx) ) { validateValueExpression(ctx, contextNode, MIN_DISTANCE_FIELD); validateValueExpression(ctx, contextNode, MAX_DISTANCE_FIELD); } validateValueExpression(ctx, contextNode, SOURCE_POINT_EXPRESSION_FIELD); validateValueExpression(ctx, contextNode, DESTINATION_POINT_EXPRESSION_FIELD); } protected boolean validateMinOrMaxExpressionRequireness(ValidationContext ctx) { String minExpr = getValue(ctx, MIN_DISTANCE_FIELD); String maxExpr = getValue(ctx, MAX_DISTANCE_FIELD); if ( StringUtils.isBlank(minExpr) && StringUtils.isBlank(maxExpr) ) { this.addInvalidMessage(ctx, MIN_DISTANCE_FIELD, Labels.getLabel(MIN_OR_MAX_REQUIRED_MESSAGE_KEY)); this.addInvalidMessage(ctx, MAX_DISTANCE_FIELD, Labels.getLabel(MIN_OR_MAX_REQUIRED_MESSAGE_KEY)); return false; } else { return true; } } }
package com.archimatetool.canvas.templates.wizard; import java.io.File; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; 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.Text; import org.eclipse.ui.PlatformUI; import com.archimatetool.canvas.model.ICanvasModel; import com.archimatetool.canvas.templates.model.CanvasTemplateManager; import com.archimatetool.editor.ui.IArchiImages; import com.archimatetool.editor.ui.UIUtils; import com.archimatetool.editor.utils.StringUtils; import com.archimatetool.templates.model.TemplateManager; import com.archimatetool.templates.wizard.TemplateUtils; /** * Save Canvas As Template Wizard Page 1 * * @author Phillip Beauvoir */ public class SaveCanvasAsTemplateWizardPage extends WizardPage { private static String HELP_ID = "com.archimatetool.help.SaveCanvasAsTemplateWizardPage"; //$NON-NLS-1$ private ICanvasModel fCanvasModel; private Text fFileTextField; private Text fNameTextField; private Text fDescriptionTextField; private Label fPreviewLabel; private Button fButtonIncludeThumbnail; private TemplateManager fTemplateManager; static File CURRENT_FOLDER = new File(System.getProperty("user.home")); //$NON-NLS-1$ public SaveCanvasAsTemplateWizardPage(ICanvasModel canvasModel, TemplateManager templateManager) { super("SaveCanvasAsTemplateWizardPage"); //$NON-NLS-1$ setTitle(Messages.SaveCanvasAsTemplateWizardPage_0); setDescription(Messages.SaveCanvasAsTemplateWizardPage_1); setImageDescriptor(IArchiImages.ImageFactory.getImageDescriptor(IArchiImages.ECLIPSE_IMAGE_NEW_WIZARD)); fCanvasModel = canvasModel; fTemplateManager = templateManager; } @Override public void createControl(Composite parent) { GridData gd; Label label; Composite container = new Composite(parent, SWT.NULL); container.setLayout(new GridLayout()); setControl(container); PlatformUI.getWorkbench().getHelpSystem().setHelp(container, HELP_ID); Group fileComposite = new Group(container, SWT.NULL); fileComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridLayout layout = new GridLayout(3, false); fileComposite.setLayout(layout); label = new Label(fileComposite, SWT.NULL); label.setText(Messages.SaveCanvasAsTemplateWizardPage_2); fFileTextField = new Text(fileComposite, SWT.BORDER | SWT.SINGLE); fFileTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); File newFile = new File(CURRENT_FOLDER, Messages.SaveCanvasAsTemplateWizardPage_3 + CanvasTemplateManager.CANVAS_TEMPLATE_FILE_EXTENSION); fFileTextField.setText(newFile.getPath()); // Single text control so strip CRLFs UIUtils.conformSingleTextControl(fFileTextField); fFileTextField.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validateFields(); } }); Button fileButton = new Button(fileComposite, SWT.PUSH); fileButton.setText(Messages.SaveCanvasAsTemplateWizardPage_4); fileButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { File file = chooseFile(); if(file != null) { fFileTextField.setText(file.getPath()); CURRENT_FOLDER = file.getParentFile(); } } }); Group fieldGroup = new Group(container, SWT.NULL); fieldGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout = new GridLayout(2, false); fieldGroup.setLayout(layout); label = new Label(fieldGroup, SWT.NULL); label.setText(Messages.SaveCanvasAsTemplateWizardPage_5); fNameTextField = new Text(fieldGroup, SWT.BORDER | SWT.SINGLE); fNameTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if(StringUtils.isSet(fCanvasModel.getName())) { fNameTextField.setText(fCanvasModel.getName()); } // Single text control so strip CRLFs UIUtils.conformSingleTextControl(fNameTextField); fNameTextField.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validateFields(); } }); label = new Label(fieldGroup, SWT.NULL); label.setText(Messages.SaveCanvasAsTemplateWizardPage_6); gd = new GridData(SWT.NULL, SWT.TOP, false, false); label.setLayoutData(gd); fDescriptionTextField = new Text(fieldGroup, SWT.BORDER | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 120; gd.widthHint = 550; // Stop overstretch fDescriptionTextField.setLayoutData(gd); if(StringUtils.isSet(fCanvasModel.getDocumentation())) { fDescriptionTextField.setText(fCanvasModel.getDocumentation()); } // Thumbnail Group thumbsGroup = new Group(container, SWT.NULL); thumbsGroup.setLayoutData(new GridData(GridData.FILL_BOTH)); layout = new GridLayout(2, false); thumbsGroup.setLayout(layout); fButtonIncludeThumbnail = new Button(thumbsGroup, SWT.CHECK); fButtonIncludeThumbnail.setText(Messages.SaveCanvasAsTemplateWizardPage_7); fButtonIncludeThumbnail.setSelection(true); fButtonIncludeThumbnail.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { fPreviewLabel.setEnabled(fButtonIncludeThumbnail.getSelection()); } }); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalSpan = 2; fButtonIncludeThumbnail.setLayoutData(gd); label = new Label(thumbsGroup, SWT.NULL); label.setText(Messages.SaveCanvasAsTemplateWizardPage_8 + " "); //$NON-NLS-1$ gd = new GridData(SWT.NULL, SWT.TOP, false, false); label.setLayoutData(gd); fPreviewLabel = new Label(thumbsGroup, SWT.BORDER); gd = new GridData(GridData.FILL_BOTH); gd.heightHint = 120; gd.widthHint = 150; fPreviewLabel.setLayoutData(gd); // Dispose of the image here not in the main dispose() method because if the help system is showing then // the TrayDialog is resized and this label is asked to relayout. fPreviewLabel.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { disposePreviewImage(); } }); Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { TemplateUtils.createThumbnailPreviewImage(fCanvasModel, fPreviewLabel); } }); fPreviewLabel.addControlListener(new ControlAdapter() { int oldTime; @Override public void controlResized(ControlEvent e) { if(e.time - oldTime > 10) { disposePreviewImage(); TemplateUtils.createThumbnailPreviewImage(fCanvasModel, fPreviewLabel); } oldTime = e.time; } }); validateFields(); } /**r * @return The File for the template */ public String getFileName() { return fFileTextField.getText(); } /** * @return The Name for the template */ public String getTemplateName() { return fNameTextField.getText(); } /** * @return The Name for the template */ public String getTemplateDescription() { return fDescriptionTextField.getText(); } public boolean includeThumbnail() { return fButtonIncludeThumbnail.getSelection(); } private File chooseFile() { FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); dialog.setText(Messages.SaveCanvasAsTemplateWizardPage_9); dialog.setFilterExtensions(new String[] { "*" + fTemplateManager.getTemplateFileExtension(), "*.*" } ); //$NON-NLS-1$ //$NON-NLS-2$ String path = dialog.open(); if(path != null) { // Only Windows adds the extension by default if(dialog.getFilterIndex() == 0 && !path.endsWith(CanvasTemplateManager.CANVAS_TEMPLATE_FILE_EXTENSION)) { path += CanvasTemplateManager.CANVAS_TEMPLATE_FILE_EXTENSION; } return new File(path); } return null; } private void validateFields() { String fileName = getFileName(); if(!StringUtils.isSetAfterTrim(fileName)) { updateStatus(Messages.SaveCanvasAsTemplateWizardPage_10); return; } String name = getTemplateName(); if(!StringUtils.isSetAfterTrim(name)) { updateStatus(Messages.SaveCanvasAsTemplateWizardPage_11); return; } updateStatus(null); } /** * Update the page status */ private void updateStatus(String message) { setErrorMessage(message); setPageComplete(message == null); } private void disposePreviewImage() { if(fPreviewLabel != null && fPreviewLabel.getImage() != null && !fPreviewLabel.getImage().isDisposed()) { fPreviewLabel.getImage().dispose(); } } }
package com.intellij.mock; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.PsiManagerEx; import com.intellij.psi.impl.file.impl.FileManager; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.containers.FactoryMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author peter */ public class MockFileManager implements FileManager { private PsiManagerEx myManager; private FactoryMap<VirtualFile,FileViewProvider> myViewProviders = new FactoryMap<VirtualFile, FileViewProvider>() { protected FileViewProvider create(final VirtualFile key) { return new SingleRootFileViewProvider(myManager, key); } }; public FileViewProvider createFileViewProvider(final VirtualFile file, final boolean physical) { return new SingleRootFileViewProvider(myManager, file, physical); } public MockFileManager(final PsiManagerEx manager) { myManager = manager; } public void dispose() { throw new UnsupportedOperationException("Method dispose is not yet implemented in " + getClass().getName()); } public void runStartupActivity() { throw new UnsupportedOperationException("Method runStartupActivity is not yet implemented in " + getClass().getName()); } @Nullable public PsiFile findFile(@NotNull VirtualFile vFile) { return getCachedPsiFile(vFile); } @Nullable public PsiDirectory findDirectory(@NotNull VirtualFile vFile) { throw new UnsupportedOperationException("Method findDirectory is not yet implemented in " + getClass().getName()); } public void reloadFromDisk(@NotNull PsiFile file) //Q: move to PsiFile(Impl)? { throw new UnsupportedOperationException("Method reloadFromDisk is not yet implemented in " + getClass().getName()); } @Nullable public PsiFile getCachedPsiFile(@NotNull VirtualFile vFile) { final FileViewProvider provider = findCachedViewProvider(vFile); return provider.getPsi(provider.getBaseLanguage()); } @NotNull public GlobalSearchScope getResolveScope(@NotNull PsiElement element) { return new MockGlobalSearchScope(); } @NotNull public GlobalSearchScope getUseScope(@NotNull PsiElement element) { return GlobalSearchScope.allScope(element.getProject()); } public void cleanupForNextTest() { throw new UnsupportedOperationException("Method cleanupForNextTest is not yet implemented in " + getClass().getName()); } public FileViewProvider findViewProvider(VirtualFile file) { throw new UnsupportedOperationException("Method findViewProvider is not yet implemented in " + getClass().getName()); } public FileViewProvider findCachedViewProvider(VirtualFile file) { return myViewProviders.get(file); } public void setViewProvider(VirtualFile virtualFile, FileViewProvider fileViewProvider) { myViewProviders.put(virtualFile, fileViewProvider); } public List<PsiFile> getAllCachedFiles() { throw new UnsupportedOperationException("Method getAllCachedFiles is not yet implemented in " + getClass().getName()); } }
package etomica.freeenergy.npath; import etomica.action.BoxInflate; import etomica.action.activity.ActivityIntegrate; import etomica.atom.AtomType; import etomica.atom.DiameterHash; import etomica.atom.DiameterHashByType; import etomica.atom.IAtom; import etomica.box.Box; import etomica.chem.elements.Iron; import etomica.config.ConfigurationLattice; import etomica.data.*; import etomica.data.history.HistoryCollapsingAverage; import etomica.data.history.HistoryScrolling; import etomica.data.meter.*; import etomica.graphics.ColorScheme; import etomica.graphics.DisplayPlot; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorEvent; import etomica.integrator.IntegratorListener; import etomica.integrator.IntegratorMC; import etomica.integrator.IntegratorVelocityVerlet; import etomica.lattice.LatticeCubicBcc; import etomica.lattice.LatticeCubicFcc; import etomica.lattice.LatticeHcp4; import etomica.lattice.SpaceLattice; import etomica.lattice.crystal.Primitive; import etomica.lattice.crystal.PrimitiveCubic; import etomica.lattice.crystal.PrimitiveHCP4; import etomica.meam.P2EAM; import etomica.meam.PotentialCalculationEnergySumEAM; import etomica.nbr.cell.PotentialMasterCell; import etomica.nbr.list.PotentialMasterList; import etomica.potential.PotentialCalculationForceSum; import etomica.simulation.Simulation; import etomica.space.Vector; import etomica.space3d.Space3D; import etomica.species.SpeciesSpheresMono; import etomica.units.*; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import java.awt.*; import java.util.Arrays; import static etomica.freeenergy.npath.SimFe.Crystal.HCP; public class SimFe extends Simulation { public final PotentialMasterList potentialMaster; public final ActivityIntegrate ai; public IntegratorVelocityVerlet integrator; public SpeciesSpheresMono species; public Box box; public P2EAM potential; public P1ImageHarmonic p1ImageHarmonic; public MCMoveAtomSwap mcMoveSwap; public SimFe(Crystal crystal, int numAtoms, double temperature, double density, double w, int offsetDim, int numInnerSteps, boolean swap, boolean doHarmonic) { super(Space3D.getInstance()); species = new SpeciesSpheresMono(space, Iron.INSTANCE); species.setIsDynamic(true); addSpecies(species); box = new Box(space); addBox(box); box.setNMolecules(species, numAtoms); Primitive primitive = (crystal == HCP) ? new PrimitiveHCP4(space) : new PrimitiveCubic(space); Vector l = space.makeVector(); double[] primitiveSize = primitive.getSize(); int[] f = new int[]{10,10,10}; if (crystal == HCP) f = new int[]{6,4,4}; for (int i=0; i<3; i++) { double x = f[i]*primitiveSize[i]; if (i<=offsetDim) x *= 2; l.setX(i,x); } box.getBoundary().setBoxSize(l); BoxInflate inflater = new BoxInflate(box, space); inflater.setTargetDensity(density); inflater.actionPerformed(); double n = 8.7932; double m = 8.14475; double eps = ElectronVolt.UNIT.toSim(0.0220225); double a = 3.48501; double C = 28.8474; double rc = 6; potential = new P2EAM(space, n, m, eps, a, C, rc, rc); potentialMaster = new PotentialMasterList(this, 1.2*rc, space); potentialMaster.getNbrCellManager(box).setSuppressBoxLengthWarning(true); potentialMaster.setCellRange(2); AtomType leafType = species.getLeafType(); potentialMaster.addPotential(potential, new AtomType[]{leafType, leafType}); Vector offset = space.makeVector(); offset.setX(offsetDim, box.getBoundary().getBoxSize().getX(offsetDim) * 0.5); p1ImageHarmonic = new P1ImageHarmonic(space, offset, w, !doHarmonic); potentialMaster.addPotential(p1ImageHarmonic, new AtomType[]{leafType}); if (numInnerSteps > 0 && w > 0) { if (doHarmonic) { integrator = new IntegratorImageHarmonicMD(potentialMaster, random, 0.001, temperature, space); ((IntegratorImageHarmonicMD) integrator).setP1Harmonic(p1ImageHarmonic); } else { integrator = new IntegratorImageMultistepMD(potentialMaster, random, 0.001, temperature, space); ((IntegratorImageMultistepMD) integrator).setP1Harmonic(p1ImageHarmonic); ((IntegratorImageMultistepMD) integrator).setNumInnerSteps(numInnerSteps); } } else { integrator = new IntegratorVelocityVerlet(potentialMaster, random, 0.001, temperature, space); } MeterPotentialEnergy meterPE = new MeterPotentialEnergy(potentialMaster); meterPE.setPotentialCalculation(new PotentialCalculationEnergySumEAM(potential)); integrator.setMeterPotentialEnergy(meterPE); integrator.setIsothermal(true); integrator.setTemperature(temperature); integrator.setThermostatNoDrift(true); integrator.getEventManager().addListener(potential.makeIntegratorListener(potentialMaster, box)); integrator.setForceSum(new PotentialCalculationForceSum()); ai = new ActivityIntegrate(integrator); getController().addAction(ai); integrator.setBox(box); p1ImageHarmonic.setZeroForce(true); SpaceLattice lat = null; if (crystal == Crystal.FCC) { lat = new LatticeCubicFcc(space); } else if (crystal == Crystal.BCC) { lat = new LatticeCubicBcc(space); } else if (crystal == HCP) { lat = new LatticeHcp4(space); } else { throw new RuntimeException("Don't know how to do "+crystal); } ConfigurationLattice config = new ConfigurationLattice(lat, space); config.initializeCoordinates(box); p1ImageHarmonic.findNOffset(box); integrator.getEventManager().addListener(potentialMaster.getNeighborManager(box)); potentialMaster.getNeighborManager(box).reset(); Vector boxLength = box.getBoundary().getBoxSize(); double lMin = boxLength.getX(0); if (boxLength.getX(1) < lMin) lMin = boxLength.getX(1); if (boxLength.getX(2) < lMin) lMin = boxLength.getX(2); double ww = w / lMin; double swapDistance = 1.5*Math.sqrt(1.5*temperature/ww); if (swapDistance > lMin/4) swapDistance = lMin/4; if (swapDistance > rc) swapDistance = rc; if (swapDistance < 2) swapDistance = 2; PotentialMasterCell potentialMasterCell = new PotentialMasterCell(this, swapDistance, space); potentialMasterCell.setCellRange(2); potentialMasterCell.getNbrCellManager(box).assignCellAll(); if (swap) { mcMoveSwap = new MCMoveAtomSwap(random, potentialMasterCell, space, p1ImageHarmonic); mcMoveSwap.setNbrDistance(swapDistance); IntegratorMC integratorMC = new IntegratorMC(potentialMaster, random, temperature); integratorMC.getMoveManager().addMCMove(mcMoveSwap); integratorMC.setBox(box); integratorMC.reset(); integrator.getEventManager().addListener(new IntegratorListener() { int countdown = 10, interval = 10; public void integratorInitialized(IntegratorEvent e) { } public void integratorStepStarted(IntegratorEvent e) { } @Override public void integratorStepFinished(IntegratorEvent e) { if (--countdown > 0) { return; } countdown = interval; potentialMasterCell.getNbrCellManager(box).assignCellAll(); for (int i = 0; i < 10 * numAtoms; i++) { integratorMC.doStep(); } integrator.reset(); } }); } } public static void main(String[] args) { LjMC3DParams params = new LjMC3DParams(); ParseArgs.doParseArgs(params, args); if (args.length==0) { params.graphics = true; params.numAtoms = 1024; params.steps = 10000; params.density = 0.150375939849624; params.T = 7947.1916; params.w = 8048.485777; params.crystal = Crystal.BCC; params.offsetDim = 2; params.numInnerSteps = 100; params.swap = true; params.nve = false; params.rmsdFile = "rmsd.dat"; params.thermostatInterval = 500; } final int numAtoms = params.numAtoms; final double temperatureK = params.T; final double temperature = Kelvin.UNIT.toSim(temperatureK); final double density = params.density; long steps = params.steps; boolean graphics = params.graphics; double w = params.w; int offsetDim = params.offsetDim; Crystal crystal = params.crystal; boolean swap = params.swap; int numInnerSteps = w > 0 ? params.numInnerSteps : 0; boolean nve = params.nve; int thermostatInterval = params.thermostatInterval; boolean doHarmonic = params.doHarmonic; String rmsdFile = params.rmsdFile; double timeStep = params.timeStep; int interval = 10; if (Math.abs(timeStep - 0.001) > 1e-10) { int fac = (int) Math.round(0.001 / timeStep); thermostatInterval *= fac; interval *= fac; } if (!graphics) { System.out.println("Running Iron MC with N="+numAtoms+" at rho="+density+" T="+temperatureK); System.out.println(steps+" steps"); System.out.println("w: "+w); if (!doHarmonic && numInnerSteps > 0) System.out.println(numInnerSteps + " inner steps"); System.out.println("thermostat interval: " + thermostatInterval); } double L = Math.pow(numAtoms/density, 1.0/3.0); final SimFe sim = new SimFe(crystal, numAtoms, temperature, density, w, offsetDim, numInnerSteps, swap, doHarmonic); if (sim.integrator instanceof IntegratorImageHarmonicMD) { System.out.println("internal dimer velocity randomized: " + ((IntegratorImageHarmonicMD) sim.integrator).getRandomizeProbability()); int[] seeds = sim.getRandomSeeds(); if (seeds != null) System.out.println("random seeds: " + Arrays.toString(seeds)); } DataSourceEnergies dsEnergies = new DataSourceEnergies(sim.potentialMaster); dsEnergies.setPotentialCalculation(new DataSourceEnergies.PotentialCalculationEnergiesEAM(sim.potential)); dsEnergies.setBox(sim.box); IData u = dsEnergies.getData(); if (!graphics) System.out.println("Fe lattice energy (eV/atom): "+ElectronVolt.UNIT.fromSim(u.getValue(1)/numAtoms)); MeterStructureFactor meterSfac = new MeterStructureFactor(sim.space, sim.box, 8); if (graphics) { sim.integrator.setThermostatInterval(thermostatInterval); final String APP_NAME = "SimFe"; final SimulationGraphic simGraphic = new SimulationGraphic(sim, SimulationGraphic.TABBED_PANE, APP_NAME, 3, sim.getSpace(), sim.getController()); ColorScheme colorScheme = new ColorScheme() { @Override public Color getAtomColor(IAtom a) { int idx0 = a.getLeafIndex(); int idx1 = sim.p1ImageHarmonic.getPartner(idx0); return idx0 < idx1 ? Color.RED : Color.BLUE; } }; simGraphic.getDisplayBox(sim.box).setColorScheme(colorScheme); DiameterHash diameter = simGraphic.getDisplayBox(sim.box).getDiameterHash(); ((DiameterHashByType)diameter).setDiameter(sim.species.getLeafType(),2); simGraphic.getController().getReinitButton().setPostAction(simGraphic.getPaintAction(sim.box)); DataSourceCountTime tSource = new DataSourceCountTime(sim.integrator); AccumulatorHistory energyHist = new AccumulatorHistory(new HistoryCollapsingAverage()); energyHist.setTimeDataSource(tSource); AccumulatorHistory springHist = new AccumulatorHistory(new HistoryCollapsingAverage()); springHist.setTimeDataSource(tSource); DataSplitter splitter = new DataSplitter(); DataPumpListener energyPump = new DataPumpListener(dsEnergies, splitter, interval); sim.integrator.getEventManager().addListener(energyPump); splitter.setDataSink(0, springHist); splitter.setDataSink(1, energyHist); DisplayPlot energyPlot = new DisplayPlot(); energyPlot.setLabel("Fe"); energyPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); // energyPlot.setUnit(new CompoundUnit(new Unit[]{ElectronVolt.UNIT, new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{1,-1})); // energyPlot.setUnit(ElectronVolt.UNIT); energyHist.addDataSink(energyPlot.getDataSet().makeDataSink()); simGraphic.add(energyPlot); energyPlot.setDoLegend(false); DisplayPlot springPlot = new DisplayPlot(); springPlot.setLabel("spring"); springPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); springHist.addDataSink(springPlot.getDataSet().makeDataSink()); simGraphic.add(springPlot); springPlot.setDoLegend(false); MeterTemperature meterT = new MeterTemperature(sim.box, 3); AccumulatorHistory tHist = new AccumulatorHistory(new HistoryCollapsingAverage()); tHist.setTimeDataSource(tSource); DataPumpListener tPump = new DataPumpListener(meterT, tHist, interval); sim.integrator.getEventManager().addListener(tPump); DisplayPlot tPlot = new DisplayPlot(); tPlot.setLabel("T"); tPlot.setUnit(Kelvin.UNIT); simGraphic.add(tPlot); tHist.addDataSink(tPlot.getDataSet().makeDataSink()); tPlot.setDoLegend(false); MeterKineticEnergy meterKE = new MeterKineticEnergy(); meterKE.setBox(sim.box); AccumulatorHistory keHist = new AccumulatorHistory(new HistoryCollapsingAverage()); keHist.setTimeDataSource(tSource); DataPumpListener kePump = new DataPumpListener(meterKE, keHist, interval); sim.integrator.getEventManager().addListener(kePump); DisplayPlot kePlot = new DisplayPlot(); kePlot.setLabel("KE"); kePlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION, 1.0 / numAtoms, "why do you want a name. just use it.", "per atom", false)}, new double[]{-1})); simGraphic.add(kePlot); keHist.addDataSink(kePlot.getDataSet().makeDataSink()); kePlot.setDoLegend(false); MeterPotentialEnergy meterPE = new MeterPotentialEnergy(sim.potentialMaster); meterPE.setBox(sim.box); meterPE.setPotentialCalculation(new DataSourceEnergies.PotentialCalculationEnergiesEAM(sim.potential)); MeterEnergy meterE = new MeterEnergy(sim.potentialMaster, sim.box); meterE.setPotential(meterPE); AccumulatorHistory eHist = new AccumulatorHistory(new HistoryScrolling(1000)); eHist.setTimeDataSource(tSource); DataPumpListener ePump = new DataPumpListener(meterE, eHist, interval); sim.integrator.getEventManager().addListener(ePump); DisplayPlot tePlot = new DisplayPlot(); tePlot.setLabel("total E"); tePlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION, 1.0 / numAtoms, "why do you want a name. just use it.", "per atom", false)}, new double[]{-1})); simGraphic.add(tePlot); eHist.addDataSink(tePlot.getDataSet().makeDataSink()); tePlot.setDoLegend(false); AccumulatorHistory dudwHist = new AccumulatorHistory(new HistoryCollapsingAverage()); splitter.setDataSink(2, dudwHist); dudwHist.setTimeDataSource(tSource); DisplayPlot dudwPlot = new DisplayPlot(); dudwHist.addDataSink(dudwPlot.getDataSet().makeDataSink()); dudwPlot.setLabel("dudw"); dudwPlot.setUnit(new CompoundUnit(new Unit[]{new SimpleUnit(Null.DIMENSION,1.0/numAtoms,"why do you want a name. just use it.","per atom", false)},new double[]{-1})); simGraphic.add(dudwPlot); AccumulatorAverageFixed avgSfac = new AccumulatorAverageFixed(1); avgSfac.setPushInterval(1); DataPumpListener pumpSfac = new DataPumpListener(meterSfac, avgSfac, 100 * interval); sim.integrator.getEventManager().addListener(pumpSfac); DisplayPlot plotSfac = new DisplayPlot(); avgSfac.addDataSink(plotSfac.getDataSet().makeDataSink(), new AccumulatorAverage.StatType[]{AccumulatorAverage.AVERAGE}); plotSfac.setLabel("Structure Factor"); plotSfac.setDoDrawLines(new DataTag[]{meterSfac.getTag()},false); plotSfac.getPlot().setYLog(true); simGraphic.add(plotSfac); simGraphic.makeAndDisplayFrame(APP_NAME); return; } MeterRMSD meterRMSD = new MeterRMSD(sim.box, sim.space); sim.integrator.setThermostatInterval(10); sim.ai.setMaxSteps(steps/10); sim.getController().actionPerformed(); sim.getController().reset(); sim.integrator.resetStepCount(); sim.integrator.setThermostatInterval(thermostatInterval); sim.ai.setMaxSteps(steps); if (nve) { sim.integrator.setIsothermal(false); } System.out.println("equilibration finished (" + steps / 10 + " steps)"); long t1 = System.currentTimeMillis(); if (thermostatInterval > interval * 10) interval = 20; int numBlocks = 100; if (steps / numBlocks < thermostatInterval) numBlocks = (int) (steps / thermostatInterval); long blockSize = steps / numBlocks / interval; if (blockSize==0) blockSize = 1; System.out.println("numBlocks: " + numBlocks); AccumulatorAverageCovariance accEnergies = new AccumulatorAverageCovariance(blockSize); DataPumpListener pumpEnergies = new DataPumpListener(dsEnergies, accEnergies, interval); sim.integrator.getEventManager().addListener(pumpEnergies); if (rmsdFile != null) { DataLogger dataLogger = new DataLogger(); DataPumpListener pumpRMSD = new DataPumpListener(meterRMSD, dataLogger, 5 * interval); sim.integrator.getEventManager().addListener(pumpRMSD); dataLogger.setFileName(rmsdFile); DataArrayWriter writer = new DataArrayWriter(); writer.setIncludeHeader(false); dataLogger.setDataSink(writer); dataLogger.setAppending(false); sim.getController().getEventManager().addListener(dataLogger); } sim.getController().actionPerformed(); if (swap) System.out.println("swap acceptance: " + sim.mcMoveSwap.getTracker().acceptanceProbability()); IData avgEnergies = accEnergies.getData(AccumulatorAverage.AVERAGE); IData errEnergies = accEnergies.getData(AccumulatorAverage.ERROR); IData corEnergies = accEnergies.getData(AccumulatorAverage.BLOCK_CORRELATION); IData covEnergies = accEnergies.getData(AccumulatorAverageCovariance.BLOCK_COVARIANCE); System.out.println("spring energy: "+avgEnergies.getValue(0)/numAtoms+" error: "+errEnergies.getValue(0)/numAtoms+" cor: "+corEnergies.getValue(0)); System.out.println("Fe energy: "+avgEnergies.getValue(1)/numAtoms+" error: "+errEnergies.getValue(1)/numAtoms+" cor: "+corEnergies.getValue(1)); System.out.println("du/dw: "+avgEnergies.getValue(2)/numAtoms+" error: "+errEnergies.getValue(2)/numAtoms+" cor: "+corEnergies.getValue(2)); double var0 = covEnergies.getValue(0*3+0); double var1 = covEnergies.getValue(1*3+1); double var2 = covEnergies.getValue(2*3+2); double cor01 = 0; if (var0*var1>0) cor01 = covEnergies.getValue(0*3+1)/Math.sqrt(covEnergies.getValue(0*3+0)*covEnergies.getValue(1*3+1)); double cor02 = 0; if (var0*var2>0) cor02 = covEnergies.getValue(0*3+2)/Math.sqrt(covEnergies.getValue(0*3+0)*covEnergies.getValue(2*3+2)); System.out.println("spring correlation: 1 "+cor01+" "+cor02); double cor12 = covEnergies.getValue(1*3+2)/Math.sqrt(covEnergies.getValue(1*3+1)*covEnergies.getValue(2*3+2)); System.out.println("Fe correlation: "+cor01+" 1 "+cor12); System.out.println("du/dw correlation: "+cor02+" "+cor12+" 1"); long t2 = System.currentTimeMillis(); System.out.println("time: "+(t2-t1)/1000.0+" seconds"); } enum Crystal {FCC, BCC, HCP} public static class LjMC3DParams extends ParameterBase { public int numAtoms = 500; public double T = 2.0; public double density = 0.3; public long steps = 100000; public boolean graphics = false; public double w = 1; public int offsetDim = 0; public int numInnerSteps = 10; public Crystal crystal = Crystal.FCC; public boolean swap = true; public boolean nve = false; public int thermostatInterval = 10; public boolean doHarmonic = true; public String rmsdFile = null; public double timeStep = 0.001; } }
package sfBugs; import edu.umd.cs.findbugs.annotations.DesireNoWarning; public class Bug3062023 { private enum E { A, B, C, D } @DesireNoWarning("DB_DUPLICATE_SWITCH_CLAUSES") private void noWarning(E e) { switch (e) { case A: something(1); break; case B: //Nothing to report break; case C: something(2); break; case D: break; default: something(10); break; } } private void something(int i) { } }
package org.intermine.web.config; import java.util.Iterator; import java.util.Set; import java.util.Collections; import org.apache.commons.collections.set.ListOrderedSet; /** * Configuration object for displaying a class * * @author Andrew Varley */ public class Type { // if fieldName is null it's ignored and the webapp will use the default renderer private String fieldName; private String className; private ListOrderedSet fieldConfigs = new ListOrderedSet(); private ListOrderedSet longDisplayers = new ListOrderedSet(); /** * Set the fully-qualified class name for this Type * * @param className the name of the Type */ public void setClassName(String className) { this.className = className; } /** * Get the class name * * @return the name */ public String getClassName() { return this.className; } /** * Add a FieldConfig for this Type * * @param df the FieldConfig to add */ public void addFieldConfig(FieldConfig df) { fieldConfigs.add(df); } /** * Get the List of FieldConfig objects * * @return the List of FieldConfig objects */ public Set getFieldConfigs() { return Collections.unmodifiableSet(this.fieldConfigs); } /** * Add a long displayer for this Type * * @param disp the Displayer to add */ public void addLongDisplayer(Displayer disp) { longDisplayers.add(disp); } /** * Get the List of long Displayers * * @return the List of long Displayers */ public Set getLongDisplayers() { return Collections.unmodifiableSet(this.longDisplayers); } /** * @see Object#equals * * @param obj the Object to compare with * @return true if this is equal to obj */ public boolean equals(Object obj) { if (!(obj instanceof Type)) { return false; } Type typeObj = (Type) obj; return fieldConfigs.equals(typeObj.fieldConfigs) && longDisplayers.equals(typeObj.longDisplayers); } /** * @see Object#hashCode * * @return the hashCode for this Type object */ public int hashCode() { return fieldConfigs.hashCode() + 3 * longDisplayers.hashCode(); } /** * Return an XML String of this Type object * * @return a String version of this WebConfig object */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("<class className=\"" + className + "\""); if (fieldName != null) { sb.append(" fieldName=\"" + fieldName + "\""); } sb.append(">"); sb.append("<fieldconfigs>"); Iterator iter = fieldConfigs.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</fieldconfigs>"); sb.append("<longdisplayers>"); iter = longDisplayers.iterator(); while (iter.hasNext()) { sb.append(iter.next().toString()); } sb.append("</longdisplayers>"); sb.append("</class>"); return sb.toString(); } }
package cinetudoproject.model.domain; public class Assento { private String fila; private int numero; private int ocupado; public Assento(String fila, int numero) { this.fila = fila; this.numero = numero; this.ocupado = 0; } public Assento() { } public String getFila() { return fila; } public void setFila(String fila) { this.fila = fila; } public int getNumero() { return numero; } public void setNumero(int numero) { if(numero > 0) this.numero = numero; } public int getOcupado() { return ocupado; } public void setOcupado(int ocupado) { this.ocupado = ocupado; } }
package edu.umd.cs.daveho.ba; import java.util.*; // We require BCEL 5.0 or later. import org.apache.bcel.*; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; public class BetterCFGBuilder implements CFGBuilder, EdgeTypes { private static final boolean DEBUG = Boolean.getBoolean("cfgbuilder.debug"); private static class WorkListItem { public final InstructionHandle start; public final BasicBlock basicBlock; public final LinkedList<InstructionHandle> jsrStack; public boolean handledPEI; public WorkListItem(InstructionHandle start, BasicBlock basicBlock, LinkedList<InstructionHandle> jsrStack, boolean handledPEI) { this.start = start; this.basicBlock = basicBlock; this.jsrStack = jsrStack; this.handledPEI = handledPEI; } } // Reasons for why a basic block was ended. private static final int BRANCH = 0; private static final int MERGE = 1; private static final int NEXT_IS_PEI = 2; private MethodGen methodGen; private ConstantPoolGen cpg; private CFG cfg; private LinkedList<WorkListItem> workList; private IdentityHashMap<InstructionHandle, BasicBlock> basicBlockMap; private IdentityHashMap<InstructionHandle, BasicBlock> allHandlesToBasicBlockMap; private ExceptionHandlerMap exceptionHandlerMap; public BetterCFGBuilder(MethodGen methodGen) { this.methodGen = methodGen; this.cpg = methodGen.getConstantPool(); this.cfg = new CFG(); this.workList = new LinkedList<WorkListItem>(); this.basicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.allHandlesToBasicBlockMap = new IdentityHashMap<InstructionHandle, BasicBlock>(); this.exceptionHandlerMap = new ExceptionHandlerMap(methodGen); } public void setMode(int mode) { } public void build() { getBlock(methodGen.getInstructionList().getStart(), new LinkedList<InstructionHandle>()); workListLoop: while (!workList.isEmpty()) { WorkListItem item = workList.removeFirst(); InstructionHandle start = item.start; BasicBlock basicBlock = item.basicBlock; LinkedList<InstructionHandle> jsrStack = item.jsrStack; boolean handledPEI = item.handledPEI; if (DEBUG) System.out.println("START BLOCK " + basicBlock.getId()); // If the start instruction is a PEI which we haven't handled yet, then // this block is an Exception Thrower Block (ETB). if (isPEI(start) && !handledPEI) { // This block is an ETB. basicBlock.setExceptionThrower(true); // Add handled exception edges. addExceptionEdges(start, basicBlock, jsrStack); // Add fall through edge. Note that we add the work list item for the // new block by hand, because getBlock() // (1) sets handledPEI to false, and // (2) maps the start instruction to the new block; the ETB is // the correct block for the start instruction, not the // fall through block BasicBlock nextBasicBlock = cfg.allocate(); addEdge(basicBlock, nextBasicBlock, FALL_THROUGH_EDGE); WorkListItem nextItem = new WorkListItem(start, nextBasicBlock, jsrStack, true); workList.add(nextItem); continue workListLoop; } InstructionHandle handle = start; InstructionHandle next = null; TargetEnumeratingVisitor visitor = null; int endBlockMode; // Add instructions to the basic block scanInstructionsLoop: while (true) { // Add the instruction to the block basicBlock.addInstruction(handle); if (DEBUG) System.out.println("** Add " + handle + (isPEI(handle) ? " [PEI]" : "")); // Except for instructions in JSR subroutines, no instruction should be // in more than one basic block. if (allHandlesToBasicBlockMap.get(handle) != null && jsrStack.isEmpty()) throw new IllegalStateException("Instruction in multiple blocks: " + handle); allHandlesToBasicBlockMap.put(handle, basicBlock); // PEIs should always be the first instruction in the basic block if (isPEI(handle) && handle != basicBlock.getFirstInstruction()) throw new IllegalStateException("PEI is not first instruction in block!"); // This will be assigned if the potential next instruction in the // basic block is something other than what would be returned // by handle.getNext(). This only happens for JSR and RET instructions. next = null; Instruction ins = handle.getInstruction(); // Handle JSR, RET, and explicit branches. if (ins instanceof JsrInstruction) { // Remember where we came from jsrStack.addLast(handle); // Transfer control to the subroutine JsrInstruction jsr = (JsrInstruction) ins; next = jsr.getTarget(); } else if (ins instanceof RET) { // Return control to instruction after JSR next = jsrStack.removeLast().getNext(); } else if ((visitor = new TargetEnumeratingVisitor(handle, cpg)).isEndOfBasicBlock()) { // Basic block ends with explicit branch. endBlockMode = BRANCH; break scanInstructionsLoop; } // If control gets here, then the current instruction was not cause // for ending the basic block. Check the next instruction, which may // be cause for ending the block. if (next == null) next = handle.getNext(); if (next == null) throw new IllegalStateException("Falling off end of method: " + handle); // Control merge? if (isMerge(next)) { endBlockMode = MERGE; break scanInstructionsLoop; } // Next instruction is a PEI? if (isPEI(next)) { endBlockMode = NEXT_IS_PEI; break scanInstructionsLoop; } // The basic block definitely continues to the next instruction. handle = next; } if (DEBUG) dumpBlock(basicBlock); // Depending on how the basic block ended, add appropriate edges to the CFG. if (next != null) { // There is a successor instruction, meaning that this // is a control merge, or the block was ended because of a PEI. // In either case, just fall through to the successor. if (endBlockMode != MERGE && endBlockMode != NEXT_IS_PEI) throw new IllegalStateException("next != null, but not merge or PEI"); BasicBlock nextBlock = getBlock(next, jsrStack); addEdge(basicBlock, nextBlock, FALL_THROUGH_EDGE); } else { // There is no successor instruction, meaning that the block ended // in an explicit branch of some sort. if (endBlockMode != BRANCH) throw new IllegalStateException("next == null, but not branch"); if (visitor.instructionIsThrow()) { // Explicit ATHROW instruction. Add exception edges, // and mark the block as an ETB. addExceptionEdges(handle, basicBlock, jsrStack); basicBlock.setExceptionThrower(true); } else if (visitor.instructionIsReturn() || visitor.instructionIsExit()) { // Return or call to System.exit(). In either case, // add a return edge. addEdge(basicBlock, cfg.getExit(), RETURN_EDGE); } else { // The TargetEnumeratingVisitor takes care of telling us what the targets are. // (This includes the fall through edges for IF branches.) Iterator<Target> i = visitor.targetIterator(); while (i.hasNext()) { Target target = i.next(); BasicBlock targetBlock = getBlock(target.getTargetInstruction(), jsrStack); addEdge(basicBlock, targetBlock, target.getEdgeType()); } } } } } public CFG getCFG() { return cfg; } private boolean isPEI(InstructionHandle handle) { Instruction ins = handle.getInstruction(); //return (ins instanceof ExceptionThrower) && !(ins instanceof ATHROW); if (!(ins instanceof ExceptionThrower)) return false; if (ins instanceof ATHROW) return false; if (ins instanceof ReturnInstruction && !methodGen.isSynchronized()) return false; return true; } private BasicBlock getBlock(InstructionHandle start, LinkedList<InstructionHandle> jsrStack) { BasicBlock basicBlock = basicBlockMap.get(start); if (basicBlock == null) { basicBlock = cfg.allocate(); basicBlockMap.put(start, basicBlock); WorkListItem item = new WorkListItem(start, basicBlock, cloneJsrStack(jsrStack), false); workList.add(item); } return basicBlock; } private void addExceptionEdges(InstructionHandle handle, BasicBlock sourceBlock, LinkedList<InstructionHandle> jsrStack) { List<CodeExceptionGen> exceptionHandlerList = exceptionHandlerMap.getHandlerList(handle); if (exceptionHandlerList == null) return; Iterator<CodeExceptionGen> i = exceptionHandlerList.iterator(); while (i.hasNext()) { CodeExceptionGen exceptionHandler = i.next(); BasicBlock handlerBlock = getBlock(exceptionHandler.getHandlerPC(), jsrStack); addEdge(sourceBlock, handlerBlock, HANDLED_EXCEPTION_EDGE); } } private LinkedList<InstructionHandle> cloneJsrStack(LinkedList<InstructionHandle> jsrStack) { LinkedList<InstructionHandle> dup = new LinkedList<InstructionHandle>(); dup.addAll(jsrStack); return dup; } private boolean isMerge(InstructionHandle handle) { if (handle.hasTargeters()) { // Check all targeters of this handle to see if any // of them are branches. Note that we don't consider JSR // instructions to be branches, since we inline JSR subroutines. InstructionTargeter[] targeterList = handle.getTargeters(); for (int i = 0; i < targeterList.length; ++i) { InstructionTargeter targeter = targeterList[i]; if (targeter instanceof BranchInstruction && !(targeter instanceof JsrInstruction)) { return true; } } } return false; } private void addEdge(BasicBlock sourceBlock, BasicBlock destBlock, int edgeType) { if (DEBUG) System.out.println("Add edge: " + sourceBlock.getId() + " -> " + destBlock.getId() + ": " + Edge.edgeTypeToString(edgeType)); cfg.addEdge(sourceBlock, destBlock, edgeType); } private void dumpBlock(BasicBlock basicBlock) { System.out.println("BLOCK " + basicBlock.getId()); Iterator<InstructionHandle> i = basicBlock.instructionIterator(); while (i.hasNext()) { InstructionHandle handle = i.next(); System.out.println(handle.toString()); } System.out.println("END"); } } // vim:ts=4
package edu.umd.cs.findbugs.graph; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; public abstract class AbstractGraph < EdgeType extends AbstractEdge<EdgeType, VertexType>, VertexType extends AbstractVertex<EdgeType, VertexType> > implements Graph<EdgeType, VertexType> { /** * Iterator over outgoing edges. */ private static class OutgoingEdgeIterator < EdgeType extends AbstractEdge<EdgeType, VertexType>, VertexType extends AbstractVertex<EdgeType, VertexType> > implements Iterator<EdgeType> { private EdgeType edge; public OutgoingEdgeIterator(VertexType source) { this.edge = source.getFirstOutgoingEdge(); } public boolean hasNext() { return edge != null; } public EdgeType next() { if (!hasNext()) throw new NoSuchElementException(); EdgeType result = edge; edge = edge.getNextOutgoingEdge(); return result; } public void remove() { throw new UnsupportedOperationException(); } } /** * Iterator over incoming edges. */ private static class IncomingEdgeIterator < EdgeType extends AbstractEdge<EdgeType, VertexType>, VertexType extends AbstractVertex<EdgeType, VertexType> > implements Iterator<EdgeType> { private EdgeType edge; public IncomingEdgeIterator(VertexType target) { this.edge = target.getFirstIncomingEdge(); } public boolean hasNext() { return edge != null; } public EdgeType next() { if (!hasNext()) throw new NoSuchElementException(); EdgeType result = edge; edge = edge.getNextIncomingEdge(); return result; } public void remove() { throw new UnsupportedOperationException(); } } private ArrayList<VertexType> vertexList; private ArrayList<EdgeType> edgeList; private int maxVertexLabel; private int nextVertexId; private int maxEdgeLabel; public AbstractGraph() { this.vertexList = new ArrayList<VertexType>(); this.edgeList = new ArrayList<EdgeType>(); this.maxVertexLabel = 0; this.nextVertexId = 0; this.maxEdgeLabel = 0; } public int getNumEdges() { return edgeList.size(); } public int getNumVertices() { return vertexList.size(); } public Iterator<EdgeType> edgeIterator() { return edgeList.iterator(); } public Iterator<VertexType> vertexIterator() { return vertexList.iterator(); } public void addVertex(VertexType v) { vertexList.add(v); v.setId(nextVertexId++); v.setLabel(maxVertexLabel++); } public boolean containsVertex(VertexType v) { Iterator<VertexType> i = vertexList.iterator(); while (i.hasNext()) { VertexType existingVertex = i.next(); if (v == existingVertex) return true; } return false; } public EdgeType createEdge(VertexType source, VertexType target) { EdgeType edge = allocateEdge(source, target); edgeList.add(edge); source.addOutgoingEdge(edge); target.addIncomingEdge(edge); edge.setLabel(maxEdgeLabel++); return edge; } public EdgeType lookupEdge(VertexType source, VertexType target) { Iterator<EdgeType> i = outgoingEdgeIterator(source); while (i.hasNext()) { EdgeType edge = i.next(); if (edge.getTarget() == target) return edge; } return null; } public int getNumVertexLabels() { return maxVertexLabel; } public void setNumVertexLabels(int numLabels) { this.maxVertexLabel = numLabels; } public int getNumEdgeLabels() { return maxEdgeLabel; } public void setNumEdgeLabels(int numLabels) { maxEdgeLabel = numLabels; } public void removeEdge(EdgeType edge) { if (!edgeList.remove(edge)) throw new IllegalArgumentException("removing nonexistent edge!"); edge.getSource().removeOutgoingEdge(edge); edge.getTarget().removeIncomingEdge(edge); } public void removeVertex(VertexType v) { if (!vertexList.remove(v)) throw new IllegalArgumentException("removing nonexistent vertex!"); for (Iterator<EdgeType> i = incomingEdgeIterator(v); i.hasNext(); ) removeEdge(i.next()); for (Iterator<EdgeType> i = outgoingEdgeIterator(v); i.hasNext(); ) removeEdge(i.next()); } public Iterator<EdgeType> outgoingEdgeIterator(VertexType source) { return new OutgoingEdgeIterator<EdgeType, VertexType>(source); } public Iterator<EdgeType> incomingEdgeIterator(VertexType target) { return new IncomingEdgeIterator<EdgeType, VertexType>(target); } public Iterator<VertexType> successorIterator(final VertexType source) { return new Iterator<VertexType>() { private Iterator<EdgeType> iter = outgoingEdgeIterator(source); public boolean hasNext() { return iter.hasNext(); } public VertexType next() { return iter.next().getTarget(); } public void remove() { iter.remove(); } }; } public Iterator<VertexType> predecessorIterator(final VertexType target) { return new Iterator<VertexType>() { private Iterator<EdgeType> iter = incomingEdgeIterator(target); public boolean hasNext() { return iter.hasNext(); } public VertexType next() { return iter.next().getSource(); } public void remove() { iter.remove(); } }; } protected abstract EdgeType allocateEdge(VertexType source, VertexType target); } // vim:ts=4