lang
stringclasses
1 value
license
stringclasses
13 values
stderr
stringlengths
0
350
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
7
45.1k
new_contents
stringlengths
0
1.87M
new_file
stringlengths
6
292
old_contents
stringlengths
0
1.87M
message
stringlengths
6
9.26k
old_file
stringlengths
6
292
subject
stringlengths
0
4.45k
Java
mit
c0540f1147809bf6b20ffeb5d0a8b567c4074110
0
OpenAMEE/amee.platform.api
package com.amee.platform.resource.itemvaluedefinition.v_3_1; import com.amee.base.domain.Since; import com.amee.base.resource.RequestWrapper; import com.amee.base.resource.ResponseHelper; import com.amee.base.validation.ValidationException; import com.amee.domain.data.ItemValueDefinition; import com.amee.platform.resource.itemvaluedefinition.ItemValueDefinitionValidationHelper; import org.jdom.Document; import org.jdom.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.Map; @Service @Scope("prototype") @Since("3.1.0") public class ItemValueDefinitionDOMAcceptor extends com.amee.platform.resource.itemvaluedefinition.ItemValueDefinitionDOMAcceptor { @Autowired private ItemValueDefinitionValidationHelper validationHelper; protected Object handle(RequestWrapper requestWrapper, ItemValueDefinition itemValueDefinition) { Document document = requestWrapper.getBodyAsDocument(); Element rootElem = document.getRootElement(); if (rootElem.getName().equals("ItemValueDefinition")) { Map<String, String> parameters = new HashMap<String, String>(); for (Object o : rootElem.getChildren()) { Element childElem = (Element) o; if (childElem.getChildren().isEmpty()) { parameters.put(StringUtils.uncapitalize(childElem.getName()), childElem.getText()); } } validationHelper.setItemValueDefinition(itemValueDefinition); if (validationHelper.isValid(parameters)) { return ResponseHelper.getOK(requestWrapper); } else { throw new ValidationException(validationHelper.getValidationResult()); } } else { throw new ValidationException(); } } }
src/main/java/com/amee/platform/resource/itemvaluedefinition/v_3_1/ItemValueDefinitionDOMAcceptor.java
package com.amee.platform.resource.itemvaluedefinition.v_3_1; import com.amee.base.domain.Since; import com.amee.base.resource.RequestWrapper; import com.amee.base.resource.ResponseHelper; import com.amee.base.validation.ValidationException; import com.amee.domain.data.ItemValueDefinition; import com.amee.platform.resource.itemvaluedefinition.ItemValueDefinitionValidationHelper; import org.jdom.Document; import org.jdom.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service @Scope("prototype") @Since("3.1.0") public class ItemValueDefinitionDOMAcceptor extends com.amee.platform.resource.itemvaluedefinition.ItemValueDefinitionDOMAcceptor { @Autowired private ItemValueDefinitionValidationHelper validationHelper; protected Object handle(RequestWrapper requestWrapper, ItemValueDefinition itemValueDefinition) { Document document = requestWrapper.getBodyAsDocument(); Element rootElem = document.getRootElement(); Map<String, String> parameters = new HashMap<String, String>(); for (Object o : rootElem.getChildren()) { Element childElem = (Element) o; if (childElem.getChildren().isEmpty()) { parameters.put(childElem.getName(), childElem.getText()); } } validationHelper.setItemValueDefinition(itemValueDefinition); if (validationHelper.isValid(parameters)) { return ResponseHelper.getOK(requestWrapper); } else { throw new ValidationException(validationHelper.getValidationResult()); } } }
PL-2962 - ItemValueDefinitionDOMAcceptor handles XML.
src/main/java/com/amee/platform/resource/itemvaluedefinition/v_3_1/ItemValueDefinitionDOMAcceptor.java
PL-2962 - ItemValueDefinitionDOMAcceptor handles XML.
Java
mit
dc8cdbfd0947ecb55ba9f464b712cff7ba1d243f
0
synchrotron-soleil-ica/continuous-materials,synchrotron-soleil-ica/continuous-materials,synchrotron-soleil-ica/continuous-materials
package fr.synchrotron.soleil.ica.ci.service.multirepoproxy; import io.netty.handler.codec.http.HttpResponseStatus; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpClientRequest; import org.vertx.java.core.http.HttpClientResponse; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.streams.Pump; import java.util.List; /** * @author Gregory Boissinot */ public class ProxyRequestHandler implements Handler<HttpServerRequest> { private final Vertx vertx; private final RepositoryScanner repositoryScanner; public ProxyRequestHandler(Vertx vertx, List<RepositoryObject> repos) { this.vertx = vertx; if (repos == null || repos.size() == 0) { throw new IllegalArgumentException("repos"); } this.repositoryScanner = new RepositoryScanner(repos); } @Override public void handle(final HttpServerRequest request) { processRepo(request, 0); } private void processRepo(final HttpServerRequest request, final int repoIndex) { final RepositoryObject repositoryInfo = repositoryScanner.getRepoFromIndex(repoIndex); final HttpClient vertxHttpClient = vertx.createHttpClient(); vertxHttpClient.setHost(repositoryInfo.getHost()).setPort(repositoryInfo.getPort()); final String repoURIPath = repositoryInfo.getUri(); HttpClientRequest vertxRequest = vertxHttpClient.get(buildRequestPath(request, repoURIPath), new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse clientResponse) { if (HttpResponseStatus.NOT_FOUND.code() == clientResponse.statusCode() || HttpResponseStatus.MOVED_PERMANENTLY.code() == clientResponse.statusCode()) { if (repositoryScanner.isLastRepo(repoIndex)) { request.response().setStatusCode(clientResponse.statusCode()); request.response().setStatusMessage("Artifact NOT FOUND"); request.response().end(); } else { processRepo(request, repositoryScanner.getNextIndex(repoIndex)); } } else if (HttpResponseStatus.OK.code() == clientResponse.statusCode()) { makeGetRepoRequest(request, vertxHttpClient, repoURIPath); } else { request.response().setStatusCode(clientResponse.statusCode()); request.response().setStatusMessage(clientResponse.statusMessage()); request.response().end(); } } }); vertxRequest.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable e) { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Exception from ").append(repositoryInfo); errorMsg.append("-->").append(e.toString()); errorMsg.append("\n"); request.response().end(errorMsg.toString()); } }); vertxRequest.end(); } private String buildRequestPath(final HttpServerRequest request, String repoURIPath) { final String prefix = RepoProxyHttpEndpointVerticle.PROXY_PATH; String artifactPath = request.path().substring(prefix.length() + 1); return repoURIPath.endsWith("/") ? (repoURIPath + artifactPath) : (repoURIPath + "/" + artifactPath); } private void makeGetRepoRequest(final HttpServerRequest request, final HttpClient vertxHttpClient, final String repoUri) { HttpClientRequest vertxRequest = vertxHttpClient.get(buildRequestPath(request, repoUri), new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse clientResponse) { final int statusCode = clientResponse.statusCode(); request.response().setStatusCode(statusCode); request.response().setStatusMessage(clientResponse.statusMessage()); request.response().headers().set(clientResponse.headers()); clientResponse.endHandler(new Handler<Void>() { public void handle(Void event) { request.response().end(); } }); if (statusCode == HttpResponseStatus.NOT_MODIFIED.code() || statusCode == HttpResponseStatus.OK.code()) { //Send result to original client Pump.createPump(clientResponse, request.response().setChunked(true)).start(); } } }); vertxRequest.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable e) { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Exception from ").append(repoUri); errorMsg.append("-->").append(e.toString()); errorMsg.append("\n"); request.response().end(errorMsg.toString()); } }); vertxRequest.end(); } }
Services/ServiceMultiRepoProxy/src/main/java/fr/synchrotron/soleil/ica/ci/service/multirepoproxy/ProxyRequestHandler.java
package fr.synchrotron.soleil.ica.ci.service.multirepoproxy; import io.netty.handler.codec.http.HttpResponseStatus; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpClient; import org.vertx.java.core.http.HttpClientRequest; import org.vertx.java.core.http.HttpClientResponse; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.streams.Pump; import java.util.List; /** * @author Gregory Boissinot */ public class ProxyRequestHandler implements Handler<HttpServerRequest> { private final Vertx vertx; private final RepositoryScanner repositoryScanner; public ProxyRequestHandler(Vertx vertx, List<RepositoryObject> repos) { this.vertx = vertx; if (repos == null || repos.size() == 0) { throw new IllegalArgumentException("repos"); } this.repositoryScanner = new RepositoryScanner(repos); } @Override public void handle(final HttpServerRequest request) { processRepo(request, 0); } private void processRepo(final HttpServerRequest request, final int repoIndex) { final RepositoryObject repositoryInfo = repositoryScanner.getRepoFromIndex(repoIndex); final HttpClient vertxHttpClient = vertx.createHttpClient(); vertxHttpClient.setHost(repositoryInfo.getHost()).setPort(repositoryInfo.getPort()); final String repoURIPath = repositoryInfo.getUri(); HttpClientRequest vertxRequest = vertxHttpClient.get(buildRequestPath(request, repoURIPath), new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse clientResponse) { clientResponse.endHandler(new Handler<Void>() { public void handle(Void event) { //request.response().end(); } }); if (HttpResponseStatus.NOT_FOUND.code() == clientResponse.statusCode()) { if (repositoryScanner.isLastRepo(repoIndex)) { request.response().setStatusCode(clientResponse.statusCode()); request.response().setStatusMessage("Artifact NOT FOUND"); request.response().end(); } else { processRepo(request, repositoryScanner.getNextIndex(repoIndex)); } } else if (HttpResponseStatus.OK.code() == clientResponse.statusCode()) { makeGetRepoRequest(request, vertxHttpClient, repoURIPath); } else { request.response().setStatusCode(clientResponse.statusCode()); request.response().setStatusMessage(clientResponse.statusMessage()); request.response().end(); } } }); vertxRequest.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable e) { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Exception from ").append(repositoryInfo); errorMsg.append("-->").append(e.toString()); errorMsg.append("\n"); request.response().end(errorMsg.toString()); } }); vertxRequest.end(); } private String buildRequestPath(final HttpServerRequest request, String repoURIPath) { final String prefix = RepoProxyHttpEndpointVerticle.PROXY_PATH; String artifactPath = request.path().substring(prefix.length() + 1); return repoURIPath.endsWith("/") ? (repoURIPath + artifactPath) : (repoURIPath + "/" + artifactPath); } private void makeGetRepoRequest(final HttpServerRequest request, final HttpClient vertxHttpClient, final String repoUri) { HttpClientRequest vertxRequest = vertxHttpClient.get(buildRequestPath(request, repoUri), new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse clientResponse) { final int statusCode = clientResponse.statusCode(); request.response().setStatusCode(statusCode); request.response().setStatusMessage(clientResponse.statusMessage()); request.response().headers().set(clientResponse.headers()); clientResponse.endHandler(new Handler<Void>() { public void handle(Void event) { request.response().end(); } }); if (statusCode == HttpResponseStatus.NOT_MODIFIED.code() || statusCode == HttpResponseStatus.OK.code()) { //Send result to original client Pump.createPump(clientResponse, request.response().setChunked(true)).start(); } } }); vertxRequest.exceptionHandler(new Handler<Throwable>() { @Override public void handle(Throwable e) { request.response().setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); StringBuilder errorMsg = new StringBuilder(); errorMsg.append("Exception from ").append(repoUri); errorMsg.append("-->").append(e.toString()); errorMsg.append("\n"); request.response().end(errorMsg.toString()); } }); vertxRequest.end(); } }
Remove Unused code
Services/ServiceMultiRepoProxy/src/main/java/fr/synchrotron/soleil/ica/ci/service/multirepoproxy/ProxyRequestHandler.java
Remove Unused code
Java
epl-1.0
a384ed0d8a94dc321269f38f0e87845d68260476
0
debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief,debrief/debrief
package org.mwc.debrief.lite.gui.custom.narratives; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; public class NarrativeEntryItemRenderer extends JPanel implements TableCellRenderer { private static final ImageIcon HIGHLIGHT_ICON = Utils.getIcon( "icons/16/highlight.png"); private static final ImageIcon BLANK_ICON = Utils.getIcon( "icons/16/blank.png"); private static final ImageIcon REMOVE_NARRATIVE_ICON = Utils.getIcon( "icons/16/remove_narrative.png"); private static final ImageIcon EDIT_NARRATIVE_ICON = Utils.getIcon( "icons/16/edit_narrative.png"); /** * */ private static final long serialVersionUID = -2227870470228775898L; private int panelWidth; private boolean isWrapping; private JPanel getHeader(final NarrativeEntryItem valueItem, final JLabel time, final Font originalFont) { final JPanel header = new JPanel(new FlowLayout(FlowLayout.LEFT)); header.setPreferredSize(new Dimension(300, 18)); final Font smallFont = new Font(originalFont.getName(), originalFont .getStyle(), 8); time.setFont(smallFont); final JLabel trackName = new JLabel(valueItem.getEntry().getTrackName()); trackName.setFont(smallFont); final JLabel typeName = new JLabel(valueItem.getEntry().getType()); typeName.setFont(smallFont); header.add(Box.createHorizontalStrut(12)); header.add(time); header.add(Box.createHorizontalStrut(3)); header.add(trackName); header.add(Box.createHorizontalStrut(3)); header.add(typeName); return header; } private JLabel getName(final String text, final boolean hasFocus, final Font originalFont, final JTable table) { final JLabel name = new JLabel(); final String html = "<html><body style='width: %1spx'>%1s"; name.setOpaque(false); name.setFocusable(false); if (isWrapping()) { final int emptySpace; if (hasFocus) { emptySpace = 120; } else { emptySpace = 80; } name.setText(String.format(html, panelWidth - emptySpace, text)); } else { name.setText(text); } final Font bigFont = new Font(originalFont.getName(), originalFont .getStyle(), 12); name.setFont(bigFont); final int width = table.getWidth(); if (width > 0) { name.setSize(width, Short.MAX_VALUE); } return name; } public int getPanelWidth() { return panelWidth; } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final Color selectedColor = new Color(229, 229, 229); if (value instanceof NarrativeEntryItem) { final NarrativeEntryItem valueItem = (NarrativeEntryItem) value; final String text = valueItem.getEntry().getEntry(); final JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); final JLabel time = new JLabel(valueItem.getEntry().getDTGString()); final Font originalFont = time.getFont(); // the header bar, with the metadata final JPanel header = getHeader(valueItem, time, originalFont); // the content of the narrative entry final JLabel name = getName(text, hasFocus, originalFont, table); final JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BorderLayout()); innerPanel.add(header, BorderLayout.NORTH); innerPanel.add(name, BorderLayout.CENTER); mainPanel.add(innerPanel, BorderLayout.CENTER); JLabel highlightIcon; if (isSelected) { highlightIcon = new JLabel(HIGHLIGHT_ICON); } else { highlightIcon = new JLabel(BLANK_ICON); } mainPanel.add(highlightIcon, BorderLayout.WEST); if (hasFocus) { mainPanel.setBackground(selectedColor); name.setBackground(selectedColor); header.setBackground(selectedColor); innerPanel.setBackground(selectedColor); final JLabel editNarrative = new JLabel(EDIT_NARRATIVE_ICON); final JLabel removeNarrative = new JLabel(REMOVE_NARRATIVE_ICON); final JPanel iconsPanel = new JPanel(); iconsPanel.setBackground(selectedColor); iconsPanel.add(editNarrative); iconsPanel.add(removeNarrative); mainPanel.add(iconsPanel, BorderLayout.EAST); } return mainPanel; } else { return null; } } public boolean isWrapping() { return isWrapping; } public void setPanelWidth(final int panelWidth) { this.panelWidth = panelWidth; } public void setWrapping(final boolean isWrapping) { this.isWrapping = isWrapping; } }
org.mwc.debrief.lite/src/main/java/org/mwc/debrief/lite/gui/custom/narratives/NarrativeEntryItemRenderer.java
package org.mwc.debrief.lite.gui.custom.narratives; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.TableCellRenderer; public class NarrativeEntryItemRenderer extends JPanel implements TableCellRenderer { private static final ImageIcon HIGHLIGHT_ICON = Utils.getIcon( "icons/16/highlight.png"); private static final ImageIcon BLANK_ICON = Utils.getIcon( "icons/16/blank.png"); private static final ImageIcon REMOVE_NARRATIVE_ICON = Utils.getIcon( "icons/16/remove_narrative.png"); private static final ImageIcon EDIT_NARRATIVE_ICON = Utils.getIcon( "icons/16/edit_narrative.png"); private int panelWidth; private boolean isWrapping; /** * */ private static final long serialVersionUID = -2227870470228775898L; private JPanel getHeader(final NarrativeEntryItem valueItem, final JLabel time, final Font originalFont) { final JPanel header = new JPanel(new FlowLayout(FlowLayout.LEFT)); header.setPreferredSize(new Dimension(300, 18)); final Font smallFont = new Font(originalFont.getName(), originalFont .getStyle(), 8); time.setFont(smallFont); final JLabel trackName = new JLabel(valueItem.getEntry().getTrackName()); trackName.setFont(smallFont); final JLabel typeName = new JLabel(valueItem.getEntry().getType()); typeName.setFont(smallFont); header.add(Box.createHorizontalStrut(12)); header.add(time); header.add(Box.createHorizontalStrut(3)); header.add(trackName); header.add(Box.createHorizontalStrut(3)); header.add(typeName); return header; } @Override public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { final Color selectedColor = new Color(229, 229, 229); if (value instanceof NarrativeEntryItem) { final NarrativeEntryItem valueItem = (NarrativeEntryItem) value; final String text = valueItem.getEntry().getEntry(); final JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); final JLabel time = new JLabel(valueItem.getEntry().getDTGString()); final Font originalFont = time.getFont(); // the header bar, with the metadata final JPanel header = getHeader(valueItem, time, originalFont); // the content of the narrative entry final JLabel name = getName(text, hasFocus, originalFont, table); final JPanel innerPanel = new JPanel(); innerPanel.setLayout(new BorderLayout()); innerPanel.add(header, BorderLayout.NORTH); innerPanel.add(name, BorderLayout.CENTER); mainPanel.add(innerPanel, BorderLayout.CENTER); JLabel highlightIcon; if (isSelected) { highlightIcon = new JLabel(HIGHLIGHT_ICON); } else { highlightIcon = new JLabel(BLANK_ICON); } mainPanel.add(highlightIcon, BorderLayout.WEST); if (hasFocus) { mainPanel.setBackground(selectedColor); name.setBackground(selectedColor); header.setBackground(selectedColor); innerPanel.setBackground(selectedColor); final JLabel editNarrative = new JLabel(EDIT_NARRATIVE_ICON); final JLabel removeNarrative = new JLabel(REMOVE_NARRATIVE_ICON); final JPanel iconsPanel = new JPanel(); iconsPanel.setBackground(selectedColor); iconsPanel.add(editNarrative); iconsPanel.add(removeNarrative); mainPanel.add(iconsPanel, BorderLayout.EAST); } return mainPanel; } else { return null; } } private JLabel getName(String text, boolean hasFocus, final Font originalFont,final JTable table) { final JLabel name = new JLabel(); final String html = "<html><body style='width: %1spx'>%1s"; name.setOpaque(false); name.setFocusable(false); if ( isWrapping() ) { final int emptySpace; if ( hasFocus ) { emptySpace = 120; }else { emptySpace = 80; } name.setText(String.format(html, panelWidth - emptySpace, text)); }else { name.setText(text); } final Font bigFont = new Font(originalFont.getName(), originalFont .getStyle(), 12); name.setFont(bigFont); final int width = table.getWidth(); if (width > 0) { name.setSize(width, Short.MAX_VALUE); } return name; } public int getPanelWidth() { return panelWidth; } public void setPanelWidth(int panelWidth) { this.panelWidth = panelWidth; } public boolean isWrapping() { return isWrapping; } public void setWrapping(boolean isWrapping) { this.isWrapping = isWrapping; } }
apply code cleanup
org.mwc.debrief.lite/src/main/java/org/mwc/debrief/lite/gui/custom/narratives/NarrativeEntryItemRenderer.java
apply code cleanup
Java
agpl-3.0
fc0fe934f4dbe0643b65900f22963f320dcb38e6
0
EaglesoftZJ/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,EaglesoftZJ/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,ufosky-server/actor-platform,actorapp/actor-platform,ufosky-server/actor-platform,dfsilva/actor-platform,ufosky-server/actor-platform,ufosky-server/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform,actorapp/actor-platform,dfsilva/actor-platform,dfsilva/actor-platform,actorapp/actor-platform,actorapp/actor-platform,EaglesoftZJ/actor-platform,actorapp/actor-platform
package im.actor.sdk.controllers.root; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import im.actor.sdk.ActorSDK; import im.actor.sdk.R; import im.actor.sdk.controllers.activity.BaseFragmentActivity; import im.actor.sdk.controllers.tools.InviteHandler; /** * Root Activity of Application */ public class RootActivity extends BaseFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_root); // // Configure Toolbar // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); assert toolbar != null; setSupportActionBar(toolbar); if (ActorSDK.sharedActor().style.getToolBarColor() != 0) { toolbar.setBackgroundDrawable(new ColorDrawable(ActorSDK.sharedActor().style.getToolBarColor())); } if (savedInstanceState == null) { Fragment fragment = ActorSDK.sharedActor().getDelegate().fragmentForRoot(); if (fragment == null) { fragment = new RootFragment(); } getSupportFragmentManager().beginTransaction() .add(R.id.root, fragment) .commit(); } InviteHandler.handleIntent(this, getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); InviteHandler.handleIntent(this, intent); } }
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/root/RootActivity.java
package im.actor.sdk.controllers.root; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.support.v7.widget.Toolbar; import android.widget.Toast; import java.io.UnsupportedEncodingException; import im.actor.core.entity.Peer; import im.actor.core.viewmodel.CommandCallback; import im.actor.core.viewmodel.GroupVM; import im.actor.runtime.HTTP; import im.actor.runtime.android.AndroidContext; import im.actor.runtime.function.Consumer; import im.actor.runtime.http.HTTPResponse; import im.actor.runtime.json.JSONException; import im.actor.runtime.json.JSONObject; import im.actor.sdk.ActorSDK; import im.actor.sdk.R; import im.actor.sdk.controllers.Intents; import im.actor.sdk.controllers.activity.BaseFragmentActivity; import im.actor.sdk.controllers.tools.InviteHandler; import im.actor.sdk.intents.ActorIntent; import im.actor.sdk.intents.ActorIntentActivity; import static im.actor.sdk.util.ActorSDKMessenger.groups; import static im.actor.sdk.util.ActorSDKMessenger.messenger; /** * Root Activity of Application */ public class RootActivity extends BaseFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_root); // // Configure Toolbar // Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); assert toolbar != null; setSupportActionBar(toolbar); if (ActorSDK.sharedActor().style.getToolBarColor() != 0) { toolbar.setBackgroundDrawable(new ColorDrawable(ActorSDK.sharedActor().style.getToolBarColor())); } if (savedInstanceState == null) { Fragment fragment = ActorSDK.sharedActor().getDelegate().fragmentForRoot(); if (fragment == null) { fragment = new RootFragment(); } getSupportFragmentManager().beginTransaction() .add(R.id.root, fragment) .commit(); } InviteHandler.handleIntent(this, getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); InviteHandler.handleIntent(this, intent); } }
refactor(android): removed unused imports from rootActivity left from invite link handler
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/root/RootActivity.java
refactor(android): removed unused imports from rootActivity left from invite link handler
Java
lgpl-2.1
c8b71f1cc9ea2f1437f9054d79f29e2a36f8643c
0
johnscancella/spotbugs,johnscancella/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,johnscancella/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,KengoTODA/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,KengoTODA/spotbugs
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004,2005, Tom Truscott <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.detect; import java.text.NumberFormat; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.visitclass.Constants2; public class TestingGround extends BytecodeScanningDetector implements Constants2, StatelessDetector { private static final boolean active = Boolean.getBoolean("findbugs.tg.active");; private NumberFormat formatter = null; public TestingGround(BugReporter bugReporter) { if (active) { formatter = NumberFormat.getIntegerInstance(); formatter.setMinimumIntegerDigits(4); formatter.setGroupingUsed(false); } } public Object clone() throws CloneNotSupportedException { return super.clone(); } public void visit(JavaClass obj) { } public void visit(Method obj) { } public void visit(Code obj) { // unless active, don't bother dismantling bytecode if (active) { System.out.println("TestingGround: " + getFullyQualifiedMethodName()); super.visit(obj); } } public void sawOpcode(int seen) { printOpCode(seen); } private void printOpCode(int seen) { System.out.print(" TestingGround: [" + formatter.format(getPC()) + "] " + OPCODE_NAMES[seen]); if ((seen == INVOKEVIRTUAL) || (seen == INVOKESPECIAL) || (seen == INVOKEINTERFACE) || (seen == INVOKESTATIC)) System.out.print(" " + getClassConstantOperand() + "." + getNameConstantOperand() + " " + getSigConstantOperand()); else if (seen == LDC || seen == LDC_W || seen == LDC2_W) { Constant c = getConstantRefOperand(); if (c instanceof ConstantString) System.out.print(" \"" + getStringConstantOperand() + "\""); else if (c instanceof ConstantClass) System.out.print(" " + getClassConstantOperand()); else System.out.print(" " + c); } else if ((seen == ALOAD) || (seen == ASTORE)) System.out.print(" " + getRegisterOperand()); else if ((seen == GOTO) || (seen == GOTO_W) || (seen == IF_ACMPEQ) || (seen == IF_ACMPNE) || (seen == IF_ICMPEQ) || (seen == IF_ICMPGE) || (seen == IF_ICMPGT) || (seen == IF_ICMPLE) || (seen == IF_ICMPLT) || (seen == IF_ICMPNE) || (seen == IFEQ) || (seen == IFGE) || (seen == IFGT) || (seen == IFLE) || (seen == IFLT) || (seen == IFNE) || (seen == IFNONNULL) || (seen == IFNULL)) System.out.print(" " + getBranchTarget()); else if ((seen == NEW) || (seen == INSTANCEOF)) System.out.print(" " + getClassConstantOperand()); else if ((seen == TABLESWITCH) || (seen == LOOKUPSWITCH)) { System.out.print(" ["); int switchPC = getPC(); int[] offsets = getSwitchOffsets(); for (int i = 0; i < offsets.length; i++) { System.out.print((switchPC + offsets[i]) + ","); } System.out.print((switchPC + getDefaultSwitchOffset()) + "]"); } System.out.println(); } }
findbugs/src/java/edu/umd/cs/findbugs/detect/TestingGround.java
/* * FindBugs - Find bugs in Java programs * Copyright (C) 2004,2005, Tom Truscott <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.detect; import java.text.NumberFormat; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.Constant; import org.apache.bcel.classfile.ConstantClass; import org.apache.bcel.classfile.ConstantString; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.visitclass.Constants2; public class TestingGround extends BytecodeScanningDetector implements Constants2, StatelessDetector { private static final boolean active = Boolean.getBoolean("findbugs.tg.active");; private NumberFormat formatter = null; public TestingGround(BugReporter bugReporter) { if (active) { formatter = NumberFormat.getIntegerInstance(); formatter.setMinimumIntegerDigits(4); formatter.setGroupingUsed(false); } } public Object clone() throws CloneNotSupportedException { return super.clone(); } public void visit(JavaClass obj) { } public void visit(Method obj) { } public void visit(Code obj) { // unless active, don't bother dismantling bytecode if (active) { System.out.println("TestingGround: " + getFullyQualifiedMethodName()); super.visit(obj); } } public void sawOpcode(int seen) { printOpCode(seen); } private void printOpCode(int seen) { System.out.print(" TestingGround: [" + formatter.format(getPC()) + "] " + OPCODE_NAMES[seen]); if ((seen == INVOKEVIRTUAL) || (seen == INVOKESPECIAL) || (seen == INVOKEINTERFACE) || (seen == INVOKESTATIC)) System.out.print(" " + getClassConstantOperand() + "." + getNameConstantOperand() + " " + getSigConstantOperand()); else if (seen == LDC || seen == LDC_W || seen == LDC2_W) { Constant c = getConstantRefOperand(); if (c instanceof ConstantString) System.out.print(" \"" + getStringConstantOperand() + "\""); else if (c instanceof ConstantClass) System.out.print(" " + getClassConstantOperand()); else System.out.print(" " + c); } else if ((seen == ALOAD) || (seen == ASTORE)) System.out.print(" " + getRegisterOperand()); else if ((seen == GOTO) || (seen == GOTO_W) || (seen == IF_ACMPEQ) || (seen == IF_ACMPNE) || (seen == IF_ICMPEQ) || (seen == IF_ICMPGE) || (seen == IF_ICMPGT) || (seen == IF_ICMPLE) || (seen == IF_ICMPLT) || (seen == IF_ICMPNE) || (seen == IFEQ) || (seen == IFGE) || (seen == IFGT) || (seen == IFLE) || (seen == IFLT) || (seen == IFNE) || (seen == IFNONNULL) || (seen == IFNULL)) System.out.print(" " + getBranchTarget()); else if ((seen == NEW) || (seen == INSTANCEOF)) System.out.print(" " + getClassConstantOperand()); System.out.println(); } }
add switch offsets to testing ground git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@3514 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/detect/TestingGround.java
add switch offsets to testing ground
Java
lgpl-2.1
59dea5dad893f30639dba373276fa3d7225f1d1d
0
jtalks-org/poulpe,standpoint/poulpe,jtalks-org/poulpe,standpoint/poulpe
/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.poulpe.web.controller.group; import org.jtalks.common.model.entity.Group; import org.jtalks.poulpe.service.GroupService; import org.jtalks.poulpe.web.controller.SelectedEntity; import org.jtalks.poulpe.web.controller.WindowManager; import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zul.ListModelList; import javax.annotation.Nonnull; /** * View-model for 'User Groups' Is used to order to work with page that allows admin to manage groups(add, edit, * delete). Also class provides access to Members edit window, presented by {@link EditGroupMembersVm}. * * @author Leonid Kazancev */ public class UserGroupVm { private static final String SHOW_DELETE_DIALOG = "showDeleteDialog", SHOW_EDIT_DIALOG = "showEditDialog", SHOW_NEW_DIALOG = "showNewDialog", SELECTED_GROUP = "selectedGroup"; //Injected private GroupService groupService; private final WindowManager windowManager; private ListModelList<Group> groups; private Group selectedGroup; private SelectedEntity<Group> selectedEntity; private String searchString = ""; private boolean showDeleteDialog; private boolean showEditDialog; private boolean showNewDialog; /** * Construct View-Model for 'User groups' view. * * @param groupService the group service instance * @param selectedEntity the selected entity instance * @param windowManager the window manager instance */ public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity, @Nonnull WindowManager windowManager) { this.groupService = groupService; this.selectedEntity = selectedEntity; this.windowManager = windowManager; this.groups = new ListModelList<Group>(groupService.getAll(), true); } /** * Makes group list view actual. */ public void updateView() { groups.clear(); groups.addAll(groupService.getAll()); } // -- ZK Command bindings -------------------- /** * Look for the users matching specified pattern from the search textbox. */ @Command public void searchGroup() { groups.clear(); groups.addAll(groupService.getAllMatchedByName(searchString)); } /** * Opens edit group members window. */ @Command public void showGroupMemberEditWindow() { selectedEntity.setEntity(selectedGroup); EditGroupMembersVm.showDialog(windowManager); } /** * Deletes selected group. */ @Command @NotifyChange(SELECTED_GROUP) public void deleteGroup() { groupService.deleteGroup(selectedGroup); closeDialog(); updateView(); } /** * Opens group adding dialog. */ @Command @NotifyChange({SELECTED_GROUP, SHOW_NEW_DIALOG}) public void showNewGroupDialog() { selectedGroup = new Group(); showNewDialog = true; } /** * Saves group, closing group edit(add) dialog and updates view. * * @param group editing group */ @Command @NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG}) public void saveGroup(@BindingParam(value = "group") Group group) { groupService.saveGroup(group); closeDialog(); updateView(); } /** * Close all dialogs by set visibility to false. */ @Command @NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG}) public void closeDialog() { showNewDialog = false; showDeleteDialog = false; showEditDialog = false; } // -- Getters/Setters -------------------- /** * Gets visibility status of Delete dialog window. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowDeleteDialog() { return showDeleteDialog; } /** * Gets visibility status of Edit dialog window. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowEditDialog() { return showEditDialog; } /** * Gets visibility status of New group dialog window, boolean show added as fix for onClose action, which don't send * anything to the server when closing window because of event.stopPropagation, so during next change notification * ZK will think that we need to show that dialog again which is wrong. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowNewDialog() { boolean show = showNewDialog; showNewDialog = false; return show; } /** * Gets List of groups which shown at UI. * * @return Groups currently displayed at UI. */ @SuppressWarnings("unused") public ListModelList<Group> getGroups() { return groups; } /** * Gets current selected group. * * @return Group selected at UI. */ @SuppressWarnings("unused") public Group getSelectedGroup() { return selectedGroup; } /** * Sets current selected group. * * @param group selected at UI. */ public void setSelectedGroup(Group group) { this.selectedGroup = group; } /** * Sets List of groups which shown at UI. * * @param groups selected at UI. */ public void setGroups(ListModelList<Group> groups) { this.groups = groups; } /** * Sets Search string, used for group search. * * @param searchString string used for group search. */ public void setSearchString(String searchString) { this.searchString = searchString; } }
poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java
/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.poulpe.web.controller.group; import org.jtalks.common.model.entity.Group; import org.jtalks.poulpe.service.GroupService; import org.jtalks.poulpe.web.controller.SelectedEntity; import org.jtalks.poulpe.web.controller.WindowManager; import org.zkoss.bind.annotation.BindingParam; import org.zkoss.bind.annotation.Command; import org.zkoss.bind.annotation.NotifyChange; import org.zkoss.zul.ListModelList; import javax.annotation.Nonnull; /** * View-model for 'User Groups' Is used to order to work with page that allows admin to manage groups(add, edit, * delete). Also class provides access to Members edit window, presented by {@link EditGroupMembersVm}. * * @author Leonid Kazancev */ public class UserGroupVm { private static final String SHOW_DELETE_DIALOG = "showDeleteDialog", SHOW_EDIT_DIALOG = "showEditDialog", SHOW_NEW_DIALOG = "showNewDialog", SELECTED_GROUP = "selectedGroup"; //Injected private GroupService groupService; private final WindowManager windowManager; private ListModelList<Group> groups; private Group selectedGroup; private SelectedEntity<Group> selectedEntity; private String searchString = ""; private boolean showDeleteDialog; private boolean showEditDialog; private boolean showNewDialog; /** * Construct View-Model for 'User groups' view. * * @param groupService the group service instance * @param selectedEntity the selected entity instance * @param windowManager the window manager instance */ public UserGroupVm(@Nonnull GroupService groupService, @Nonnull SelectedEntity<Group> selectedEntity, @Nonnull WindowManager windowManager) { this.groupService = groupService; this.selectedEntity = selectedEntity; this.windowManager = windowManager; this.groups = new ListModelList<Group>(groupService.getAll(), true); } /** * Makes group list view actual. */ public void updateView() { groups.clear(); groups.addAll(groupService.getAll()); } // -- ZK Command bindings -------------------- /** * Look for the users matching specified pattern from the search textbox. */ @Command public void searchGroup() { groups.clear(); groups.addAll(groupService.getAllMatchedByName(searchString)); } /** * Opens edit group members window. */ @Command public void showGroupMemberEditWindow() { selectedEntity.setEntity(selectedGroup); EditGroupMembersVm.showDialog(windowManager); } /** * Deletes selected group. */ @Command @NotifyChange(SELECTED_GROUP) public void deleteGroup() { groupService.deleteGroup(selectedGroup); closeDialog(); updateView(); } /** * Opens group adding dialog. */ @Command @NotifyChange({SELECTED_GROUP, SHOW_NEW_DIALOG}) public void showNewGroupDialog() { selectedGroup = new Group(); showNewDialog = true; } /** * Saves group, closing group edit(add) dialog and updates view. * * @param group editing group */ @Command @NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG}) public void saveGroup(@BindingParam(value = "group") Group group) { groupService.saveGroup(group); closeDialog(); updateView(); } /** * Close all dialogs by set visibility to false. */ @Command @NotifyChange({SHOW_NEW_DIALOG, SHOW_DELETE_DIALOG, SHOW_EDIT_DIALOG}) public void closeDialog() { showNewDialog = false; showDeleteDialog = false; showEditDialog = false; } // -- Getters/Setters -------------------- /** * Gets visibility status of Delete dialog window. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowDeleteDialog() { return showDeleteDialog; } /** * Gets visibility status of Edit dialog window. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowEditDialog() { return showEditDialog; } /** * Gets visibility status of New group dialog window, boolean show added as fix for onClose action, which don't send * anything to the server when closing window because of event.stopPropagation, so during next change notification * ZK will think that we need to show that dialog again which is wrong. * * @return true if dialog is visible false if dialog is invisible */ public boolean isShowNewDialog() { boolean show = showNewDialog; showNewDialog = false; return show; } /** * Gets List of groups which shown at UI. * * @return Groups currently displayed at UI. */ @SuppressWarnings("unused") public ListModelList<Group> getGroups() { return groups; } /** * Gets current selected group. * * @return Group selected at UI. */ @SuppressWarnings("unused") public Group getSelectedGroup() { return selectedGroup; } /** * Sets current selected group. * * @param group selected at UI. */ public void setSelectedGroup(Group group) { this.selectedGroup = group; } /** * Sets List of groups which shown at UI. * * @param groups selected at UI. */ public void setGroups(ListModelList<Group> groups) { this.groups = groups; } /** * Sets Search string, used for group search. * * @param searchString string used for group search. */ public void setSearchString(String searchString) { this.searchString = searchString; } }
Longline fixed
poulpe-view/poulpe-web-controller/src/main/java/org/jtalks/poulpe/web/controller/group/UserGroupVm.java
Longline fixed
Java
lgpl-2.1
8cbfd4efc7177a266f58af025c9923529f8c19b4
0
krichter722/swingx,krichter722/swingx,trejkaz/swingx,trejkaz/swingx,tmyroadctfig/swingx
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.PrinterException; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.DefaultCellEditor; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SizeSequence; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableModelEvent; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.BoundAction; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterPipeline; import org.jdesktop.swingx.decorator.PatternHighlighter; import org.jdesktop.swingx.decorator.PipelineEvent; import org.jdesktop.swingx.decorator.PipelineListener; import org.jdesktop.swingx.decorator.RowSizing; import org.jdesktop.swingx.decorator.SearchHighlighter; import org.jdesktop.swingx.decorator.Selection; import org.jdesktop.swingx.decorator.Sorter; import org.jdesktop.swingx.icon.ColumnControlIcon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.table.TableColumnModelExt; /** * <p> * A JXTable is a JTable with built-in support for row sorting, filtering, and * highlighting, column visibility and a special popup control on the column * header for quick access to table configuration. You can instantiate a JXTable * just as you would a JTable, using a TableModel. However, a JXTable * automatically wraps TableColumns inside a TableColumnExt instance. * TableColumnExt supports visibility, sortability, and prototype values for * column sizing, none of which are available in TableColumn. You can retrieve * the TableColumnExt instance for a column using {@link #getColumnExt(Object)} * or {@link #getColumnExt(int colnumber)}. * * <p> * A JXTable is, by default, sortable by clicking on column headers; each * subsequent click on a header reverses the order of the sort, and a sort arrow * icon is automatically drawn on the header. Sorting can be disabled using * {@link #setSortable(boolean)}. Sorting on columns is handled by a Sorter * instance which contains a Comparator used to compare values in two rows of a * column. You can replace the Comparator for a given column by using * <code>getColumnExt("column").getSorter().setComparator(customComparator)</code> * * <p> * Columns can be hidden or shown by setting the visible property on the * TableColumnExt using {@link TableColumnExt#setVisible(boolean)}. Columns can * also be shown or hidden from the column control popup. * * <p> * The column control popup is triggered by an icon drawn to the far right of * the column headers, above the table's scrollbar (when installed in a * JScrollPane). The popup allows the user to select which columns should be * shown or hidden, as well as to pack columns and turn on horizontal scrolling. * To show or hide the column control, use the * {@link #setColumnControlVisible(boolean show)}method. * * <p> * Rows can be filtered from a JXTable using a Filter class and a * FilterPipeline. One assigns a FilterPipeline to the table using * {@link #setFilters(FilterPipeline)}. Filtering hides, but does not delete or * permanently remove rows from a JXTable. Filters are used to provide sorting * to the table--rows are not removed, but the table is made to believe rows in * the model are in a sorted order. * * <p> * One can automatically highlight certain rows in a JXTable by attaching * Highlighters in the {@link #setHighlighters(HighlighterPipeline)}method. An * example would be a Highlighter that colors alternate rows in the table for * readability; AlternateRowHighlighter does this. Again, like Filters, * Highlighters can be chained together in a HighlighterPipeline to achieve more * interesting effects. * * <p> * You can resize all columns, selected columns, or a single column using the * methods like {@link #packAll()}. Packing combines several other aspects of a * JXTable. If horizontal scrolling is enabled using * {@link #setHorizontalScrollEnabled(boolean)}, then the scrollpane will allow * the table to scroll right-left, and columns will be sized to their preferred * size. To control the preferred sizing of a column, you can provide a * prototype value for the column in the TableColumnExt using * {@link TableColumnExt#setPrototypeValue(Object)}. The prototype is used as * an indicator of the preferred size of the column. This can be useful if some * data in a given column is very long, but where the resize algorithm would * normally not pick this up. * * <p> * Last, you can also provide searches on a JXTable using the search methods. * * @author Ramesh Gupta * @author Amy Fowler * @author Mark Davidson * @author Jeanette Winzenburg */ public class JXTable extends JTable { //implements Searchable { /** * Constant string for horizontal scroll actions, used in JXTable's Action * Map. */ public static final String HORIZONTALSCROLL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "horizontalScroll"; /** Constant string for packing all columns, used in JXTable's Action Map. */ public static final String PACKALL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packAll"; /** * Constant string for packing selected columns, used in JXTable's Action * Map. */ public static final String PACKSELECTED_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packSelected"; /** The prefix marker to find component related properties in the resourcebundle. */ public static final String UIPREFIX = "JXTable."; /** key for client property to use SearchHighlighter as match marker. */ public static final String MATCH_HIGHLIGHTER = "match.highlighter"; static { // Hack: make sure the resource bundle is loaded LookAndFeelAddons.getAddon(); } /** The FilterPipeline for the table. */ protected FilterPipeline filters = null; /** The HighlighterPipeline for the table. */ protected HighlighterPipeline highlighters = null; /** The ComponentAdapter for model data access. */ protected ComponentAdapter dataAdapter; /** The handler for mapping view/model coordinates of row selection. */ private Selection selection; /** flag to indicate if table is interactively sortable. */ private boolean sortable; /** future - enable/disable autosort on cell updates not used */ // private boolean automaticSortDisabled; /** Listens for changes from the filters. */ private PipelineListener pipelineListener; /** Listens for changes from the highlighters. */ private ChangeListener highlighterChangeListener; /** the factory to use for column creation and configuration. */ private ColumnFactory columnFactory; /** The default number of visible rows (in a ScrollPane). */ private int visibleRowCount = 18; private RowSizing rowSizing; private Field rowModelField; private boolean rowHeightEnabled; /** * flag to indicate if the column control is visible. */ private boolean columnControlVisible; /** * ScrollPane's original vertical scroll policy. If the columnControl is * visible the policy is set to ALWAYS. */ private int verticalScrollPolicy; /** * A button that allows the user to select which columns to display, and * which to hide */ private JComponent columnControlButton; /** * Mouse/Motion/Listener keeping track of mouse moved in cell coordinates. */ private RolloverProducer rolloverProducer; /** * RolloverController: listens to cell over events and repaints * entered/exited rows. */ private LinkController linkController; /** field to store the autoResizeMode while interactively setting * horizontal scrollbar to visible. */ private int oldAutoResizeMode; /** temporary hack: rowheight will be internally adjusted to font size * on instantiation and in updateUI if * the height has not been set explicitly by the application. */ protected boolean isXTableRowHeightSet; protected Searchable searchable; /** Instantiates a JXTable with a default table model, no data. */ public JXTable() { init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm) { super(dm); init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm, TableColumnModel cm) { super(dm, cm); init(); } /** * Instantiates a JXTable with a specific table model, column model, and * selection model. * * @param dm * The table model to use. * @param cm * The colomn model to use. * @param sm * The list selection model to use. */ public JXTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) { super(dm, cm, sm); init(); } /** * Instantiates a JXTable for a given number of columns and rows. * * @param numRows * Count of rows to accomodate. * @param numColumns * Count of columns to accomodate. */ public JXTable(int numRows, int numColumns) { super(numRows, numColumns); init(); } /** * Instantiates a JXTable with data in a vector or rows and column names. * * @param rowData * Row data, as a Vector of Objects. * @param columnNames * Column names, as a Vector of Strings. */ public JXTable(Vector rowData, Vector columnNames) { super(rowData, columnNames); init(); } /** * Instantiates a JXTable with data in a array or rows and column names. * * @param rowData * Row data, as a two-dimensional Array of Objects (by row, for * column). * @param columnNames * Column names, as a Array of Strings. */ public JXTable(Object[][] rowData, Object[] columnNames) { super(rowData, columnNames); init(); } /** Initializes the table for use. */ protected void init() { setSortable(true); // guarantee getFilters() to return != null setFilters(null); initActionsAndBindings(); // instantiate row height depending on font size updateRowHeightUI(false); } /** * Property to enable/disable rollover support. This can be enabled to show * "live" rollover behaviour, f.i. the cursor over LinkModel cells. Default * is disabled. If using a RolloverHighlighter on the table, this should be * set to true. * * @param rolloverEnabled */ public void setRolloverEnabled(boolean rolloverEnabled) { boolean old = isRolloverEnabled(); if (rolloverEnabled == old) return; if (rolloverEnabled) { rolloverProducer = new RolloverProducer(); addMouseListener(rolloverProducer); addMouseMotionListener(rolloverProducer); linkController = new LinkController(); addPropertyChangeListener(linkController); } else { removeMouseListener(rolloverProducer); removeMouseMotionListener(rolloverProducer); rolloverProducer = null; removePropertyChangeListener(linkController); linkController = null; } firePropertyChange("rolloverEnabled", old, isRolloverEnabled()); } /** * Returns the rolloverEnabled property. * * @return <code>true</code> if rollover is enabled */ public boolean isRolloverEnabled() { return rolloverProducer != null; } /** * If the default editor for LinkModel.class is of type LinkRenderer enables * link visiting with the given linkVisitor. As a side-effect the rollover * property is set to true. * * @param linkVisitor */ public void setDefaultLinkVisitor(ActionListener linkVisitor) { TableCellEditor renderer = getDefaultEditor(LinkModel.class); if (renderer instanceof LinkRenderer) { ((LinkRenderer) renderer).setVisitingDelegate(linkVisitor); } setRolloverEnabled(true); } //--------------------------------- ColumnControl /** * overridden to addionally configure the upper right corner of an enclosing * scrollpane with the ColumnControl. */ protected void configureEnclosingScrollPane() { super.configureEnclosingScrollPane(); configureColumnControl(); configureViewportBackground(); } /** * set's the viewports background to this.background. PENDING: need to * repeat on background changes to this! * */ protected void configureViewportBackground() { Container p = getParent(); if (p instanceof JViewport) { p.setBackground(getBackground()); } } /** * configure the upper right corner of an enclosing scrollpane with/o the * ColumnControl, depending on setting of columnControl visibility flag. * * PENDING: should choose corner depending on component orientation. */ private void configureColumnControl() { Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; // Make certain we are the viewPort's view and not, for // example, the rowHeaderView of the scrollPane - // an implementor of fixed columns might do this. JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } if (isColumnControlVisible()) { verticalScrollPolicy = scrollPane .getVerticalScrollBarPolicy(); scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, getColumnControl()); scrollPane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); } else { scrollPane .setVerticalScrollBarPolicy(verticalScrollPolicy == 0 ? ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED : verticalScrollPolicy); try { scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, null); } catch (Exception ex) { // Ignore spurious exception thrown by JScrollPane. This // is a Swing bug! } } } } } /** * returns visibility flag of column control. * <p> * * Note: if the table is not inside a JScrollPane the column control is not * shown even if this returns true. In this case it's the responsibility of * the client code to actually show it. * * @return */ public boolean isColumnControlVisible() { return columnControlVisible; } /** * returns the component for column control. * * @return */ public JComponent getColumnControl() { if (columnControlButton == null) { columnControlButton = new ColumnControlButton(this, new ColumnControlIcon()); } return columnControlButton; } /** * bound property to flag visibility state of column control. * * @param showColumnControl */ public void setColumnControlVisible(boolean showColumnControl) { boolean old = columnControlVisible; this.columnControlVisible = showColumnControl; // JW: hacking issue #38(swingx) to initially add all columns // if (showColumnControl) { // getColumnControl(); // } configureColumnControl(); firePropertyChange("columnControlVisible", old, columnControlVisible); } //--------------------- actions /** * A small class which dispatches actions. TODO: Is there a way that we can * make this static? JW: I hate those if constructs... we are in OO-land! */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("print".equals(getName())) { try { print(); } catch (PrinterException ex) { // REMIND(aim): should invoke pluggable application error // handler ex.printStackTrace(); } } else if ("find".equals(getName())) { find(); } } } private void initActionsAndBindings() { // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("print", new Actions("print")); map.put("find", new Actions("find")); map.put(PACKALL_ACTION_COMMAND, createPackAllAction()); map.put(PACKSELECTED_ACTION_COMMAND, createPackSelectedAction()); map.put(HORIZONTALSCROLL_ACTION_COMMAND, createHorizontalScrollAction()); // this should be handled by the LF! KeyStroke findStroke = KeyStroke.getKeyStroke("control F"); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find"); } /** Creates an Action for horizontal scrolling. */ private Action createHorizontalScrollAction() { String actionName = getUIString(HORIZONTALSCROLL_ACTION_COMMAND); BoundAction action = new BoundAction(actionName, HORIZONTALSCROLL_ACTION_COMMAND); action.setStateAction(); action.registerCallback(this, "setHorizontalScrollEnabled"); action.setSelected(isHorizontalScrollEnabled()); return action; } private String getUIString(String key) { String text = UIManager.getString(UIPREFIX + key); return text != null ? text : key; } /** Creates an Action for packing selected columns. */ private Action createPackSelectedAction() { String text = getUIString(PACKSELECTED_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKSELECTED_ACTION_COMMAND); action.registerCallback(this, "packSelected"); action.setEnabled(getSelectedColumnCount() > 0); return action; } /** Creates an Action for packing all columns. */ private Action createPackAllAction() { String text = getUIString(PACKALL_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKALL_ACTION_COMMAND); action.registerCallback(this, "packAll"); return action; } //------------------ bound action callback methods /** * This resizes all columns to fit the viewport; if horizontal scrolling is * enabled, all columns will get their preferred width. This can be * triggered by the "packAll" BoundAction on the table as well. */ public void packAll() { packTable(getDefaultPackMargin()); } /** * This resizes selected columns to fit the viewport; if horizontal * scrolling is enabled, selected columns will get their preferred width. * This can be triggered by the "packSelected" BoundAction on the table as * well. */ public void packSelected() { int selected = getSelectedColumn(); if (selected >= 0) { packColumn(selected, getDefaultPackMargin()); } } /** * Controls horizontal scrolling in the viewport, and works in coordination * with column sizing. * * @param enabled * If true, the scrollpane will allow the table to scroll * horizontally, and columns will resize to their preferred * width. If false, columns will resize to fit the viewport. */ public void setHorizontalScrollEnabled(boolean enabled) { if (enabled == (isHorizontalScrollEnabled())) return; if (enabled) { oldAutoResizeMode = getAutoResizeMode(); setAutoResizeMode(AUTO_RESIZE_OFF); } else { setAutoResizeMode(oldAutoResizeMode); } } /** Returns the current setting for horizontal scrolling. */ private boolean isHorizontalScrollEnabled() { return getAutoResizeMode() == AUTO_RESIZE_OFF; } /** Returns the default margin for packing columns. */ private int getDefaultPackMargin() { return 4; } /** Notifies the table that a new column has been selected. * overridden to update the enabled state of the packSelected * action. */ public void columnSelectionChanged(ListSelectionEvent e) { super.columnSelectionChanged(e); if (e.getValueIsAdjusting()) return; Action packSelected = getActionMap().get(PACKSELECTED_ACTION_COMMAND); if ((packSelected != null)) {// && (e.getSource() instanceof // ListSelectionModel)){ packSelected.setEnabled(!((ListSelectionModel) e.getSource()) .isSelectionEmpty()); } } /** * overridden to update the show horizontal scrollbar action's * selected state. */ public void setAutoResizeMode(int mode) { super.setAutoResizeMode(mode); Action showHorizontal = getActionMap().get( HORIZONTALSCROLL_ACTION_COMMAND); if (showHorizontal instanceof BoundAction) { ((BoundAction) showHorizontal) .setSelected(isHorizontalScrollEnabled()); } } //------------------------ override super because of filter-awareness /** * Returns the row count in the table; if filters are applied, this is the * filtered row count. */ @Override public int getRowCount() { // RG: If there are no filters, call superclass version rather than // accessing model directly return filters == null ? // return ((filters == null) || !filters.isAssigned()) ? super.getRowCount() : filters.getOutputSize(); } public boolean isHierarchical(int column) { return false; } /** * Convert row index from view coordinates to model coordinates accounting * for the presence of sorters and filters. * * @param row * row index in view coordinates * @return row index in model coordinates */ public int convertRowIndexToModel(int row) { return getFilters().convertRowIndexToModel(row); } /** * Convert row index from model coordinates to view coordinates accounting * for the presence of sorters and filters. * * @param row * row index in model coordinates * @return row index in view coordinates */ public int convertRowIndexToView(int row) { return getFilters().convertRowIndexToView(row); } /** * {@inheritDoc} */ public Object getValueAt(int row, int column) { return getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(column)); // return getFilters().getValueAt(row, convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public void setValueAt(Object aValue, int row, int column) { getModel().setValueAt(aValue, convertRowIndexToModel(row), convertColumnIndexToModel(column)); // getFilters().setValueAt(aValue, row, convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public boolean isCellEditable(int row, int column) { return getModel().isCellEditable(convertRowIndexToModel(row), convertColumnIndexToModel(column)); // return getFilters().isCellEditable(row, // convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public void setModel(TableModel newModel) { // JW: need to clear here because super.setModel // calls tableChanged... // fixing #173 // clearSelection(); getSelection().lock(); super.setModel(newModel); // JW: PENDING - needs cleanup, probably much simpler now... // not needed because called in tableChanged // use(filters); } /** ? */ public void tableChanged(TableModelEvent e) { // make Selection deaf ... super doesn't know about row // mapping and sets rowSelection in model coordinates // causing complete confusion. getSelection().lock(); super.tableChanged(e); updateSelectionAndRowModel(e); use(filters); // JW: this is for the sake of the very first call to setModel, done in // super on instantiation - at that time filters cannot be set // because they will be re-initialized to null // ... arrrgggg // if (filters != null) { // filters.flush(); // will call updateOnFilterContentChanged() // } else { // // not really needed... we reach this branch only on the // // very first super.setModel() // getSelection().restoreSelection(); // } } /** * reset model selection coordinates in Selection after * model events. * * @param e */ private void updateSelectionAndRowModel(TableModelEvent e) { // c&p from JTable // still missing: checkLeadAnchor if (e.getType() == TableModelEvent.INSERT) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } // Adjust the selection to account for the new rows. int length = end - start + 1; getSelection().insertIndexInterval(start, length, true); getRowSizing().insertIndexInterval(start, length, getRowHeight()); } else if (e.getType() == TableModelEvent.DELETE) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } int deletedCount = end - start + 1; int previousRowCount = getModel().getRowCount() + deletedCount; // Adjust the selection to account for the new rows getSelection().removeIndexInterval(start, end); getRowSizing().removeIndexInterval(start, deletedCount); } else if (getSelectionModel().isSelectionEmpty()) { // possibly got a dataChanged or structureChanged // super will have cleared selection getSelection().clearModelSelection(); getRowSizing().clearModelSizes(); getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); } } private Selection getSelection() { if (selection == null) { selection = new Selection(filters, getSelectionModel()); } return selection; } //----------------------------- filters /** Returns the FilterPipeline for the table. */ public FilterPipeline getFilters() { // PENDING: this is guaranteed to be != null because // init calls setFilters(null) which enforces an empty // pipeline return filters; } /** * setModel() and setFilters() may be called in either order. * * @param pipeline */ private void use(FilterPipeline pipeline) { if (pipeline != null) { // check JW: adding listener multiple times (after setModel)? if (initialUse(pipeline)) { pipeline.addPipelineListener(getFilterPipelineListener()); pipeline.assign(getComponentAdapter()); } else { pipeline.flush(); } } } /** * @return true is not yet used in this JXTable, false otherwise */ private boolean initialUse(FilterPipeline pipeline) { if (pipelineListener == null) return true; PipelineListener[] l = pipeline.getPipelineListeners(); for (int i = 0; i < l.length; i++) { if (pipelineListener.equals(l[i])) return false; } return true; } /** Sets the FilterPipeline for filtering table rows. */ public void setFilters(FilterPipeline pipeline) { FilterPipeline old = getFilters(); Sorter sorter = null; if (old != null) { old.removePipelineListener(pipelineListener); sorter = old.getSorter(); } if (pipeline == null) { pipeline = new FilterPipeline(); } filters = pipeline; filters.setSorter(sorter); getSelection().setFilters(filters); getRowSizing().setFilters(filters); use(filters); } /** returns the listener for changes in filters. */ protected PipelineListener getFilterPipelineListener() { if (pipelineListener == null) { pipelineListener = createPipelineListener(); } return pipelineListener; } /** creates the listener for changes in filters. */ protected PipelineListener createPipelineListener() { PipelineListener l = new PipelineListener() { public void contentsChanged(PipelineEvent e) { updateOnFilterContentChanged(); } }; return l; } /** * method called on change notification from filterpipeline. */ protected void updateOnFilterContentChanged() { // Force private rowModel in JTable to null; // adminSetRowHeight(getRowHeight()); revalidate(); repaint(); } //-------------------------------- sorting /** * Sets &quot;sortable&quot; property indicating whether or not this table * supports sortable columns. If <code>sortable</code> is * <code>true</code> then sorting will be enabled on all columns whose * <code>sortable</code> property is <code>true</code>. If * <code>sortable</code> is <code>false</code> then sorting will be * disabled for all columns, regardless of each column's individual * <code>sorting</code> property. The default is <code>true</code>. * * @see TableColumnExt#isSortable() * @param sortable * boolean indicating whether or not this table supports sortable * columns */ public void setSortable(boolean sortable) { if (sortable == isSortable()) return; this.sortable = sortable; if (!isSortable()) resetSorter(); firePropertyChange("sortable", !sortable, sortable); // JW @todo: this is a hack! // check if the sortable/not sortable toggling still works with the // sorter in pipeline // if (getInteractiveSorter() != null) { // updateOnFilterContentChanged(); // } // } /** Returns true if the table is sortable. */ public boolean isSortable() { return sortable; } // public void setAutomaticSort(boolean automaticEnabled) { // this.automaticSortDisabled = !automaticEnabled; // // } // // public boolean isAutomaticSort() { // return !automaticSortDisabled; // } private void setInteractiveSorter(Sorter sorter) { // this check is for the sake of the very first call after instantiation if (filters == null) return; getFilters().setSorter(sorter); } private Sorter getInteractiveSorter() { // this check is for the sake of the very first call after instantiation if (filters == null) return null; return getFilters().getSorter(); } /** * Removes the interactive sorter. * Used by headerListener. * */ protected void resetSorter() { // JW PENDING: think about notification instead of manual repaint. setInteractiveSorter(null); getTableHeader().repaint(); } public void columnRemoved(TableColumnModelEvent e) { // old problem: need access to removed column // to get hold of removed modelIndex // to remove interactive sorter if any // no way // int modelIndex = convertColumnIndexToModel(e.getFromIndex()); updateSorterAfterColumnRemoved(); super.columnRemoved(e); } /** * guarantee that the interactive sorter is removed if its column * is removed. * */ private void updateSorterAfterColumnRemoved() { // bloody hack: get sorter and check if there's a column with it // available Sorter sorter = getInteractiveSorter(); if (sorter != null) { int sorterColumn = sorter.getColumnIndex(); List columns = getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); if (column.getModelIndex() == sorterColumn) return; } // didn't find a column with the sorter's index - remove resetSorter(); } } /** * * request to sort the column at columnIndex in view coordinates. if there * is already an interactive sorter for this column it's sort order is * reversed. Otherwise the columns sorter is used as is. * Used by headerListener. * */ protected void setSorter(int columnIndex) { if (!isSortable()) return; Sorter sorter = getInteractiveSorter(); if ((sorter != null) && (sorter.getColumnIndex() == convertColumnIndexToModel(columnIndex))) { sorter.toggle(); } else { TableColumnExt column = getColumnExt(columnIndex); getFilters().setSorter(column != null ? column.getSorter() : null); } } /** * Returns the interactive sorter if it is set from the given column. * Used by ColumnHeaderRenderer.getTableCellRendererComponent(). * * @param columnIndex the column index in view coordinates. * @return the interactive sorter if matches the column or null. */ public Sorter getSorter(int columnIndex) { Sorter sorter = getInteractiveSorter(); return sorter == null ? null : sorter.getColumnIndex() == convertColumnIndexToModel(columnIndex) ? sorter : null; } //---------------------- enhanced TableColumn/Model support /** * Remove all columns, make sure to include hidden. * */ protected void removeColumns() { /** * @todo promote this method to superclass, and change * createDefaultColumnsFromModel() to call this method */ List columns = getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { getColumnModel().removeColumn((TableColumn) iter.next()); } } /** * returns a list of all visible TableColumns. * * @return */ public List getColumns() { return Collections.list(getColumnModel().getColumns()); } /** * returns a list of TableColumns including hidden if the parameter is set * to true. * * @param includeHidden * @return */ public List getColumns(boolean includeHidden) { if (includeHidden && (getColumnModel() instanceof TableColumnModelExt)) { return ((TableColumnModelExt) getColumnModel()) .getColumns(includeHidden); } return getColumns(); } /** * returns the number of TableColumns including hidden if the parameter is set * to true. * * @param includeHidden * @return */ public int getColumnCount(boolean includeHidden) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnCount(includeHidden); } return getColumnCount(); } /** * reorders the columns in the sequence given array. Logical names that do * not correspond to any column in the model will be ignored. Columns with * logical names not contained are added at the end. * * @param columnNames * array of logical column names */ public void setColumnSequence(Object[] identifiers) { List columns = getColumns(true); Map map = new HashMap(); for (Iterator iter = columns.iterator(); iter.hasNext();) { // PENDING: handle duplicate identifiers ... TableColumn column = (TableColumn) iter.next(); map.put(column.getIdentifier(), column); getColumnModel().removeColumn(column); } for (int i = 0; i < identifiers.length; i++) { TableColumn column = (TableColumn) map.get(identifiers[i]); if (column != null) { getColumnModel().addColumn(column); columns.remove(column); } } for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); getColumnModel().addColumn(column); } } /** * Returns the <code>TableColumnExt</code> object for the column in the * table whose identifier is equal to <code>identifier</code>, when * compared using <code>equals</code>. The returned TableColumn is * guaranteed to be part of the current ColumnModel but may be hidden, that * is * * <pre> <code> * TableColumnExt column = table.getColumnExt(id); * if (column != null) { * int viewIndex = table.convertColumnIndexToView(column.getModelIndex()); * assertEquals(column.isVisible(), viewIndex &gt;= 0); * } * </code> </pre> * * @param identifier * the identifier object * * @return the <code>TableColumnExt</code> object that matches the * identifier or null if none is found. */ public TableColumnExt getColumnExt(Object identifier) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnExt(identifier); } else { // PENDING: not tested! try { TableColumn column = getColumn(identifier); if (column instanceof TableColumnExt) { return (TableColumnExt) column; } } catch (Exception e) { // TODO: handle exception } } return null; } /** * Returns the <code>TableColumnExt</code> object for the column in the * table whose column index is equal to <code>viewColumnIndex</code> * * @param viewColumnIndex * index of the column with the object in question * * @return the <code>TableColumnExt</code> object that matches the column * index * @exception IllegalArgumentException * if no <code>TableColumn</code> has this identifier */ public TableColumnExt getColumnExt(int viewColumnIndex) { return (TableColumnExt) getColumnModel().getColumn(viewColumnIndex); } public void createDefaultColumnsFromModel() { TableModel model = getModel(); if (model != null) { // Create new columns from the data model info // Note: it's critical to create the new columns before // deleting the old ones. Why? // JW PENDING: the reason is somewhere in the early forums - search! int modelColumnCount = model.getColumnCount(); TableColumn newColumns[] = new TableColumn[modelColumnCount]; for (int i = 0; i < newColumns.length; i++) { newColumns[i] = createAndConfigureColumn(model, i); } // Remove any current columns removeColumns(); // Now add the new columns to the column model for (int i = 0; i < newColumns.length; i++) { addColumn(newColumns[i]); } } } protected TableColumn createAndConfigureColumn(TableModel model, int modelColumn) { return getColumnFactory().createAndConfigureTableColumn(model, modelColumn); } protected ColumnFactory getColumnFactory() { if (columnFactory == null) { columnFactory = ColumnFactory.getInstance(); } return columnFactory; } //----------------------- delegating methods?? from super /** * Returns the margin between columns. * * @return the margin between columns */ public int getColumnMargin() { return getColumnModel().getColumnMargin(); } /** * Sets the margin between columns. * * @param value * margin between columns; must be greater than or equal to zero. */ public void setColumnMargin(int value) { getColumnModel().setColumnMargin(value); } /** * Returns the selection mode used by this table's selection model. * * @return the selection mode used by this table's selection model */ public int getSelectionMode() { return getSelectionModel().getSelectionMode(); } //----------------------- Search support /** Opens the find widget for the table. */ private void find() { SearchFactory.getInstance().showFindInput(this, getSearchable()); // if (dialog == null) { // dialog = new JXFindDialog(); // } // dialog.setSearchable(this); // dialog.setVisible(true); } /** * * @returns a not-null Searchable for this editor. */ public Searchable getSearchable() { if (searchable == null) { searchable = new TableSearchable(); } return searchable; } /** * sets the Searchable for this editor. If null, a default * searchable will be used. * * @param searchable */ public void setSearchable(Searchable searchable) { this.searchable = searchable; } public class TableSearchable implements Searchable { /** * Performs a search across the table using String that represents a * regex pattern; {@link java.util.regex.Pattern}. All columns and all * rows are searched; the row id of the first match is returned. */ public int search(String searchString) { return search(searchString, -1); } /** * Performs a search on a column using String that represents a regex * pattern; {@link java.util.regex.Pattern}. The specified column * searched; the row id of the first match is returned. */ public int search(String searchString, int columnIndex) { if (searchString != null) { return search(Pattern.compile(searchString, 0), columnIndex); } return -1; } /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. All columns and all rows are * searched; the row id of the first match is returned. */ public int search(Pattern pattern) { return search(pattern, -1); } /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. starting at a given row. All * columns and all rows are searched; the row id of the first match is * returned. */ public int search(Pattern pattern, int startIndex) { return search(pattern, startIndex, false); } // Save the last column with the match. // TODO (JW) - lastCol should either be a valid column index or < 0 private int lastCol = 0; private SearchHighlighter searchHighlighter; /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. starting at a given row. All * columns and all rows are searched; the row id of the first match is * returned. * * @param startIndex * row to start search * @param backwards * whether to start at the last row and search up to the * first. * @return row with a match. */ public int search(Pattern pattern, int startIndex, boolean backwards) { int matchingRow = searchMatchingRow(pattern, startIndex, backwards); moveMatchMarker(pattern, matchingRow, lastCol); return matchingRow; } /** * returns/updates the matching row/column indices. * * @param pattern * @param startIndex * @param backwards * @return */ protected int searchMatchingRow(Pattern pattern, int startIndex, boolean backwards) { if (pattern == null) { lastCol = 0; return -1; } int rows = getRowCount(); int endCol = getColumnCount(); int matchRow = -1; if (backwards == true) { if (startIndex < 0) startIndex = rows; int startRow = startIndex - 1; for (int r = startRow; r >= 0 && matchRow == -1; r--) { for (int c = endCol - 1; c >= 0; c--) { Object value = getValueAt(r, c); if ((value != null) && pattern.matcher(value.toString()).find()) { matchRow = r; lastCol = c; break; // No need to search other columns } } if (matchRow == -1) { lastCol = endCol; } } } else { int startRow = startIndex + 1; for (int r = startRow; r < rows && matchRow == -1; r++) { for (int c = lastCol; c < endCol; c++) { Object value = getValueAt(r, c); if ((value != null) && pattern.matcher(value.toString()).find()) { matchRow = r; lastCol = c; break; // No need to search other columns } } if (matchRow == -1) { lastCol = 0; } } } return matchRow; } protected void moveMatchMarker(Pattern pattern, int row, int column) { if (markByHighlighter()) { Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } ensureInsertedSearchHighlighters(); // TODO (JW) - cleanup SearchHighlighter state management if ((row >= 0) && (column >= 0)) { getSearchHighlighter().setPattern(pattern); int modelColumn = convertColumnIndexToModel(column); getSearchHighlighter().setHighlightCell(row, modelColumn); } else { getSearchHighlighter().setPattern(null); } } else { // use selection changeSelection(row, column, false, false); if (!getAutoscrolls()) { // scrolling not handled by moving selection Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } } } } private boolean markByHighlighter() { return Boolean.TRUE.equals(getClientProperty(MATCH_HIGHLIGHTER)); } private SearchHighlighter getSearchHighlighter() { if (searchHighlighter == null) { searchHighlighter = createSearchHighlighter(); } return searchHighlighter; } private void ensureInsertedSearchHighlighters() { if (getHighlighters() == null) { setHighlighters(new HighlighterPipeline(new Highlighter[] {getSearchHighlighter()})); } else if (!isInPipeline(getSearchHighlighter())){ getHighlighters().addHighlighter(getSearchHighlighter()); } } private boolean isInPipeline(PatternHighlighter searchHighlighter) { Highlighter[] inPipeline = getHighlighters().getHighlighters(); for (int i = 0; i < inPipeline.length; i++) { if (searchHighlighter.equals(inPipeline[i])) return true; } return false; } protected SearchHighlighter createSearchHighlighter() { return new SearchHighlighter(); } } //-------------------------------- sizing support /** ? */ public void setVisibleRowCount(int visibleRowCount) { this.visibleRowCount = visibleRowCount; } /** ? */ public int getVisibleRowCount() { return visibleRowCount; } public Dimension getPreferredScrollableViewportSize() { Dimension prefSize = super.getPreferredScrollableViewportSize(); // JTable hardcodes this to 450 X 400, so we'll calculate it // based on the preferred widths of the columns and the // visibleRowCount property instead... if (prefSize.getWidth() == 450 && prefSize.getHeight() == 400) { TableColumnModel columnModel = getColumnModel(); int columnCount = columnModel.getColumnCount(); int w = 0; for (int i = 0; i < columnCount; i++) { TableColumn column = columnModel.getColumn(i); initializeColumnPreferredWidth(column); w += column.getPreferredWidth(); } prefSize.width = w; JTableHeader header = getTableHeader(); // remind(aim): height is still off...??? int rowCount = getVisibleRowCount(); prefSize.height = rowCount * getRowHeight() + (header != null ? header.getPreferredSize().height : 0); setPreferredScrollableViewportSize(prefSize); } return prefSize; } /** * Packs all the columns to their optimal size. Works best with auto * resizing turned off. * * Contributed by M. Hillary (Issue #60) * * @param margin * the margin to apply to each column. */ public void packTable(int margin) { for (int c = 0; c < getColumnCount(); c++) packColumn(c, margin, -1); } /** * Packs an indivudal column in the table. Contributed by M. Hillary (Issue * #60) * * @param column * The Column index to pack in View Coordinates * @param margin * The Margin to apply to the column width. */ public void packColumn(int column, int margin) { packColumn(column, margin, -1); } /** * Packs an indivual column in the table to less than or equal to the * maximum witdth. If maximun is -1 then the column is made as wide as it * needs. Contributed by M. Hillary (Issue #60) * * @param column * The Column index to pack in View Coordinates * @param margin * The margin to apply to the column * @param max * The maximum width the column can be resized to. -1 mean any * size. */ public void packColumn(int column, int margin, int max) { getColumnFactory().packColumn(this, getColumnExt(column), margin, max); } /** * Initialize the preferredWidth of the specified column based on the * column's prototypeValue property. If the column is not an instance of * <code>TableColumnExt</code> or prototypeValue is <code>null</code> * then the preferredWidth is left unmodified. * * @see org.jdesktop.swingx.table.TableColumnExt#setPrototypeValue * @param column * TableColumn object representing view column */ protected void initializeColumnPreferredWidth(TableColumn column) { if (column instanceof TableColumnExt) { getColumnFactory().configureColumnWidths(this, (TableColumnExt) column); } } //----------------------------------- uniform data model access protected ComponentAdapter getComponentAdapter() { if (dataAdapter == null) { dataAdapter = new TableAdapter(this); } return dataAdapter; } protected static class TableAdapter extends ComponentAdapter { private final JXTable table; /** * Constructs a <code>TableDataAdapter</code> for the specified target * component. * * @param component * the target component */ public TableAdapter(JXTable component) { super(component); table = component; } /** * Typesafe accessor for the target component. * * @return the target component as a {@link javax.swing.JTable} */ public JXTable getTable() { return table; } public String getColumnName(int columnIndex) { // TableColumnModel columnModel = table.getColumnModel(); // if (columnModel == null) { // return "Column " + columnIndex; // } // int viewColumn = modelToView(columnIndex); // TableColumn column = null; // if (viewColumn >= 0) { // column = columnModel.getColumn(viewColumn); // } TableColumn column = getColumnByModelIndex(columnIndex); return column == null ? "" : column.getHeaderValue().toString(); } protected TableColumn getColumnByModelIndex(int modelColumn) { List columns = table.getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); if (column.getModelIndex() == modelColumn) { return column; } } return null; } public String getColumnIdentifier(int columnIndex) { TableColumn column = getColumnByModelIndex(columnIndex); // int viewColumn = modelToView(columnIndex); // if (viewColumn >= 0) { // table.getColumnExt(viewColumn).getIdentifier(); // } Object identifier = column != null ? column.getIdentifier() : null; return identifier != null ? identifier.toString() : null; } public int getColumnCount() { return table.getModel().getColumnCount(); } public int getRowCount() { return table.getModel().getRowCount(); } /** * {@inheritDoc} */ public Object getValueAt(int row, int column) { // RG: eliminate superfluous back-and-forth conversions return table.getModel().getValueAt(row, column); } public void setValueAt(Object aValue, int row, int column) { // RG: eliminate superfluous back-and-forth conversions table.getModel().setValueAt(aValue, row, column); } public boolean isCellEditable(int row, int column) { // RG: eliminate superfluous back-and-forth conversions return table.getModel().isCellEditable(row, column); } public boolean isTestable(int column) { return getColumnByModelIndex(column) != null; } //-------------------------- accessing view state/values public Object getFilteredValueAt(int row, int column) { return table.getValueAt(row, modelToView(column)); // in view coordinates } /** * {@inheritDoc} */ public boolean isSelected() { return table.isCellSelected(row, column); } /** * {@inheritDoc} */ public boolean hasFocus() { boolean rowIsLead = (table.getSelectionModel() .getLeadSelectionIndex() == row); boolean colIsLead = (table.getColumnModel().getSelectionModel() .getLeadSelectionIndex() == column); return table.isFocusOwner() && (rowIsLead && colIsLead); } /** * {@inheritDoc} */ public int modelToView(int columnIndex) { return table.convertColumnIndexToView(columnIndex); } /** * {@inheritDoc} */ public int viewToModel(int columnIndex) { return table.convertColumnIndexToModel(columnIndex); } } //--------------------- managing renderers/editors /** Returns the HighlighterPipeline assigned to the table, null if none. */ public HighlighterPipeline getHighlighters() { return highlighters; } /** * Assigns a HighlighterPipeline to the table. bound property. */ public void setHighlighters(HighlighterPipeline pipeline) { HighlighterPipeline old = getHighlighters(); if (old != null) { old.removeChangeListener(getHighlighterChangeListener()); } highlighters = pipeline; if (highlighters != null) { highlighters.addChangeListener(getHighlighterChangeListener()); } firePropertyChange("highlighters", old, getHighlighters()); } /** * returns the ChangeListener to use with highlighters. Creates one if * necessary. * * @return != null */ private ChangeListener getHighlighterChangeListener() { if (highlighterChangeListener == null) { highlighterChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { repaint(); } }; } return highlighterChangeListener; } /** * Returns the decorated <code>Component</code> used as a stamp to render * the specified cell. Overrides superclass version to provide support for * cell decorators. * * @param renderer * the <code>TableCellRenderer</code> to prepare * @param row * the row of the cell to render, where 0 is the first row * @param column * the column of the cell to render, where 0 is the first column * @return the decorated <code>Component</code> used as a stamp to render * the specified cell * @see org.jdesktop.swingx.decorator.Highlighter */ public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { // JW PENDING: testing cadavers ... check if still needed // Object value = getValueAt(row, column); // Class columnClass = getColumnClass(column); // boolean typeclash = !columnClass.isInstance(value); // TableColumn tableColumn = getColumnModel().getColumn(column); // getColumnClass(column); Component stamp = super.prepareRenderer(renderer, row, column); adjustComponentOrientation(stamp); if (highlighters == null) { return stamp; // no need to decorate renderer with highlighters } else { // MUST ALWAYS ACCESS dataAdapter through accessor method!!! ComponentAdapter adapter = getComponentAdapter(); adapter.row = row; adapter.column = column; return highlighters.apply(stamp, adapter); } } private void adjustComponentOrientation(Component stamp) { if (stamp.getComponentOrientation().equals(getComponentOrientation())) return; stamp.applyComponentOrientation(getComponentOrientation()); } /** * Returns a new instance of the default renderer for the specified class. * This differs from <code>getDefaultRenderer()</code> in that it returns * a <b>new </b> instance each time so that the renderer may be set and * customized on a particular column. * * @param columnClass * Class of value being rendered * @return TableCellRenderer instance which renders values of the specified * type */ public TableCellRenderer getNewDefaultRenderer(Class columnClass) { TableCellRenderer renderer = getDefaultRenderer(columnClass); if (renderer != null) { try { return (TableCellRenderer) renderer.getClass().newInstance(); } catch (Exception e) { e.printStackTrace(); } } return null; } /** ? */ protected void createDefaultEditors() { super.createDefaultEditors(); setLazyEditor(LinkModel.class, "org.jdesktop.swingx.LinkRenderer"); } /** * Creates default cell renderers for objects, numbers, doubles, dates, * booleans, icons, and links. * THINK: delegate to TableCellRenderers? * */ protected void createDefaultRenderers() { // super.createDefaultRenderers(); // This duplicates JTable's functionality in order to make the renderers // available in getNewDefaultRenderer(); If JTable's renderers either // were public, or it provided a factory for *new* renderers, this would // not be needed defaultRenderersByColumnClass = new UIDefaults(); // Objects setLazyRenderer(Object.class, "javax.swing.table.DefaultTableCellRenderer"); // Numbers setLazyRenderer(Number.class, "org.jdesktop.swingx.JXTable$NumberRenderer"); // Doubles and Floats setLazyRenderer(Float.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); setLazyRenderer(Double.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); // Dates setLazyRenderer(Date.class, "org.jdesktop.swingx.JXTable$DateRenderer"); // Icons and ImageIcons setLazyRenderer(Icon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); setLazyRenderer(ImageIcon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); // Booleans setLazyRenderer(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanRenderer"); // Other setLazyRenderer(LinkModel.class, "org.jdesktop.swingx.LinkRenderer"); } /** ? */ private void setLazyValue(Hashtable h, Class c, String s) { h.put(c, new UIDefaults.ProxyLazyValue(s)); } /** ? */ private void setLazyRenderer(Class c, String s) { setLazyValue(defaultRenderersByColumnClass, c, s); } /** ? */ private void setLazyEditor(Class c, String s) { setLazyValue(defaultEditorsByColumnClass, c, s); } /* * Default Type-based Renderers: JTable's default table cell renderer * classes are private and JTable:getDefaultRenderer() returns a *shared* * cell renderer instance, thus there is no way for us to instantiate a new * instance of one of its default renderers. So, we must replicate the * default renderer classes here so that we can instantiate them when we * need to create renderers to be set on specific columns. */ public static class NumberRenderer extends DefaultTableCellRenderer { public NumberRenderer() { super(); setHorizontalAlignment(JLabel.TRAILING); } } public static class DoubleRenderer extends NumberRenderer { NumberFormat formatter; public DoubleRenderer() { super(); } public void setValue(Object value) { if (formatter == null) { formatter = NumberFormat.getInstance(); } setText((value == null) ? "" : formatter.format(value)); } } public static class DateRenderer extends DefaultTableCellRenderer { DateFormat formatter; public DateRenderer() { super(); } public void setValue(Object value) { if (formatter == null) { formatter = DateFormat.getDateInstance(); } setText((value == null) ? "" : formatter.format(value)); } } public static class IconRenderer extends DefaultTableCellRenderer { public IconRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); } public void setValue(Object value) { setIcon((value instanceof Icon) ? (Icon) value : null); } } public static class BooleanRenderer extends JCheckBox implements TableCellRenderer { public BooleanRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setSelected((value != null && ((Boolean) value).booleanValue())); return this; } } //---------------------------- updateUI support /** * bug fix: super doesn't update all renderers/editors. */ public void updateUI() { super.updateUI(); // JW PENDING: update columnControl if (columnControlButton != null) { columnControlButton.updateUI(); } for (Enumeration defaultEditors = defaultEditorsByColumnClass .elements(); defaultEditors.hasMoreElements();) { updateEditorUI(defaultEditors.nextElement()); } for (Enumeration defaultRenderers = defaultRenderersByColumnClass .elements(); defaultRenderers.hasMoreElements();) { updateRendererUI(defaultRenderers.nextElement()); } Enumeration columns = getColumnModel().getColumns(); if (getColumnModel() instanceof TableColumnModelExt) { columns = Collections .enumeration(((TableColumnModelExt) getColumnModel()) .getAllColumns()); } while (columns.hasMoreElements()) { TableColumn column = (TableColumn) columns.nextElement(); updateEditorUI(column.getCellEditor()); updateRendererUI(column.getCellRenderer()); updateRendererUI(column.getHeaderRenderer()); } updateRowHeightUI(true); configureViewportBackground(); } /** ? */ private void updateRowHeightUI(boolean respectRowSetFlag) { if (respectRowSetFlag && isXTableRowHeightSet) return; int minimumSize = getFont().getSize() + 6; int uiSize = UIManager.getInt(UIPREFIX + "rowHeight"); setRowHeight(Math.max(minimumSize, uiSize != 0 ? uiSize : 18)); isXTableRowHeightSet = false; } /** Changes the row height for all rows in the table. */ public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (rowHeight > 0) { isXTableRowHeightSet = true; } getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); } public void setRowHeight(int row, int rowHeight) { if (!isRowHeightEnabled()) return; super.setRowHeight(row, rowHeight); getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); resizeAndRepaint(); } /** * sets enabled state of individual rowHeight support. The default * is false. * Enabling the support envolves reflective access * to super's private field rowModel which may fail due to security * issues. If failing the support is not enabled. * * PENDING: should we throw an Exception if the enabled fails? * Or silently fail - depends on runtime context, * can't do anything about it. * * @param enabled */ public void setRowHeightEnabled(boolean enabled) { boolean old = isRowHeightEnabled(); if (old == enabled) return; if (enabled && !canEnableRowHeight()) return; rowHeightEnabled = enabled; if (!enabled) { adminSetRowHeight(getRowHeight()); } // getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); firePropertyChange("rowHeightEnabled", old, rowHeightEnabled); } private boolean canEnableRowHeight() { return getRowModelField() != null; } public boolean isRowHeightEnabled() { return rowHeightEnabled; } private SizeSequence getSuperRowModel() { try { Field field = getRowModelField(); if (field != null) { return (SizeSequence) field.get(this); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * @return * @throws NoSuchFieldException */ private Field getRowModelField() { if (rowModelField == null) { try { rowModelField = JTable.class.getDeclaredField("rowModel"); rowModelField.setAccessible(true); } catch (SecurityException e) { rowModelField = null; e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rowModelField; } /** * * @return */ protected RowSizing getRowSizing() { if (rowSizing == null) { rowSizing = new RowSizing(filters); } return rowSizing; } /** * calling setRowHeight for internal reasons. * Keeps the isXTableRowHeight unchanged. */ protected void adminSetRowHeight(int rowHeight) { boolean heightSet = isXTableRowHeightSet; setRowHeight(rowHeight); isXTableRowHeightSet = heightSet; } private void updateEditorUI(Object value) { // maybe null or proxyValue if (!(value instanceof TableCellEditor)) return; // super handled this if ((value instanceof JComponent) || (value instanceof DefaultCellEditor)) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellEditor) value) .getTableCellEditorComponent(this, null, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } /** ? */ private void updateRendererUI(Object value) { // maybe null or proxyValue if (!(value instanceof TableCellRenderer)) return; // super handled this if (value instanceof JComponent) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellRenderer) value) .getTableCellRendererComponent(this, null, false, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } //---------------------------- overriding super factory methods and buggy /** * workaround bug in JTable. (Bug Parade ID #6291631 - negative y is mapped * to row 0). */ public int rowAtPoint(Point point) { if (point.y < 0) return -1; return super.rowAtPoint(point); } /** ? */ protected JTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel); } /** ? */ protected TableColumnModel createDefaultColumnModel() { return new DefaultTableColumnModelExt(); } // /** // * Returns the default table model object, which is // * a <code>DefaultTableModel</code>. A subclass can override this // * method to return a different table model object. // * // * @return the default table model object // * @see DefaultTableColumnModelExt // */ // protected TableModel createDefaultDataModel() { // return new DefaultTableModelExt(); // } }
src/java/org/jdesktop/swingx/JXTable.java
/* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.print.PrinterException; import java.lang.reflect.Field; import java.text.DateFormat; import java.text.NumberFormat; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.regex.Pattern; import javax.swing.Action; import javax.swing.ActionMap; import javax.swing.DefaultCellEditor; import javax.swing.DefaultListSelectionModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.KeyStroke; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SizeSequence; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableModelEvent; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import org.jdesktop.swingx.action.BoundAction; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.FilterPipeline; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterPipeline; import org.jdesktop.swingx.decorator.PatternHighlighter; import org.jdesktop.swingx.decorator.PipelineEvent; import org.jdesktop.swingx.decorator.PipelineListener; import org.jdesktop.swingx.decorator.RowSizing; import org.jdesktop.swingx.decorator.SearchHighlighter; import org.jdesktop.swingx.decorator.Selection; import org.jdesktop.swingx.decorator.Sorter; import org.jdesktop.swingx.icon.ColumnControlIcon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.table.ColumnControlButton; import org.jdesktop.swingx.table.ColumnFactory; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; import org.jdesktop.swingx.table.TableColumnExt; import org.jdesktop.swingx.table.TableColumnModelExt; /** * <p> * A JXTable is a JTable with built-in support for row sorting, filtering, and * highlighting, column visibility and a special popup control on the column * header for quick access to table configuration. You can instantiate a JXTable * just as you would a JTable, using a TableModel. However, a JXTable * automatically wraps TableColumns inside a TableColumnExt instance. * TableColumnExt supports visibility, sortability, and prototype values for * column sizing, none of which are available in TableColumn. You can retrieve * the TableColumnExt instance for a column using {@link #getColumnExt(Object)} * or {@link #getColumnExt(int colnumber)}. * * <p> * A JXTable is, by default, sortable by clicking on column headers; each * subsequent click on a header reverses the order of the sort, and a sort arrow * icon is automatically drawn on the header. Sorting can be disabled using * {@link #setSortable(boolean)}. Sorting on columns is handled by a Sorter * instance which contains a Comparator used to compare values in two rows of a * column. You can replace the Comparator for a given column by using * <code>getColumnExt("column").getSorter().setComparator(customComparator)</code> * * <p> * Columns can be hidden or shown by setting the visible property on the * TableColumnExt using {@link TableColumnExt#setVisible(boolean)}. Columns can * also be shown or hidden from the column control popup. * * <p> * The column control popup is triggered by an icon drawn to the far right of * the column headers, above the table's scrollbar (when installed in a * JScrollPane). The popup allows the user to select which columns should be * shown or hidden, as well as to pack columns and turn on horizontal scrolling. * To show or hide the column control, use the * {@link #setColumnControlVisible(boolean show)}method. * * <p> * Rows can be filtered from a JXTable using a Filter class and a * FilterPipeline. One assigns a FilterPipeline to the table using * {@link #setFilters(FilterPipeline)}. Filtering hides, but does not delete or * permanently remove rows from a JXTable. Filters are used to provide sorting * to the table--rows are not removed, but the table is made to believe rows in * the model are in a sorted order. * * <p> * One can automatically highlight certain rows in a JXTable by attaching * Highlighters in the {@link #setHighlighters(HighlighterPipeline)}method. An * example would be a Highlighter that colors alternate rows in the table for * readability; AlternateRowHighlighter does this. Again, like Filters, * Highlighters can be chained together in a HighlighterPipeline to achieve more * interesting effects. * * <p> * You can resize all columns, selected columns, or a single column using the * methods like {@link #packAll()}. Packing combines several other aspects of a * JXTable. If horizontal scrolling is enabled using * {@link #setHorizontalScrollEnabled(boolean)}, then the scrollpane will allow * the table to scroll right-left, and columns will be sized to their preferred * size. To control the preferred sizing of a column, you can provide a * prototype value for the column in the TableColumnExt using * {@link TableColumnExt#setPrototypeValue(Object)}. The prototype is used as * an indicator of the preferred size of the column. This can be useful if some * data in a given column is very long, but where the resize algorithm would * normally not pick this up. * * <p> * Last, you can also provide searches on a JXTable using the search methods. * * @author Ramesh Gupta * @author Amy Fowler * @author Mark Davidson * @author Jeanette Winzenburg */ public class JXTable extends JTable { //implements Searchable { /** * Constant string for horizontal scroll actions, used in JXTable's Action * Map. */ public static final String HORIZONTALSCROLL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "horizontalScroll"; /** Constant string for packing all columns, used in JXTable's Action Map. */ public static final String PACKALL_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packAll"; /** * Constant string for packing selected columns, used in JXTable's Action * Map. */ public static final String PACKSELECTED_ACTION_COMMAND = ColumnControlButton.COLUMN_CONTROL_MARKER + "packSelected"; /** The prefix marker to find component related properties in the resourcebundle. */ public static final String UIPREFIX = "JXTable."; /** key for client property to use SearchHighlighter as match marker. */ public static final String MATCH_HIGHLIGHTER = "match.highlighter"; static { // Hack: make sure the resource bundle is loaded LookAndFeelAddons.getAddon(); } /** The FilterPipeline for the table. */ protected FilterPipeline filters = null; /** The HighlighterPipeline for the table. */ protected HighlighterPipeline highlighters = null; /** The ComponentAdapter for model data access. */ protected ComponentAdapter dataAdapter; /** The handler for mapping view/model coordinates of row selection. */ private Selection selection; /** flag to indicate if table is interactively sortable. */ private boolean sortable; /** future - enable/disable autosort on cell updates not used */ // private boolean automaticSortDisabled; /** Listens for changes from the filters. */ private PipelineListener pipelineListener; /** Listens for changes from the highlighters. */ private ChangeListener highlighterChangeListener; /** the factory to use for column creation and configuration. */ private ColumnFactory columnFactory; /** The default number of visible rows (in a ScrollPane). */ private int visibleRowCount = 18; private RowSizing rowSizing; private Field rowModelField; private boolean rowHeightEnabled; /** * flag to indicate if the column control is visible. */ private boolean columnControlVisible; /** * ScrollPane's original vertical scroll policy. If the columnControl is * visible the policy is set to ALWAYS. */ private int verticalScrollPolicy; /** * A button that allows the user to select which columns to display, and * which to hide */ private JComponent columnControlButton; /** * Mouse/Motion/Listener keeping track of mouse moved in cell coordinates. */ private RolloverProducer rolloverProducer; /** * RolloverController: listens to cell over events and repaints * entered/exited rows. */ private LinkController linkController; /** field to store the autoResizeMode while interactively setting * horizontal scrollbar to visible. */ private int oldAutoResizeMode; /** temporary hack: rowheight will be internally adjusted to font size * on instantiation and in updateUI if * the height has not been set explicitly by the application. */ protected boolean isXTableRowHeightSet; protected Searchable searchable; /** Instantiates a JXTable with a default table model, no data. */ public JXTable() { init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm) { super(dm); init(); } /** * Instantiates a JXTable with a specific table model. * * @param dm * The model to use. */ public JXTable(TableModel dm, TableColumnModel cm) { super(dm, cm); init(); } /** * Instantiates a JXTable with a specific table model, column model, and * selection model. * * @param dm * The table model to use. * @param cm * The colomn model to use. * @param sm * The list selection model to use. */ public JXTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) { super(dm, cm, sm); init(); } /** * Instantiates a JXTable for a given number of columns and rows. * * @param numRows * Count of rows to accomodate. * @param numColumns * Count of columns to accomodate. */ public JXTable(int numRows, int numColumns) { super(numRows, numColumns); init(); } /** * Instantiates a JXTable with data in a vector or rows and column names. * * @param rowData * Row data, as a Vector of Objects. * @param columnNames * Column names, as a Vector of Strings. */ public JXTable(Vector rowData, Vector columnNames) { super(rowData, columnNames); init(); } /** * Instantiates a JXTable with data in a array or rows and column names. * * @param rowData * Row data, as a two-dimensional Array of Objects (by row, for * column). * @param columnNames * Column names, as a Array of Strings. */ public JXTable(Object[][] rowData, Object[] columnNames) { super(rowData, columnNames); init(); } /** Initializes the table for use. */ protected void init() { setSortable(true); // guarantee getFilters() to return != null setFilters(null); initActionsAndBindings(); // instantiate row height depending on font size updateRowHeightUI(false); } /** * Property to enable/disable rollover support. This can be enabled to show * "live" rollover behaviour, f.i. the cursor over LinkModel cells. Default * is disabled. If using a RolloverHighlighter on the table, this should be * set to true. * * @param rolloverEnabled */ public void setRolloverEnabled(boolean rolloverEnabled) { boolean old = isRolloverEnabled(); if (rolloverEnabled == old) return; if (rolloverEnabled) { rolloverProducer = new RolloverProducer(); addMouseListener(rolloverProducer); addMouseMotionListener(rolloverProducer); linkController = new LinkController(); addPropertyChangeListener(linkController); } else { removeMouseListener(rolloverProducer); removeMouseMotionListener(rolloverProducer); rolloverProducer = null; removePropertyChangeListener(linkController); linkController = null; } firePropertyChange("rolloverEnabled", old, isRolloverEnabled()); } /** * Returns the rolloverEnabled property. * * @return <code>true</code> if rollover is enabled */ public boolean isRolloverEnabled() { return rolloverProducer != null; } /** * If the default editor for LinkModel.class is of type LinkRenderer enables * link visiting with the given linkVisitor. As a side-effect the rollover * property is set to true. * * @param linkVisitor */ public void setDefaultLinkVisitor(ActionListener linkVisitor) { TableCellEditor renderer = getDefaultEditor(LinkModel.class); if (renderer instanceof LinkRenderer) { ((LinkRenderer) renderer).setVisitingDelegate(linkVisitor); } setRolloverEnabled(true); } //--------------------------------- ColumnControl /** * overridden to addionally configure the upper right corner of an enclosing * scrollpane with the ColumnControl. */ protected void configureEnclosingScrollPane() { super.configureEnclosingScrollPane(); configureColumnControl(); configureViewportBackground(); } /** * set's the viewports background to this.background. PENDING: need to * repeat on background changes to this! * */ protected void configureViewportBackground() { Container p = getParent(); if (p instanceof JViewport) { p.setBackground(getBackground()); } } /** * configure the upper right corner of an enclosing scrollpane with/o the * ColumnControl, depending on setting of columnControl visibility flag. * * PENDING: should choose corner depending on component orientation. */ private void configureColumnControl() { Container p = getParent(); if (p instanceof JViewport) { Container gp = p.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; // Make certain we are the viewPort's view and not, for // example, the rowHeaderView of the scrollPane - // an implementor of fixed columns might do this. JViewport viewport = scrollPane.getViewport(); if (viewport == null || viewport.getView() != this) { return; } if (isColumnControlVisible()) { verticalScrollPolicy = scrollPane .getVerticalScrollBarPolicy(); scrollPane.setCorner(JScrollPane.UPPER_TRAILING_CORNER, getColumnControl()); scrollPane .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); } else { scrollPane .setVerticalScrollBarPolicy(verticalScrollPolicy == 0 ? ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED : verticalScrollPolicy); try { scrollPane.setCorner(JScrollPane.UPPER_RIGHT_CORNER, null); } catch (Exception ex) { // Ignore spurious exception thrown by JScrollPane. This // is a Swing bug! } } } } } /** * returns visibility flag of column control. * <p> * * Note: if the table is not inside a JScrollPane the column control is not * shown even if this returns true. In this case it's the responsibility of * the client code to actually show it. * * @return */ public boolean isColumnControlVisible() { return columnControlVisible; } /** * returns the component for column control. * * @return */ public JComponent getColumnControl() { if (columnControlButton == null) { columnControlButton = new ColumnControlButton(this, new ColumnControlIcon()); } return columnControlButton; } /** * bound property to flag visibility state of column control. * * @param showColumnControl */ public void setColumnControlVisible(boolean showColumnControl) { boolean old = columnControlVisible; this.columnControlVisible = showColumnControl; // JW: hacking issue #38(swingx) to initially add all columns // if (showColumnControl) { // getColumnControl(); // } configureColumnControl(); firePropertyChange("columnControlVisible", old, columnControlVisible); } //--------------------- actions /** * A small class which dispatches actions. TODO: Is there a way that we can * make this static? JW: I hate those if constructs... we are in OO-land! */ private class Actions extends UIAction { Actions(String name) { super(name); } public void actionPerformed(ActionEvent evt) { if ("print".equals(getName())) { try { print(); } catch (PrinterException ex) { // REMIND(aim): should invoke pluggable application error // handler ex.printStackTrace(); } } else if ("find".equals(getName())) { find(); } } } private void initActionsAndBindings() { // Register the actions that this class can handle. ActionMap map = getActionMap(); map.put("print", new Actions("print")); map.put("find", new Actions("find")); map.put(PACKALL_ACTION_COMMAND, createPackAllAction()); map.put(PACKSELECTED_ACTION_COMMAND, createPackSelectedAction()); map.put(HORIZONTALSCROLL_ACTION_COMMAND, createHorizontalScrollAction()); // this should be handled by the LF! KeyStroke findStroke = KeyStroke.getKeyStroke("control F"); getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(findStroke, "find"); } /** Creates an Action for horizontal scrolling. */ private Action createHorizontalScrollAction() { String actionName = getUIString(HORIZONTALSCROLL_ACTION_COMMAND); BoundAction action = new BoundAction(actionName, HORIZONTALSCROLL_ACTION_COMMAND); action.setStateAction(); action.registerCallback(this, "setHorizontalScrollEnabled"); action.setSelected(isHorizontalScrollEnabled()); return action; } private String getUIString(String key) { String text = UIManager.getString(UIPREFIX + key); return text != null ? text : key; } /** Creates an Action for packing selected columns. */ private Action createPackSelectedAction() { String text = getUIString(PACKSELECTED_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKSELECTED_ACTION_COMMAND); action.registerCallback(this, "packSelected"); action.setEnabled(getSelectedColumnCount() > 0); return action; } /** Creates an Action for packing all columns. */ private Action createPackAllAction() { String text = getUIString(PACKALL_ACTION_COMMAND); BoundAction action = new BoundAction(text, PACKALL_ACTION_COMMAND); action.registerCallback(this, "packAll"); return action; } //------------------ bound action callback methods /** * This resizes all columns to fit the viewport; if horizontal scrolling is * enabled, all columns will get their preferred width. This can be * triggered by the "packAll" BoundAction on the table as well. */ public void packAll() { packTable(getDefaultPackMargin()); } /** * This resizes selected columns to fit the viewport; if horizontal * scrolling is enabled, selected columns will get their preferred width. * This can be triggered by the "packSelected" BoundAction on the table as * well. */ public void packSelected() { int selected = getSelectedColumn(); if (selected >= 0) { packColumn(selected, getDefaultPackMargin()); } } /** * Controls horizontal scrolling in the viewport, and works in coordination * with column sizing. * * @param enabled * If true, the scrollpane will allow the table to scroll * horizontally, and columns will resize to their preferred * width. If false, columns will resize to fit the viewport. */ public void setHorizontalScrollEnabled(boolean enabled) { if (enabled == (isHorizontalScrollEnabled())) return; if (enabled) { oldAutoResizeMode = getAutoResizeMode(); setAutoResizeMode(AUTO_RESIZE_OFF); } else { setAutoResizeMode(oldAutoResizeMode); } } /** Returns the current setting for horizontal scrolling. */ private boolean isHorizontalScrollEnabled() { return getAutoResizeMode() == AUTO_RESIZE_OFF; } /** Returns the default margin for packing columns. */ private int getDefaultPackMargin() { return 4; } /** Notifies the table that a new column has been selected. * overridden to update the enabled state of the packSelected * action. */ public void columnSelectionChanged(ListSelectionEvent e) { super.columnSelectionChanged(e); if (e.getValueIsAdjusting()) return; Action packSelected = getActionMap().get(PACKSELECTED_ACTION_COMMAND); if ((packSelected != null)) {// && (e.getSource() instanceof // ListSelectionModel)){ packSelected.setEnabled(!((ListSelectionModel) e.getSource()) .isSelectionEmpty()); } } /** * overridden to update the show horizontal scrollbar action's * selected state. */ public void setAutoResizeMode(int mode) { super.setAutoResizeMode(mode); Action showHorizontal = getActionMap().get( HORIZONTALSCROLL_ACTION_COMMAND); if (showHorizontal instanceof BoundAction) { ((BoundAction) showHorizontal) .setSelected(isHorizontalScrollEnabled()); } } //------------------------ override super because of filter-awareness /** * Returns the row count in the table; if filters are applied, this is the * filtered row count. */ @Override public int getRowCount() { // RG: If there are no filters, call superclass version rather than // accessing model directly return filters == null ? // return ((filters == null) || !filters.isAssigned()) ? super.getRowCount() : filters.getOutputSize(); } public boolean isHierarchical(int column) { return false; } /** * Convert row index from view coordinates to model coordinates accounting * for the presence of sorters and filters. * * @param row * row index in view coordinates * @return row index in model coordinates */ public int convertRowIndexToModel(int row) { return getFilters().convertRowIndexToModel(row); } /** * Convert row index from model coordinates to view coordinates accounting * for the presence of sorters and filters. * * @param row * row index in model coordinates * @return row index in view coordinates */ public int convertRowIndexToView(int row) { return getFilters().convertRowIndexToView(row); } /** * {@inheritDoc} */ public Object getValueAt(int row, int column) { return getModel().getValueAt(convertRowIndexToModel(row), convertColumnIndexToModel(column)); // return getFilters().getValueAt(row, convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public void setValueAt(Object aValue, int row, int column) { getModel().setValueAt(aValue, convertRowIndexToModel(row), convertColumnIndexToModel(column)); // getFilters().setValueAt(aValue, row, convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public boolean isCellEditable(int row, int column) { return getModel().isCellEditable(convertRowIndexToModel(row), convertColumnIndexToModel(column)); // return getFilters().isCellEditable(row, // convertColumnIndexToModel(column)); } /** * {@inheritDoc} */ public void setModel(TableModel newModel) { // JW: need to clear here because super.setModel // calls tableChanged... // fixing #173 // clearSelection(); getSelection().lock(); super.setModel(newModel); // JW: PENDING - needs cleanup, probably much simpler now... // not needed because called in tableChanged // use(filters); } /** ? */ public void tableChanged(TableModelEvent e) { // make Selection deaf ... super doesn't know about row // mapping and sets rowSelection in model coordinates // causing complete confusion. getSelection().lock(); super.tableChanged(e); updateSelectionAndRowModel(e); use(filters); // JW: this is for the sake of the very first call to setModel, done in // super on instantiation - at that time filters cannot be set // because they will be re-initialized to null // ... arrrgggg // if (filters != null) { // filters.flush(); // will call updateOnFilterContentChanged() // } else { // // not really needed... we reach this branch only on the // // very first super.setModel() // getSelection().restoreSelection(); // } } /** * reset model selection coordinates in Selection after * model events. * * @param e */ private void updateSelectionAndRowModel(TableModelEvent e) { // c&p from JTable // still missing: checkLeadAnchor if (e.getType() == TableModelEvent.INSERT) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } // Adjust the selection to account for the new rows. int length = end - start + 1; getSelection().insertIndexInterval(start, length, true); getRowSizing().insertIndexInterval(start, length, getRowHeight()); } else if (e.getType() == TableModelEvent.DELETE) { int start = e.getFirstRow(); int end = e.getLastRow(); if (start < 0) { start = 0; } if (end < 0) { end = getModel().getRowCount() - 1; } int deletedCount = end - start + 1; int previousRowCount = getModel().getRowCount() + deletedCount; // Adjust the selection to account for the new rows getSelection().removeIndexInterval(start, end); getRowSizing().removeIndexInterval(start, deletedCount); } else if (getSelectionModel().isSelectionEmpty()) { // possibly got a dataChanged or structureChanged // super will have cleared selection getSelection().clearModelSelection(); getRowSizing().clearModelSizes(); getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); } } private Selection getSelection() { if (selection == null) { selection = new Selection(filters, getSelectionModel()); } return selection; } //----------------------------- filters /** Returns the FilterPipeline for the table. */ public FilterPipeline getFilters() { // PENDING: this is guaranteed to be != null because // init calls setFilters(null) which enforces an empty // pipeline return filters; } /** * setModel() and setFilters() may be called in either order. * * @param pipeline */ private void use(FilterPipeline pipeline) { if (pipeline != null) { // check JW: adding listener multiple times (after setModel)? if (initialUse(pipeline)) { pipeline.addPipelineListener(getFilterPipelineListener()); pipeline.assign(getComponentAdapter()); } else { pipeline.flush(); } } } /** * @return true is not yet used in this JXTable, false otherwise */ private boolean initialUse(FilterPipeline pipeline) { if (pipelineListener == null) return true; PipelineListener[] l = pipeline.getPipelineListeners(); for (int i = 0; i < l.length; i++) { if (pipelineListener.equals(l[i])) return false; } return true; } /** Sets the FilterPipeline for filtering table rows. */ public void setFilters(FilterPipeline pipeline) { FilterPipeline old = getFilters(); Sorter sorter = null; if (old != null) { old.removePipelineListener(pipelineListener); sorter = old.getSorter(); } if (pipeline == null) { pipeline = new FilterPipeline(); } filters = pipeline; filters.setSorter(sorter); getSelection().setFilters(filters); getRowSizing().setFilters(filters); use(filters); } /** returns the listener for changes in filters. */ protected PipelineListener getFilterPipelineListener() { if (pipelineListener == null) { pipelineListener = createPipelineListener(); } return pipelineListener; } /** creates the listener for changes in filters. */ protected PipelineListener createPipelineListener() { PipelineListener l = new PipelineListener() { public void contentsChanged(PipelineEvent e) { updateOnFilterContentChanged(); } }; return l; } /** * method called on change notification from filterpipeline. */ protected void updateOnFilterContentChanged() { // Force private rowModel in JTable to null; // adminSetRowHeight(getRowHeight()); revalidate(); repaint(); } //-------------------------------- sorting /** * Sets &quot;sortable&quot; property indicating whether or not this table * supports sortable columns. If <code>sortable</code> is * <code>true</code> then sorting will be enabled on all columns whose * <code>sortable</code> property is <code>true</code>. If * <code>sortable</code> is <code>false</code> then sorting will be * disabled for all columns, regardless of each column's individual * <code>sorting</code> property. The default is <code>true</code>. * * @see TableColumnExt#isSortable() * @param sortable * boolean indicating whether or not this table supports sortable * columns */ public void setSortable(boolean sortable) { if (sortable == isSortable()) return; this.sortable = sortable; if (!isSortable()) resetSorter(); firePropertyChange("sortable", !sortable, sortable); // JW @todo: this is a hack! // check if the sortable/not sortable toggling still works with the // sorter in pipeline // if (getInteractiveSorter() != null) { // updateOnFilterContentChanged(); // } // } /** Returns true if the table is sortable. */ public boolean isSortable() { return sortable; } // public void setAutomaticSort(boolean automaticEnabled) { // this.automaticSortDisabled = !automaticEnabled; // // } // // public boolean isAutomaticSort() { // return !automaticSortDisabled; // } private void setInteractiveSorter(Sorter sorter) { // this check is for the sake of the very first call after instantiation if (filters == null) return; getFilters().setSorter(sorter); } private Sorter getInteractiveSorter() { // this check is for the sake of the very first call after instantiation if (filters == null) return null; return getFilters().getSorter(); } /** * Removes the interactive sorter. * Used by headerListener. * */ protected void resetSorter() { // JW PENDING: think about notification instead of manual repaint. setInteractiveSorter(null); getTableHeader().repaint(); } public void columnRemoved(TableColumnModelEvent e) { // old problem: need access to removed column // to get hold of removed modelIndex // to remove interactive sorter if any // no way // int modelIndex = convertColumnIndexToModel(e.getFromIndex()); updateSorterAfterColumnRemoved(); super.columnRemoved(e); } /** * guarantee that the interactive sorter is removed if its column * is removed. * */ private void updateSorterAfterColumnRemoved() { // bloody hack: get sorter and check if there's a column with it // available Sorter sorter = getInteractiveSorter(); if (sorter != null) { int sorterColumn = sorter.getColumnIndex(); List columns = getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); if (column.getModelIndex() == sorterColumn) return; } // didn't find a column with the sorter's index - remove resetSorter(); } } /** * * request to sort the column at columnIndex in view coordinates. if there * is already an interactive sorter for this column it's sort order is * reversed. Otherwise the columns sorter is used as is. * Used by headerListener. * */ protected void setSorter(int columnIndex) { if (!isSortable()) return; Sorter sorter = getInteractiveSorter(); if ((sorter != null) && (sorter.getColumnIndex() == convertColumnIndexToModel(columnIndex))) { sorter.toggle(); } else { TableColumnExt column = getColumnExt(columnIndex); getFilters().setSorter(column != null ? column.getSorter() : null); } } /** * Returns the interactive sorter if it is set from the given column. * Used by ColumnHeaderRenderer.getTableCellRendererComponent(). * * @param columnIndex the column index in view coordinates. * @return the interactive sorter if matches the column or null. */ public Sorter getSorter(int columnIndex) { Sorter sorter = getInteractiveSorter(); return sorter == null ? null : sorter.getColumnIndex() == convertColumnIndexToModel(columnIndex) ? sorter : null; } //---------------------- enhanced TableColumn/Model support /** * Remove all columns, make sure to include hidden. * */ protected void removeColumns() { /** * @todo promote this method to superclass, and change * createDefaultColumnsFromModel() to call this method */ List columns = getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { getColumnModel().removeColumn((TableColumn) iter.next()); } } /** * returns a list of all visible TableColumns. * * @return */ public List getColumns() { return Collections.list(getColumnModel().getColumns()); } /** * returns a list of TableColumns including hidden if the parameter is set * to true. * * @param includeHidden * @return */ public List getColumns(boolean includeHidden) { if (includeHidden && (getColumnModel() instanceof TableColumnModelExt)) { return ((TableColumnModelExt) getColumnModel()) .getColumns(includeHidden); } return getColumns(); } /** * returns the number of TableColumns including hidden if the parameter is set * to true. * * @param includeHidden * @return */ public int getColumnCount(boolean includeHidden) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnCount(includeHidden); } return getColumnCount(); } /** * reorders the columns in the sequence given array. Logical names that do * not correspond to any column in the model will be ignored. Columns with * logical names not contained are added at the end. * * @param columnNames * array of logical column names */ public void setColumnSequence(Object[] identifiers) { List columns = getColumns(true); Map map = new HashMap(); for (Iterator iter = columns.iterator(); iter.hasNext();) { // PENDING: handle duplicate identifiers ... TableColumn column = (TableColumn) iter.next(); map.put(column.getIdentifier(), column); getColumnModel().removeColumn(column); } for (int i = 0; i < identifiers.length; i++) { TableColumn column = (TableColumn) map.get(identifiers[i]); if (column != null) { getColumnModel().addColumn(column); columns.remove(column); } } for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); getColumnModel().addColumn(column); } } /** * Returns the <code>TableColumnExt</code> object for the column in the * table whose identifier is equal to <code>identifier</code>, when * compared using <code>equals</code>. The returned TableColumn is * guaranteed to be part of the current ColumnModel but may be hidden, that * is * * <pre> <code> * TableColumnExt column = table.getColumnExt(id); * if (column != null) { * int viewIndex = table.convertColumnIndexToView(column.getModelIndex()); * assertEquals(column.isVisible(), viewIndex &gt;= 0); * } * </code> </pre> * * @param identifier * the identifier object * * @return the <code>TableColumnExt</code> object that matches the * identifier or null if none is found. */ public TableColumnExt getColumnExt(Object identifier) { if (getColumnModel() instanceof TableColumnModelExt) { return ((TableColumnModelExt) getColumnModel()) .getColumnExt(identifier); } else { // PENDING: not tested! try { TableColumn column = getColumn(identifier); if (column instanceof TableColumnExt) { return (TableColumnExt) column; } } catch (Exception e) { // TODO: handle exception } } return null; } /** * Returns the <code>TableColumnExt</code> object for the column in the * table whose column index is equal to <code>viewColumnIndex</code> * * @param viewColumnIndex * index of the column with the object in question * * @return the <code>TableColumnExt</code> object that matches the column * index * @exception IllegalArgumentException * if no <code>TableColumn</code> has this identifier */ public TableColumnExt getColumnExt(int viewColumnIndex) { return (TableColumnExt) getColumnModel().getColumn(viewColumnIndex); } public void createDefaultColumnsFromModel() { TableModel model = getModel(); if (model != null) { // Create new columns from the data model info // Note: it's critical to create the new columns before // deleting the old ones. Why? // JW PENDING: the reason is somewhere in the early forums - search! int modelColumnCount = model.getColumnCount(); TableColumn newColumns[] = new TableColumn[modelColumnCount]; for (int i = 0; i < newColumns.length; i++) { newColumns[i] = createAndConfigureColumn(model, i); } // Remove any current columns removeColumns(); // Now add the new columns to the column model for (int i = 0; i < newColumns.length; i++) { addColumn(newColumns[i]); } } } protected TableColumn createAndConfigureColumn(TableModel model, int modelColumn) { return getColumnFactory().createAndConfigureTableColumn(model, modelColumn); } protected ColumnFactory getColumnFactory() { if (columnFactory == null) { columnFactory = ColumnFactory.getInstance(); } return columnFactory; } //----------------------- delegating methods?? from super /** * Returns the margin between columns. * * @return the margin between columns */ public int getColumnMargin() { return getColumnModel().getColumnMargin(); } /** * Sets the margin between columns. * * @param value * margin between columns; must be greater than or equal to zero. */ public void setColumnMargin(int value) { getColumnModel().setColumnMargin(value); } /** * Returns the selection mode used by this table's selection model. * * @return the selection mode used by this table's selection model */ public int getSelectionMode() { return getSelectionModel().getSelectionMode(); } //----------------------- Search support /** Opens the find widget for the table. */ private void find() { SearchFactory.getInstance().showFindInput(this, getSearchable()); // if (dialog == null) { // dialog = new JXFindDialog(); // } // dialog.setSearchable(this); // dialog.setVisible(true); } /** * * @returns a not-null Searchable for this editor. */ public Searchable getSearchable() { if (searchable == null) { searchable = new TableSearchable(); } return searchable; } /** * sets the Searchable for this editor. If null, a default * searchable will be used. * * @param searchable */ public void setSearchable(Searchable searchable) { this.searchable = searchable; } public class TableSearchable implements Searchable { /** * Performs a search across the table using String that represents a * regex pattern; {@link java.util.regex.Pattern}. All columns and all * rows are searched; the row id of the first match is returned. */ public int search(String searchString) { return search(searchString, -1); } /** * Performs a search on a column using String that represents a regex * pattern; {@link java.util.regex.Pattern}. The specified column * searched; the row id of the first match is returned. */ public int search(String searchString, int columnIndex) { if (searchString != null) { return search(Pattern.compile(searchString, 0), columnIndex); } return -1; } /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. All columns and all rows are * searched; the row id of the first match is returned. */ public int search(Pattern pattern) { return search(pattern, -1); } /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. starting at a given row. All * columns and all rows are searched; the row id of the first match is * returned. */ public int search(Pattern pattern, int startIndex) { return search(pattern, startIndex, false); } // Save the last column with the match. // TODO (JW) - lastCol should either be a valid column index or < 0 private int lastCol = 0; private SearchHighlighter searchHighlighter; /** * Performs a search across the table using a * {@link java.util.regex.Pattern}. starting at a given row. All * columns and all rows are searched; the row id of the first match is * returned. * * @param startIndex * row to start search * @param backwards * whether to start at the last row and search up to the * first. * @return row with a match. */ public int search(Pattern pattern, int startIndex, boolean backwards) { int matchingRow = searchMatchingRow(pattern, startIndex, backwards); moveMatchMarker(pattern, matchingRow, lastCol); return matchingRow; } /** * returns/updates the matching row/column indices. * * @param pattern * @param startIndex * @param backwards * @return */ protected int searchMatchingRow(Pattern pattern, int startIndex, boolean backwards) { if (pattern == null) { lastCol = 0; return -1; } int rows = getRowCount(); int endCol = getColumnCount(); int matchRow = -1; if (backwards == true) { if (startIndex < 0) startIndex = rows; int startRow = startIndex - 1; for (int r = startRow; r >= 0 && matchRow == -1; r--) { for (int c = endCol - 1; c >= 0; c--) { Object value = getValueAt(r, c); if ((value != null) && pattern.matcher(value.toString()).find()) { matchRow = r; lastCol = c; break; // No need to search other columns } } if (matchRow == -1) { lastCol = endCol; } } } else { int startRow = startIndex + 1; for (int r = startRow; r < rows && matchRow == -1; r++) { for (int c = lastCol; c < endCol; c++) { Object value = getValueAt(r, c); if ((value != null) && pattern.matcher(value.toString()).find()) { matchRow = r; lastCol = c; break; // No need to search other columns } } if (matchRow == -1) { lastCol = 0; } } } return matchRow; } protected void moveMatchMarker(Pattern pattern, int row, int column) { if (markByHighlighter()) { Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } ensureInsertedSearchHighlighters(); // TODO (JW) - cleanup SearchHighlighter state management if ((row >= 0) && (column >= 0)) { getSearchHighlighter().setPattern(pattern); int modelColumn = convertColumnIndexToModel(column); getSearchHighlighter().setHighlightCell(row, modelColumn); } else { getSearchHighlighter().setPattern(null); } } else { // use selection changeSelection(row, column, false, false); if (!getAutoscrolls()) { // scrolling not handled by moving selection Rectangle cellRect = getCellRect(row, column, true); if (cellRect != null) { scrollRectToVisible(cellRect); } } } } private boolean markByHighlighter() { return Boolean.TRUE.equals(getClientProperty(MATCH_HIGHLIGHTER)); } private SearchHighlighter getSearchHighlighter() { if (searchHighlighter == null) { searchHighlighter = createSearchHighlighter(); } return searchHighlighter; } private void ensureInsertedSearchHighlighters() { if (getHighlighters() == null) { setHighlighters(new HighlighterPipeline(new Highlighter[] {getSearchHighlighter()})); } else if (!isInPipeline(getSearchHighlighter())){ getHighlighters().addHighlighter(getSearchHighlighter()); } } private boolean isInPipeline(PatternHighlighter searchHighlighter) { Highlighter[] inPipeline = getHighlighters().getHighlighters(); for (int i = 0; i < inPipeline.length; i++) { if (searchHighlighter.equals(inPipeline[i])) return true; } return false; } protected SearchHighlighter createSearchHighlighter() { return new SearchHighlighter(); } } //-------------------------------- sizing support /** ? */ public void setVisibleRowCount(int visibleRowCount) { this.visibleRowCount = visibleRowCount; } /** ? */ public int getVisibleRowCount() { return visibleRowCount; } public Dimension getPreferredScrollableViewportSize() { Dimension prefSize = super.getPreferredScrollableViewportSize(); // JTable hardcodes this to 450 X 400, so we'll calculate it // based on the preferred widths of the columns and the // visibleRowCount property instead... if (prefSize.getWidth() == 450 && prefSize.getHeight() == 400) { TableColumnModel columnModel = getColumnModel(); int columnCount = columnModel.getColumnCount(); int w = 0; for (int i = 0; i < columnCount; i++) { TableColumn column = columnModel.getColumn(i); initializeColumnPreferredWidth(column); w += column.getPreferredWidth(); } prefSize.width = w; JTableHeader header = getTableHeader(); // remind(aim): height is still off...??? int rowCount = getVisibleRowCount(); prefSize.height = rowCount * getRowHeight() + (header != null ? header.getPreferredSize().height : 0); setPreferredScrollableViewportSize(prefSize); } return prefSize; } /** * Packs all the columns to their optimal size. Works best with auto * resizing turned off. * * Contributed by M. Hillary (Issue #60) * * @param margin * the margin to apply to each column. */ public void packTable(int margin) { for (int c = 0; c < getColumnCount(); c++) packColumn(c, margin, -1); } /** * Packs an indivudal column in the table. Contributed by M. Hillary (Issue * #60) * * @param column * The Column index to pack in View Coordinates * @param margin * The Margin to apply to the column width. */ public void packColumn(int column, int margin) { packColumn(column, margin, -1); } /** * Packs an indivual column in the table to less than or equal to the * maximum witdth. If maximun is -1 then the column is made as wide as it * needs. Contributed by M. Hillary (Issue #60) * * @param column * The Column index to pack in View Coordinates * @param margin * The margin to apply to the column * @param max * The maximum width the column can be resized to. -1 mean any * size. */ public void packColumn(int column, int margin, int max) { getColumnFactory().packColumn(this, getColumnExt(column), margin, max); } /** * Initialize the preferredWidth of the specified column based on the * column's prototypeValue property. If the column is not an instance of * <code>TableColumnExt</code> or prototypeValue is <code>null</code> * then the preferredWidth is left unmodified. * * @see org.jdesktop.swingx.table.TableColumnExt#setPrototypeValue * @param column * TableColumn object representing view column */ protected void initializeColumnPreferredWidth(TableColumn column) { if (column instanceof TableColumnExt) { getColumnFactory().configureColumnWidths(this, (TableColumnExt) column); } } //----------------------------------- uniform data model access protected ComponentAdapter getComponentAdapter() { if (dataAdapter == null) { dataAdapter = new TableAdapter(this); } return dataAdapter; } protected static class TableAdapter extends ComponentAdapter { private final JXTable table; /** * Constructs a <code>TableDataAdapter</code> for the specified target * component. * * @param component * the target component */ public TableAdapter(JXTable component) { super(component); table = component; } /** * Typesafe accessor for the target component. * * @return the target component as a {@link javax.swing.JTable} */ public JXTable getTable() { return table; } public String getColumnName(int columnIndex) { // TableColumnModel columnModel = table.getColumnModel(); // if (columnModel == null) { // return "Column " + columnIndex; // } // int viewColumn = modelToView(columnIndex); // TableColumn column = null; // if (viewColumn >= 0) { // column = columnModel.getColumn(viewColumn); // } TableColumn column = getColumnByModelIndex(columnIndex); return column == null ? "" : column.getHeaderValue().toString(); } protected TableColumn getColumnByModelIndex(int modelColumn) { List columns = table.getColumns(true); for (Iterator iter = columns.iterator(); iter.hasNext();) { TableColumn column = (TableColumn) iter.next(); if (column.getModelIndex() == modelColumn) { return column; } } return null; } public String getColumnIdentifier(int columnIndex) { TableColumn column = getColumnByModelIndex(columnIndex); // int viewColumn = modelToView(columnIndex); // if (viewColumn >= 0) { // table.getColumnExt(viewColumn).getIdentifier(); // } Object identifier = column != null ? column.getIdentifier() : null; return identifier != null ? identifier.toString() : null; } public int getColumnCount() { return table.getModel().getColumnCount(); } public int getRowCount() { return table.getModel().getRowCount(); } /** * {@inheritDoc} */ public Object getValueAt(int row, int column) { // RG: eliminate superfluous back-and-forth conversions return table.getModel().getValueAt(row, column); } public void setValueAt(Object aValue, int row, int column) { // RG: eliminate superfluous back-and-forth conversions table.getModel().setValueAt(aValue, row, column); } public boolean isCellEditable(int row, int column) { // RG: eliminate superfluous back-and-forth conversions return table.getModel().isCellEditable(row, column); } public boolean isTestable(int column) { return getColumnByModelIndex(column) != null; } //-------------------------- accessing view state/values public Object getFilteredValueAt(int row, int column) { return table.getValueAt(row, modelToView(column)); // in view coordinates } /** * {@inheritDoc} */ public boolean isSelected() { return table.isCellSelected(row, column); } /** * {@inheritDoc} */ public boolean hasFocus() { boolean rowIsLead = (table.getSelectionModel() .getLeadSelectionIndex() == row); boolean colIsLead = (table.getColumnModel().getSelectionModel() .getLeadSelectionIndex() == column); return table.isFocusOwner() && (rowIsLead && colIsLead); } /** * {@inheritDoc} */ public int modelToView(int columnIndex) { return table.convertColumnIndexToView(columnIndex); } /** * {@inheritDoc} */ public int viewToModel(int columnIndex) { return table.convertColumnIndexToModel(columnIndex); } } //--------------------- managing renderers/editors /** Returns the HighlighterPipeline assigned to the table, null if none. */ public HighlighterPipeline getHighlighters() { return highlighters; } /** * Assigns a HighlighterPipeline to the table. bound property. */ public void setHighlighters(HighlighterPipeline pipeline) { HighlighterPipeline old = getHighlighters(); if (old != null) { old.removeChangeListener(getHighlighterChangeListener()); } highlighters = pipeline; if (highlighters != null) { highlighters.addChangeListener(getHighlighterChangeListener()); } firePropertyChange("highlighters", old, getHighlighters()); } /** * returns the ChangeListener to use with highlighters. Creates one if * necessary. * * @return != null */ private ChangeListener getHighlighterChangeListener() { if (highlighterChangeListener == null) { highlighterChangeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { repaint(); } }; } return highlighterChangeListener; } /** * Returns the decorated <code>Component</code> used as a stamp to render * the specified cell. Overrides superclass version to provide support for * cell decorators. * * @param renderer * the <code>TableCellRenderer</code> to prepare * @param row * the row of the cell to render, where 0 is the first row * @param column * the column of the cell to render, where 0 is the first column * @return the decorated <code>Component</code> used as a stamp to render * the specified cell * @see org.jdesktop.swingx.decorator.Highlighter */ public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { // JW PENDING: testing cadavers ... check if still needed // Object value = getValueAt(row, column); // Class columnClass = getColumnClass(column); // boolean typeclash = !columnClass.isInstance(value); // TableColumn tableColumn = getColumnModel().getColumn(column); // getColumnClass(column); Component stamp = super.prepareRenderer(renderer, row, column); if (highlighters == null) { return stamp; // no need to decorate renderer with highlighters } else { // MUST ALWAYS ACCESS dataAdapter through accessor method!!! ComponentAdapter adapter = getComponentAdapter(); adapter.row = row; adapter.column = column; return highlighters.apply(stamp, adapter); } } /** * Returns a new instance of the default renderer for the specified class. * This differs from <code>getDefaultRenderer()</code> in that it returns * a <b>new </b> instance each time so that the renderer may be set and * customized on a particular column. * * @param columnClass * Class of value being rendered * @return TableCellRenderer instance which renders values of the specified * type */ public TableCellRenderer getNewDefaultRenderer(Class columnClass) { TableCellRenderer renderer = getDefaultRenderer(columnClass); if (renderer != null) { try { return (TableCellRenderer) renderer.getClass().newInstance(); } catch (Exception e) { e.printStackTrace(); } } return null; } /** ? */ protected void createDefaultEditors() { super.createDefaultEditors(); setLazyEditor(LinkModel.class, "org.jdesktop.swingx.LinkRenderer"); } /** * Creates default cell renderers for objects, numbers, doubles, dates, * booleans, icons, and links. * THINK: delegate to TableCellRenderers? * */ protected void createDefaultRenderers() { // super.createDefaultRenderers(); // This duplicates JTable's functionality in order to make the renderers // available in getNewDefaultRenderer(); If JTable's renderers either // were public, or it provided a factory for *new* renderers, this would // not be needed defaultRenderersByColumnClass = new UIDefaults(); // Objects setLazyRenderer(Object.class, "javax.swing.table.DefaultTableCellRenderer"); // Numbers setLazyRenderer(Number.class, "org.jdesktop.swingx.JXTable$NumberRenderer"); // Doubles and Floats setLazyRenderer(Float.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); setLazyRenderer(Double.class, "org.jdesktop.swingx.JXTable$DoubleRenderer"); // Dates setLazyRenderer(Date.class, "org.jdesktop.swingx.JXTable$DateRenderer"); // Icons and ImageIcons setLazyRenderer(Icon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); setLazyRenderer(ImageIcon.class, "org.jdesktop.swingx.JXTable$IconRenderer"); // Booleans setLazyRenderer(Boolean.class, "org.jdesktop.swingx.JXTable$BooleanRenderer"); // Other setLazyRenderer(LinkModel.class, "org.jdesktop.swingx.LinkRenderer"); } /** ? */ private void setLazyValue(Hashtable h, Class c, String s) { h.put(c, new UIDefaults.ProxyLazyValue(s)); } /** ? */ private void setLazyRenderer(Class c, String s) { setLazyValue(defaultRenderersByColumnClass, c, s); } /** ? */ private void setLazyEditor(Class c, String s) { setLazyValue(defaultEditorsByColumnClass, c, s); } /* * Default Type-based Renderers: JTable's default table cell renderer * classes are private and JTable:getDefaultRenderer() returns a *shared* * cell renderer instance, thus there is no way for us to instantiate a new * instance of one of its default renderers. So, we must replicate the * default renderer classes here so that we can instantiate them when we * need to create renderers to be set on specific columns. */ public static class NumberRenderer extends DefaultTableCellRenderer { public NumberRenderer() { super(); setHorizontalAlignment(JLabel.RIGHT); } } public static class DoubleRenderer extends NumberRenderer { NumberFormat formatter; public DoubleRenderer() { super(); } public void setValue(Object value) { if (formatter == null) { formatter = NumberFormat.getInstance(); } setText((value == null) ? "" : formatter.format(value)); } } public static class DateRenderer extends DefaultTableCellRenderer { DateFormat formatter; public DateRenderer() { super(); } public void setValue(Object value) { if (formatter == null) { formatter = DateFormat.getDateInstance(); } setText((value == null) ? "" : formatter.format(value)); } } public static class IconRenderer extends DefaultTableCellRenderer { public IconRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); } public void setValue(Object value) { setIcon((value instanceof Icon) ? (Icon) value : null); } } public static class BooleanRenderer extends JCheckBox implements TableCellRenderer { public BooleanRenderer() { super(); setHorizontalAlignment(JLabel.CENTER); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); super.setBackground(table.getSelectionBackground()); } else { setForeground(table.getForeground()); setBackground(table.getBackground()); } setSelected((value != null && ((Boolean) value).booleanValue())); return this; } } //---------------------------- updateUI support /** * bug fix: super doesn't update all renderers/editors. */ public void updateUI() { super.updateUI(); // JW PENDING: update columnControl if (columnControlButton != null) { columnControlButton.updateUI(); } for (Enumeration defaultEditors = defaultEditorsByColumnClass .elements(); defaultEditors.hasMoreElements();) { updateEditorUI(defaultEditors.nextElement()); } for (Enumeration defaultRenderers = defaultRenderersByColumnClass .elements(); defaultRenderers.hasMoreElements();) { updateRendererUI(defaultRenderers.nextElement()); } Enumeration columns = getColumnModel().getColumns(); if (getColumnModel() instanceof TableColumnModelExt) { columns = Collections .enumeration(((TableColumnModelExt) getColumnModel()) .getAllColumns()); } while (columns.hasMoreElements()) { TableColumn column = (TableColumn) columns.nextElement(); updateEditorUI(column.getCellEditor()); updateRendererUI(column.getCellRenderer()); updateRendererUI(column.getHeaderRenderer()); } updateRowHeightUI(true); configureViewportBackground(); } /** ? */ private void updateRowHeightUI(boolean respectRowSetFlag) { if (respectRowSetFlag && isXTableRowHeightSet) return; int minimumSize = getFont().getSize() + 6; int uiSize = UIManager.getInt(UIPREFIX + "rowHeight"); setRowHeight(Math.max(minimumSize, uiSize != 0 ? uiSize : 18)); isXTableRowHeightSet = false; } /** Changes the row height for all rows in the table. */ public void setRowHeight(int rowHeight) { super.setRowHeight(rowHeight); if (rowHeight > 0) { isXTableRowHeightSet = true; } getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); } public void setRowHeight(int row, int rowHeight) { if (!isRowHeightEnabled()) return; super.setRowHeight(row, rowHeight); getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); resizeAndRepaint(); } /** * sets enabled state of individual rowHeight support. The default * is false. * Enabling the support envolves reflective access * to super's private field rowModel which may fail due to security * issues. If failing the support is not enabled. * * PENDING: should we throw an Exception if the enabled fails? * Or silently fail - depends on runtime context, * can't do anything about it. * * @param enabled */ public void setRowHeightEnabled(boolean enabled) { boolean old = isRowHeightEnabled(); if (old == enabled) return; if (enabled && !canEnableRowHeight()) return; rowHeightEnabled = enabled; if (!enabled) { adminSetRowHeight(getRowHeight()); } // getRowSizing().setViewSizeSequence(getSuperRowModel(), getRowHeight()); firePropertyChange("rowHeightEnabled", old, rowHeightEnabled); } private boolean canEnableRowHeight() { return getRowModelField() != null; } public boolean isRowHeightEnabled() { return rowHeightEnabled; } private SizeSequence getSuperRowModel() { try { Field field = getRowModelField(); if (field != null) { return (SizeSequence) field.get(this); } } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * @return * @throws NoSuchFieldException */ private Field getRowModelField() { if (rowModelField == null) { try { rowModelField = JTable.class.getDeclaredField("rowModel"); rowModelField.setAccessible(true); } catch (SecurityException e) { rowModelField = null; e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return rowModelField; } /** * * @return */ protected RowSizing getRowSizing() { if (rowSizing == null) { rowSizing = new RowSizing(filters); } return rowSizing; } /** * calling setRowHeight for internal reasons. * Keeps the isXTableRowHeight unchanged. */ protected void adminSetRowHeight(int rowHeight) { boolean heightSet = isXTableRowHeightSet; setRowHeight(rowHeight); isXTableRowHeightSet = heightSet; } private void updateEditorUI(Object value) { // maybe null or proxyValue if (!(value instanceof TableCellEditor)) return; // super handled this if ((value instanceof JComponent) || (value instanceof DefaultCellEditor)) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellEditor) value) .getTableCellEditorComponent(this, null, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } /** ? */ private void updateRendererUI(Object value) { // maybe null or proxyValue if (!(value instanceof TableCellRenderer)) return; // super handled this if (value instanceof JComponent) return; // custom editors might balk about fake rows/columns try { Component comp = ((TableCellRenderer) value) .getTableCellRendererComponent(this, null, false, false, -1, -1); if (comp instanceof JComponent) { ((JComponent) comp).updateUI(); } } catch (Exception e) { // ignore - can't do anything } } //---------------------------- overriding super factory methods and buggy /** * workaround bug in JTable. (Bug Parade ID #6291631 - negative y is mapped * to row 0). */ public int rowAtPoint(Point point) { if (point.y < 0) return -1; return super.rowAtPoint(point); } /** ? */ protected JTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel); } /** ? */ protected TableColumnModel createDefaultColumnModel() { return new DefaultTableColumnModelExt(); } // /** // * Returns the default table model object, which is // * a <code>DefaultTableModel</code>. A subclass can override this // * method to return a different table model object. // * // * @return the default table model object // * @see DefaultTableColumnModelExt // */ // protected TableModel createDefaultDataModel() { // return new DefaultTableModelExt(); // } }
started #144-swingx: renderers and componentorientation applied variation of fix from Shai Almog changed NumberRenderer orientation to Trailing git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@445 1312f61e-266d-0410-97fa-c3b71232c9ac
src/java/org/jdesktop/swingx/JXTable.java
started #144-swingx: renderers and componentorientation
Java
lgpl-2.1
7b8d60000453625baafeecc1eecf7d0ea674e2f9
0
jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,languagetool-org/languagetool,jimregan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import org.apache.commons.lang3.StringUtils; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.Language; import org.languagetool.UserConfig; import org.languagetool.rules.AbstractStyleRepeatedWordRule; import org.languagetool.rules.Categories; import org.languagetool.rules.Example; /** * A rule checks the appearance of same words in a sentence or in two consecutive sentences. * Only substantive, verbs and adjectives are checked. * This rule detects no grammar error but a stylistic problem (default off) * @author Fred Kruse */ public class GermanStyleRepeatedWordRule extends AbstractStyleRepeatedWordRule { private static final String SYNONYMS_URL = "https://www.openthesaurus.de/synonyme/"; public GermanStyleRepeatedWordRule(ResourceBundle messages, Language lang, UserConfig userConfig) { super(messages, lang, userConfig); super.setCategory(Categories.STYLE.getCategory(messages)); addExamplePair(Example.wrong("Ich gehe zum Supermarkt, danach <marker>gehe</marker> ich nach Hause."), Example.fixed("Ich gehe zum Supermarkt, danach nach Hause.")); } @Override public String getId() { return "STYLE_REPEATED_WORD_RULE_DE"; } @Override public String getDescription() { return "Wiederholte Worte in aufeinanderfolgenden Sätzen"; } @Override protected String messageSameSentence() { return "Mögliches Stilproblem: Das Wort wird bereits im selben Satz verwendet."; } @Override protected String messageSentenceBefore() { return "Mögliches Stilproblem: Das Wort wird bereits in einem vorhergehenden Satz verwendet."; } @Override protected String messageSentenceAfter() { return "Mögliches Stilproblem: Das Wort wird bereits in einem nachfolgenden Satz verwendet."; } /* * Is a unknown word (has only letters and no PosTag) */ private static boolean isUnknownWord(AnalyzedTokenReadings token) { return token.isPosTagUnknown() && token.getToken().length() > 2 && token.getToken().matches("^[A-Za-zÄÖÜäöüß]+$"); } /* * Only substantive, names, verbs and adjectives are checked */ protected boolean isTokenToCheck(AnalyzedTokenReadings token) { return ((token.matchesPosTagRegex("(SUB|EIG|VER|ADJ):.*") && !token.matchesPosTagRegex("(PRO|A(RT|DV)|VER:(AUX|MOD)):.*") || isUnknownWord(token)) && !StringUtils.equalsAny(token.getToken(), "sicher", "weit", "Sie", "Ich", "Euch", "Eure")); } /* * Pairs of substantive are excluded like "Arm in Arm", "Seite an Seite", etc. */ protected boolean isTokenPair(AnalyzedTokenReadings[] tokens, int n, boolean before) { if (before) { if ((tokens[n-2].hasPosTagStartingWith("SUB") && tokens[n-1].hasPosTagStartingWith("PRP") && tokens[n].hasPosTagStartingWith("SUB")) || (!tokens[n-2].getToken().equals("hart") && !tokens[n-1].getToken().equals("auf") && !tokens[n].getToken().equals("hart")) ) { return true; } } else { if ((tokens[n].hasPosTagStartingWith("SUB") && tokens[n+1].hasPosTagStartingWith("PRP") && tokens[n+2].hasPosTagStartingWith("SUB")) || (!tokens[n].getToken().equals("hart") && !tokens[n-1].getToken().equals("auf") && !tokens[n + 2].getToken().equals("hart")) ) { return true; } } return false; } private boolean isFalsePair(String token1, String token2, String equalWord, String containedWord) { return ((token1.equals(equalWord) && token2.contains(containedWord)) || token2.equals(equalWord) && token1.contains(containedWord)); } @Override protected boolean isPartOfWord(String testTokenText, String tokenText) { return ( testTokenText.length() > 2 && tokenText.length() > 2 && (testTokenText.startsWith(tokenText) || testTokenText.endsWith(tokenText) || tokenText.startsWith(testTokenText) || tokenText.endsWith(testTokenText)) && (!isFalsePair(testTokenText, tokenText, "lang", "klang")) && (!isFalsePair(testTokenText, tokenText, "Art", "Artefakt")) && (testTokenText.length() == tokenText.length() || testTokenText.length() < tokenText.length() - 3 || testTokenText.length() > tokenText.length() + 3) || testTokenText.equals(tokenText + "s") || tokenText.equals(testTokenText + "s") ); } /* * set an URL to the German openThesaurus */ @Override protected URL setURL(AnalyzedTokenReadings token) throws MalformedURLException { if (token != null) { List<AnalyzedToken> readings = token.getReadings(); List<String> lemmas = new ArrayList<>(); for (AnalyzedToken reading : readings) { String lemma = reading.getLemma(); if (lemma != null) { lemmas.add(lemma); } } if (lemmas.size() == 1) { return new URL(SYNONYMS_URL + lemmas.get(0)); } return new URL(SYNONYMS_URL + token.getToken()); } return null; } }
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanStyleRepeatedWordRule.java
/* LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import org.apache.commons.lang3.StringUtils; import org.languagetool.AnalyzedToken; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.Language; import org.languagetool.UserConfig; import org.languagetool.rules.AbstractStyleRepeatedWordRule; import org.languagetool.rules.Categories; import org.languagetool.rules.Example; /** * A rule checks the appearance of same words in a sentence or in two consecutive sentences. * Only substantive, verbs and adjectives are checked. * This rule detects no grammar error but a stylistic problem (default off) * @author Fred Kruse */ public class GermanStyleRepeatedWordRule extends AbstractStyleRepeatedWordRule { private static final String SYNONYMS_URL = "https://www.openthesaurus.de/synonyme/"; public GermanStyleRepeatedWordRule(ResourceBundle messages, Language lang, UserConfig userConfig) { super(messages, lang, userConfig); super.setCategory(Categories.STYLE.getCategory(messages)); addExamplePair(Example.wrong("Ich gehe zum Supermarkt, danach <marker>gehe</marker> ich nach Hause."), Example.fixed("Ich gehe zum Supermarkt, danach nach Hause.")); } @Override public String getId() { return "STYLE_REPEATED_WORD_RULE_DE"; } @Override public String getDescription() { return "Wiederholte Worte in aufeinanderfolgenden Sätzen"; } @Override protected String messageSameSentence() { return "Mögliches Stilproblem: Das Wort wird bereits im selben Satz verwendet."; } @Override protected String messageSentenceBefore() { return "Mögliches Stilproblem: Das Wort wird bereits in einem vorhergehenden Satz verwendet."; } @Override protected String messageSentenceAfter() { return "Mögliches Stilproblem: Das Wort wird bereits in einem nachfolgenden Satz verwendet."; } /* * Is a unknown word (has only letters and no PosTag) */ private static boolean isUnknownWord(AnalyzedTokenReadings token) { return token.isPosTagUnknown() && token.getToken().length() > 2 && token.getToken().matches("^[A-Za-zÄÖÜäöüß]+$"); } /* * Only substantive, names, verbs and adjectives are checked */ protected boolean isTokenToCheck(AnalyzedTokenReadings token) { return ((token.matchesPosTagRegex("(SUB|EIG|VER|ADJ):.*") && !token.matchesPosTagRegex("(PRO|A(RT|DV)|VER:(AUX|MOD)):.*") || isUnknownWord(token)) && !StringUtils.equalsAny(token.getToken(), "sicher", "weit", "Sie", "Ich", "Euch", "Eure")); } /* * Pairs of substantive are excluded like "Arm in Arm", "Seite an Seite", etc. */ protected boolean isTokenPair(AnalyzedTokenReadings[] tokens, int n, boolean before) { if (before) { if ((tokens[n-2].hasPosTagStartingWith("SUB") && tokens[n-1].hasPosTagStartingWith("PRP") && tokens[n].hasPosTagStartingWith("SUB")) || (!tokens[n-2].getToken().equals("hart") && !tokens[n-1].getToken().equals("auf") && !tokens[n].getToken().equals("hart")) ) { return true; } } else { if ((tokens[n].hasPosTagStartingWith("SUB") && tokens[n+1].hasPosTagStartingWith("PRP") && tokens[n+2].hasPosTagStartingWith("SUB")) || (!tokens[n].getToken().equals("hart") && !tokens[n-1].getToken().equals("auf") && !tokens[n + 2].getToken().equals("hart")) ) { return true; } } return false; } private boolean isFalsePair(String token1, String token2, String equalWord, String containedWord) { return ((token1.equals(equalWord) && token2.contains(containedWord)) || token2.equals(equalWord) && token1.contains(containedWord)); } @Override protected boolean isPartOfWord(String testTokenText, String tokenText) { return ( (testTokenText.startsWith(tokenText) || testTokenText.endsWith(tokenText) || tokenText.startsWith(testTokenText) || tokenText.endsWith(testTokenText)) && (!isFalsePair(testTokenText, tokenText, "lang", "klang")) && (testTokenText.length() == tokenText.length() || testTokenText.length() < tokenText.length() - 3 || testTokenText.length() > tokenText.length() + 3) || testTokenText.equals(tokenText + "s") || tokenText.equals(testTokenText + "s") ); } /* * set an URL to the German openThesaurus */ @Override protected URL setURL(AnalyzedTokenReadings token) throws MalformedURLException { if (token != null) { List<AnalyzedToken> readings = token.getReadings(); List<String> lemmas = new ArrayList<>(); for (AnalyzedToken reading : readings) { String lemma = reading.getLemma(); if (lemma != null) { lemmas.add(lemma); } } if (lemmas.size() == 1) { return new URL(SYNONYMS_URL + lemmas.get(0)); } return new URL(SYNONYMS_URL + token.getToken()); } return null; } }
[de] solves issues #4641 and #4647
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/GermanStyleRepeatedWordRule.java
[de] solves issues #4641 and #4647
Java
apache-2.0
8a847084562c2cf9d40ddeb5c833561c9d85a148
0
ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server,ToureNPlaner/tourenplaner-server
package de.tourenplaner.algorithms.bbbundle; import com.carrotsearch.hppc.IntArrayDeque; import com.carrotsearch.hppc.IntArrayList; import com.carrotsearch.hppc.IntStack; import com.carrotsearch.hppc.cursors.IntCursor; import de.tourenplaner.algorithms.ComputeException; import de.tourenplaner.algorithms.PrioAlgorithm; import de.tourenplaner.algorithms.bbprioclassic.BoundingBox; import de.tourenplaner.computecore.ComputeRequest; import de.tourenplaner.graphrep.GraphRep; import de.tourenplaner.graphrep.PrioDings; import de.tourenplaner.utils.Timing; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.logging.Logger; /** * Created by niklas on 19.03.15. */ public class BBBundle extends PrioAlgorithm { private static Logger log = Logger.getLogger("de.tourenplaner.algorithms"); private static final int UNSEEN = 0; private static final int DISCOVERED = 1; private static final int ACTIVE = 2; private static final int COMPLETED = 3; private final int[] dfsState; private final int[] mappedIds; private final IntArrayList needClear; public BBBundle(GraphRep graph, PrioDings prioDings) { super(graph, prioDings); dfsState = new int[graph.getNodeCount()]; mappedIds = new int[graph.getNodeCount()]; needClear = new IntArrayList(); } private IntArrayDeque topoSortNodes(IntArrayList bboxNodes, int P, int coreSize) { IntArrayDeque topSorted = new IntArrayDeque(bboxNodes.size()); for (int i = 0; i < bboxNodes.size(); ++i) { int bboxNodeId = bboxNodes.get(i); // We only want nodes that aren't in the core because we got them already if (bboxNodeId >= coreSize && dfsState[bboxNodeId] == UNSEEN) { dfs(topSorted, bboxNodeId, coreSize); } } int currMapId = coreSize; for (IntCursor ic: topSorted) { assert dfsState[ic.value] == COMPLETED; mappedIds[ic.value] = currMapId++; } for (IntCursor ic : needClear) { dfsState[ic.value] = UNSEEN; } needClear.clear(); return topSorted; } private void dfs(IntArrayDeque topSorted, int bboxNodeId, int coreSize) { IntStack stack = new IntStack(); dfsState[bboxNodeId] = DISCOVERED; needClear.add(bboxNodeId); stack.push(bboxNodeId); while (!stack.isEmpty()) { int nodeId = stack.peek(); switch (dfsState[nodeId]) { case DISCOVERED: { dfsState[nodeId] = ACTIVE; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank < nodeRank) { break; } assert dfsState[trgtId] != ACTIVE; if (dfsState[trgtId] == COMPLETED || trgtId < coreSize) { continue; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending dfsState[trgtId] = DISCOVERED; needClear.add(trgtId); stack.push(trgtId); } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank < nodeRank) { break; } assert dfsState[srcId] != ACTIVE; if (dfsState[srcId] == COMPLETED || srcId < coreSize) { continue; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending dfsState[srcId] = DISCOVERED; needClear.add(srcId); stack.push(srcId); } break; } case ACTIVE: { dfsState[nodeId] = COMPLETED; topSorted.addFirst(stack.pop()); break; } case COMPLETED: // Stale stack entry, ignore stack.pop(); break; default: throw new RuntimeException("Crazy dfsState "+dfsState[nodeId]); } } } public void unpack(int index, IntArrayList unpackIds, double minLen, double maxLen, double maxRatio) { /*if (drawn.get(index)) { return; }*/ double edgeLen = ((double) graph.getEuclidianDist(index)); int skipA = graph.getFirstShortcuttedEdge(index); if (skipA == -1 || edgeLen <= minLen) { unpackIds.add(index); return; } int skipB = graph.getSecondShortcuttedEdge(index); /* * |x1 y1 1| * A = abs(1/2* |x2 y2 1|)= 1/2*Baseline*Height * |x3 y3 1| * = 1/2*((x1*y2+y1*x3+x2*y3) - (y2*x3 + y1*x2 + x1*y3)) * Height = 2*A/Baseline * ratio = Height/Baseline * */ if (edgeLen <= maxLen) { int middle = graph.getTarget(skipA); int srcId = graph.getSource(index); double x1 = graph.getXPos(srcId); double y1 = graph.getYPos(srcId); double x2 = graph.getXPos(middle); double y2 = graph.getYPos(middle); int trgtId = graph.getTarget(index); double x3 = graph.getXPos(trgtId); double y3 = graph.getYPos(trgtId); double A = Math.abs(0.5 * ((x1 * y2 + y1 * x3 + x2 * y3) - (y2 * x3 + y1 * x2 + x1 * y3))); double ratio = 2.0 * A / (edgeLen * edgeLen); if (ratio <= maxRatio) { unpackIds.add(index); return; } } unpack(skipA, unpackIds, minLen, maxLen, maxRatio); unpack(skipB, unpackIds, minLen, maxLen, maxRatio); } private void extractEdges(IntArrayDeque nodes, ArrayList<BBBundleEdge> upEdges, ArrayList<BBBundleEdge> downEdges, int coreSize, double minLen, double maxLen, double maxRatio) { int edgeCount = 0; for (IntCursor ic : nodes) { int nodeId = ic.value; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank < nodeRank) { break; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending assert (trgtId < coreSize) || mappedIds[nodeId] < mappedIds[trgtId]; int srcIdMapped = mappedIds[nodeId]; int trgtIdMapped = (trgtId >= coreSize) ? mappedIds[trgtId] : trgtId; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); upEdges.add(e); edgeCount++; } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank < nodeRank) { break; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending //assert (srcId < coreSize) || mappedIds[nodeId] < mappedIds[srcId]; // topological order, trgt -> src int srcIdMapped = (srcId >= coreSize) ? mappedIds[srcId] : srcId; int trgtIdMapped = mappedIds[nodeId]; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); downEdges.add(e); edgeCount++; } } log.info(edgeCount + " edges"); } private IntArrayList findBBoxNodes(BBBundleRequestData req) { BoundingBox bbox = req.getBbox(); long start = System.nanoTime(); IntArrayList bboxNodes = new IntArrayList(); int currNodeCount; int level; if (req.getMode() == BBBundleRequestData.LevelMode.AUTO) { level = graph.getMaxRank(); do { level = level - 10; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); } else if (req.getMode() == BBBundleRequestData.LevelMode.HINTED) { level = graph.getMaxRank(); do { level = level - 10; bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); log.info("AutoLevel was: " + level); level = (req.getLevel() + level) / 2; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } else { // else if (req.mode == BBPrioLimitedRequestData.LevelMode.EXACT){ level = req.getLevel(); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } log.info(Timing.took("ExtractBBox", start)); log.info("Level was: " + req.getLevel()); log.info("Nodes extracted: " + bboxNodes.size() + " of " + graph.getNodeCount()); return bboxNodes; } @Override public void compute(ComputeRequest request) throws ComputeException { BBBundleRequestData req = (BBBundleRequestData) request.getRequestData(); IntArrayList bboxNodes = findBBoxNodes(req); long start; start = System.nanoTime(); IntArrayDeque nodes = topoSortNodes(bboxNodes, req.getLevel(), req.getCoreSize()); log.info(Timing.took("TopSort", start)); log.info("Nodes after TopSort: (with coreSize = " + req.getCoreSize() + ") " + nodes.size()); start = System.nanoTime(); ArrayList<BBBundleEdge> upEdges = new ArrayList<>(); ArrayList<BBBundleEdge> downEdges = new ArrayList<>(); extractEdges(nodes, upEdges, downEdges, req.getCoreSize(), req.getMinLen(), req.getMaxLen(), req.getMaxRatio()); log.info(Timing.took("Extracting edges", start)); log.info("UpEdges: " + upEdges.size() + ", downEdges: " + downEdges.size()); request.setResultObject(new BBBundleResult(graph, nodes.size(), upEdges, downEdges, req)); } }
src/main/java/de/tourenplaner/algorithms/bbbundle/BBBundle.java
package de.tourenplaner.algorithms.bbbundle; import com.carrotsearch.hppc.IntArrayDeque; import com.carrotsearch.hppc.IntArrayList; import com.carrotsearch.hppc.IntStack; import com.carrotsearch.hppc.cursors.IntCursor; import de.tourenplaner.algorithms.ComputeException; import de.tourenplaner.algorithms.PrioAlgorithm; import de.tourenplaner.algorithms.bbprioclassic.BoundingBox; import de.tourenplaner.computecore.ComputeRequest; import de.tourenplaner.graphrep.GraphRep; import de.tourenplaner.graphrep.PrioDings; import de.tourenplaner.utils.Timing; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.logging.Logger; /** * Created by niklas on 19.03.15. */ public class BBBundle extends PrioAlgorithm { private static Logger log = Logger.getLogger("de.tourenplaner.algorithms"); private static final int UNSEEN = 0; private static final int DISCOVERED = 1; private static final int ACTIVE = 2; private static final int COMPLETED = 3; private final int[] dfsState; private final int[] mappedIds; private final IntArrayList needClear; public BBBundle(GraphRep graph, PrioDings prioDings) { super(graph, prioDings); dfsState = new int[graph.getNodeCount()]; mappedIds = new int[graph.getNodeCount()]; needClear = new IntArrayList(); } private IntArrayDeque topoSortNodes(IntArrayList bboxNodes, int P, int coreSize) { IntArrayDeque topSorted = new IntArrayDeque(bboxNodes.size()); for (int i = 0; i < bboxNodes.size(); ++i) { int bboxNodeId = bboxNodes.get(i); // We only want nodes that aren't in the core because we got them already if (bboxNodeId >= coreSize && dfsState[bboxNodeId] == UNSEEN) { dfs(topSorted, bboxNodeId, coreSize); } } int currMapId = coreSize; for (IntCursor ic: topSorted) { assert dfsState[ic.value] == COMPLETED; mappedIds[ic.value] = currMapId++; } for (IntCursor ic : needClear) { dfsState[ic.value] = UNSEEN; } needClear.clear(); return topSorted; } private void dfs(IntArrayDeque topSorted, int bboxNodeId, int coreSize) { IntStack stack = new IntStack(); dfsState[bboxNodeId] = DISCOVERED; needClear.add(bboxNodeId); stack.push(bboxNodeId); while (!stack.isEmpty()) { int nodeId = stack.peek(); switch (dfsState[nodeId]) { case DISCOVERED: { dfsState[nodeId] = ACTIVE; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank <= nodeRank) { break; } assert dfsState[trgtId] != ACTIVE; if (dfsState[trgtId] == COMPLETED || trgtId < coreSize) { continue; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending dfsState[trgtId] = DISCOVERED; needClear.add(trgtId); stack.push(trgtId); } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank <= nodeRank) { break; } assert dfsState[srcId] != ACTIVE; if (dfsState[srcId] == COMPLETED || srcId < coreSize) { continue; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending dfsState[srcId] = DISCOVERED; needClear.add(srcId); stack.push(srcId); } break; } case ACTIVE: { dfsState[nodeId] = COMPLETED; topSorted.addFirst(stack.pop()); break; } case COMPLETED: // Stale stack entry, ignore stack.pop(); break; default: throw new RuntimeException("Crazy dfsState "+dfsState[nodeId]); } } } public void unpack(int index, IntArrayList unpackIds, double minLen, double maxLen, double maxRatio) { /*if (drawn.get(index)) { return; }*/ double edgeLen = ((double) graph.getEuclidianDist(index)); int skipA = graph.getFirstShortcuttedEdge(index); if (skipA == -1 || edgeLen <= minLen) { unpackIds.add(index); return; } int skipB = graph.getSecondShortcuttedEdge(index); /* * |x1 y1 1| * A = abs(1/2* |x2 y2 1|)= 1/2*Baseline*Height * |x3 y3 1| * = 1/2*((x1*y2+y1*x3+x2*y3) - (y2*x3 + y1*x2 + x1*y3)) * Height = 2*A/Baseline * ratio = Height/Baseline * */ if (edgeLen <= maxLen) { int middle = graph.getTarget(skipA); int srcId = graph.getSource(index); double x1 = graph.getXPos(srcId); double y1 = graph.getYPos(srcId); double x2 = graph.getXPos(middle); double y2 = graph.getYPos(middle); int trgtId = graph.getTarget(index); double x3 = graph.getXPos(trgtId); double y3 = graph.getYPos(trgtId); double A = Math.abs(0.5 * ((x1 * y2 + y1 * x3 + x2 * y3) - (y2 * x3 + y1 * x2 + x1 * y3))); double ratio = 2.0 * A / (edgeLen * edgeLen); if (ratio <= maxRatio) { unpackIds.add(index); return; } } unpack(skipA, unpackIds, minLen, maxLen, maxRatio); unpack(skipB, unpackIds, minLen, maxLen, maxRatio); } private void extractEdges(IntArrayDeque nodes, ArrayList<BBBundleEdge> upEdges, ArrayList<BBBundleEdge> downEdges, int coreSize, double minLen, double maxLen, double maxRatio) { int edgeCount = 0; for (IntCursor ic : nodes) { int nodeId = ic.value; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank <= nodeRank) { break; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending assert (trgtId < coreSize) || mappedIds[nodeId] < mappedIds[trgtId]; int srcIdMapped = mappedIds[nodeId]; int trgtIdMapped = (trgtId >= coreSize) ? mappedIds[trgtId] : trgtId; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); upEdges.add(e); edgeCount++; } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank <= nodeRank) { break; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending //assert (srcId < coreSize) || mappedIds[nodeId] < mappedIds[srcId]; // topological order, trgt -> src int srcIdMapped = (srcId >= coreSize) ? mappedIds[srcId] : srcId; int trgtIdMapped = mappedIds[nodeId]; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); downEdges.add(e); edgeCount++; } } log.info(edgeCount + " edges"); } private IntArrayList findBBoxNodes(BBBundleRequestData req) { BoundingBox bbox = req.getBbox(); long start = System.nanoTime(); IntArrayList bboxNodes = new IntArrayList(); int currNodeCount; int level; if (req.getMode() == BBBundleRequestData.LevelMode.AUTO) { level = graph.getMaxRank(); do { level = level - 10; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); } else if (req.getMode() == BBBundleRequestData.LevelMode.HINTED) { level = graph.getMaxRank(); do { level = level - 10; bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); log.info("AutoLevel was: " + level); level = (req.getLevel() + level) / 2; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } else { // else if (req.mode == BBPrioLimitedRequestData.LevelMode.EXACT){ level = req.getLevel(); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } log.info(Timing.took("ExtractBBox", start)); log.info("Level was: " + req.getLevel()); log.info("Nodes extracted: " + bboxNodes.size() + " of " + graph.getNodeCount()); return bboxNodes; } @Override public void compute(ComputeRequest request) throws ComputeException { BBBundleRequestData req = (BBBundleRequestData) request.getRequestData(); IntArrayList bboxNodes = findBBoxNodes(req); long start; start = System.nanoTime(); IntArrayDeque nodes = topoSortNodes(bboxNodes, req.getLevel(), req.getCoreSize()); log.info(Timing.took("TopSort", start)); log.info("Nodes after TopSort: (with coreSize = " + req.getCoreSize() + ") " + nodes.size()); start = System.nanoTime(); ArrayList<BBBundleEdge> upEdges = new ArrayList<>(); ArrayList<BBBundleEdge> downEdges = new ArrayList<>(); extractEdges(nodes, upEdges, downEdges, req.getCoreSize(), req.getMinLen(), req.getMaxLen(), req.getMaxRatio()); log.info(Timing.took("Extracting edges", start)); log.info("UpEdges: " + upEdges.size() + ", downEdges: " + downEdges.size()); request.setResultObject(new BBBundleResult(graph, nodes.size(), upEdges, downEdges, req)); } }
Revert "For clarity, explicitly up/down not level" This reverts commit 0d6f7fe83f66b22c1dc20770fed12a4da4e383a2.
src/main/java/de/tourenplaner/algorithms/bbbundle/BBBundle.java
Revert "For clarity, explicitly up/down not level"
Java
apache-2.0
72db573b8b5fc6606ac145bb52e0b1aa15b5f4d3
0
sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak
package com.sequenceiq.provisioning.service.azure; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.sequenceiq.cloud.azure.client.AzureClient; import com.sequenceiq.provisioning.controller.InternalServerException; import com.sequenceiq.provisioning.controller.json.AzureStackResult; import com.sequenceiq.provisioning.controller.json.JsonHelper; import com.sequenceiq.provisioning.controller.json.StackResult; import com.sequenceiq.provisioning.domain.AzureCredential; import com.sequenceiq.provisioning.domain.AzureStackDescription; import com.sequenceiq.provisioning.domain.AzureTemplate; import com.sequenceiq.provisioning.domain.CloudPlatform; import com.sequenceiq.provisioning.domain.Credential; import com.sequenceiq.provisioning.domain.DetailedAzureStackDescription; import com.sequenceiq.provisioning.domain.Stack; import com.sequenceiq.provisioning.domain.StackDescription; import com.sequenceiq.provisioning.domain.User; import com.sequenceiq.provisioning.service.ProvisionService; import groovyx.net.http.HttpResponseDecorator; import groovyx.net.http.HttpResponseException; @Service public class AzureProvisionService implements ProvisionService { private static final Logger LOGGER = LoggerFactory.getLogger(AzureProvisionService.class); private static final String OK_STATUS = "ok"; private static final String LOCATION = "location"; private static final String NAME = "name"; private static final String DESCRIPTION = "description"; private static final String AFFINITYGROUP = "affinityGroup"; private static final String ADDRESSPREFIX = "addressPrefix"; private static final String SUBNETADDRESSPREFIX = "subnetAddressPrefix"; private static final String DEPLOYMENTSLOT = "deploymentSlot"; private static final String LABEL = "label"; private static final String IMAGENAME = "imageName"; private static final String IMAGESTOREURI = "imageStoreUri"; private static final String HOSTNAME = "hostname"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private static final String SUBNETNAME = "subnetName"; private static final String VIRTUALNETWORKNAME = "virtualNetworkName"; private static final String VMTYPE = "vmType"; private static final String DATADIR = "userdatas"; private static final String SSHPUBLICKEYFINGERPRINT = "sshPublicKeyFingerprint"; private static final String SSHPUBLICKEYPATH = "sshPublicKeyPath"; private static final String SERVICENAME = "serviceName"; private static final String ERROR = "\"error\":\"Could not fetch data from azure\""; private static final int NOT_FOUND = 404; @Autowired private JsonHelper jsonHelper; @Override @Async public StackResult createStack(User user, Stack stack, Credential credential) { AzureTemplate azureTemplate = (AzureTemplate) stack.getTemplate(); String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); Map<String, String> props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(LOCATION, AzureLocation.valueOf(azureTemplate.getLocation()).location()); props.put(DESCRIPTION, azureTemplate.getDescription()); HttpResponseDecorator affinityResponse = (HttpResponseDecorator) azureClient.createAffinityGroup(props); String requestId = (String) azureClient.getRequestId(affinityResponse); azureClient.waitUntilComplete(requestId); props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(DESCRIPTION, azureTemplate.getDescription()); props.put(AFFINITYGROUP, azureTemplate.getName()); HttpResponseDecorator storageResponse = (HttpResponseDecorator) azureClient.createStorageAccount(props); requestId = (String) azureClient.getRequestId(storageResponse); azureClient.waitUntilComplete(requestId); props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(AFFINITYGROUP, azureTemplate.getName()); props.put(SUBNETNAME, azureTemplate.getSubnetAddressPrefix()); props.put(ADDRESSPREFIX, azureTemplate.getAddressPrefix()); props.put(SUBNETADDRESSPREFIX, azureTemplate.getSubnetAddressPrefix()); HttpResponseDecorator virtualNetworkResponse = (HttpResponseDecorator) azureClient.createVirtualNetwork(props); requestId = (String) azureClient.getRequestId(virtualNetworkResponse); azureClient.waitUntilComplete(requestId); for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(azureTemplate.getName(), i); props = new HashMap<>(); props.put(NAME, vmName); props.put(DESCRIPTION, azureTemplate.getDescription()); props.put(AFFINITYGROUP, azureTemplate.getName()); HttpResponseDecorator cloudServiceResponse = (HttpResponseDecorator) azureClient.createCloudService(props); requestId = (String) azureClient.getRequestId(cloudServiceResponse); azureClient.waitUntilComplete(requestId); byte[] encoded = Base64.encodeBase64(vmName.getBytes()); String label = new String(encoded); props = new HashMap<>(); props.put(NAME, vmName); props.put(DEPLOYMENTSLOT, azureTemplate.getDeploymentSlot()); props.put(LABEL, label); props.put(IMAGENAME, azureTemplate.getImageName()); props.put(IMAGESTOREURI, String.format("http://%s.blob.core.windows.net/vhd-store/%s.vhd", azureTemplate.getName(), vmName) ); props.put(HOSTNAME, vmName); props.put(USERNAME, azureTemplate.getUserName()); if (azureTemplate.getPassword() != null) { props.put(PASSWORD, azureTemplate.getPassword()); } else { props.put(SSHPUBLICKEYFINGERPRINT, azureTemplate.getSshPublicKeyFingerprint()); props.put(SSHPUBLICKEYPATH, azureTemplate.getSshPublicKeyPath()); } props.put(SUBNETNAME, azureTemplate.getName()); props.put(VIRTUALNETWORKNAME, azureTemplate.getName()); props.put(VMTYPE, AzureVmType.valueOf(azureTemplate.getVmType()).vmType()); HttpResponseDecorator virtualMachineResponse = (HttpResponseDecorator) azureClient.createVirtualMachine(props); requestId = (String) azureClient.getRequestId(virtualMachineResponse); azureClient.waitUntilComplete(requestId); } return new AzureStackResult(OK_STATUS); } private String getVmName(String azureTemplate, int i) { return String.format("%s-%s", azureTemplate, i); } @Override public StackDescription describeStack(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); AzureStackDescription azureStackDescription = new AzureStackDescription(); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); try { Object cloudService = azureClient.getCloudService(templateName); azureStackDescription.setCloudService(jsonHelper.createJsonFromString(cloudService.toString())); } catch (Exception ex) { azureStackDescription.setCloudService(jsonHelper.createJsonFromString(String.format("{\"HostedService\": {%s}}", ERROR))); } for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object virtualMachine = azureClient.getVirtualMachine(props); azureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(virtualMachine.toString()).toString()); } catch (Exception ex) { azureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(String.format("{\"Deployment\": {%s}}", ERROR)).toString()); } } return azureStackDescription; } @Override public StackDescription describeStackWithResources(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); DetailedAzureStackDescription detailedAzureStackDescription = new DetailedAzureStackDescription(); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); try { Object affinityGroup = azureClient.getAffinityGroup(templateName); detailedAzureStackDescription.setAffinityGroup(jsonHelper.createJsonFromString(affinityGroup.toString())); } catch (Exception ex) { detailedAzureStackDescription.setAffinityGroup(jsonHelper.createJsonFromString(String.format("{\"AffinityGroup\": {%s}}", ERROR))); } try { Object cloudService = azureClient.getCloudService(templateName); detailedAzureStackDescription.setCloudService(jsonHelper.createJsonFromString(cloudService.toString()).toString()); } catch (Exception ex) { detailedAzureStackDescription.setCloudService(jsonHelper.createJsonFromString(String.format("{\"HostedService\": {%s}}", ERROR)).toString()); } try { Object storageAccount = azureClient.getStorageAccount(templateName); detailedAzureStackDescription.setStorageAccount(jsonHelper.createJsonFromString(storageAccount.toString())); } catch (Exception ex) { detailedAzureStackDescription.setStorageAccount(jsonHelper.createJsonFromString(String.format("{\"StorageService\": {%s}}", ERROR))); } for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object virtualMachine = azureClient.getVirtualMachine(props); detailedAzureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(virtualMachine.toString()).toString()); } catch (Exception ex) { detailedAzureStackDescription.getVirtualMachines().add( jsonHelper.createJsonFromString(String.format("{\"Deployment\": {%s}}", ERROR)).toString()); } } return detailedAzureStackDescription; } @Override public void deleteStack(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object deleteVirtualMachineResult = azureClient.deleteVirtualMachine(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object deleteCloudServiceResult = azureClient.deleteCloudService(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object deleteStorageAccountResult = azureClient.deleteStorageAccount(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object affinityGroup = azureClient.deleteAffinityGroup(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } } private void httpResponseExceptionHandler(HttpResponseException ex) { if (ex.getStatusCode() != NOT_FOUND) { throw new InternalServerException(ex.getMessage()); } } @Override public CloudPlatform getCloudPlatform() { return CloudPlatform.AZURE; } }
src/main/java/com/sequenceiq/provisioning/service/azure/AzureProvisionService.java
package com.sequenceiq.provisioning.service.azure; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import com.sequenceiq.cloud.azure.client.AzureClient; import com.sequenceiq.provisioning.controller.InternalServerException; import com.sequenceiq.provisioning.controller.json.AzureStackResult; import com.sequenceiq.provisioning.controller.json.JsonHelper; import com.sequenceiq.provisioning.controller.json.StackResult; import com.sequenceiq.provisioning.domain.AzureCredential; import com.sequenceiq.provisioning.domain.AzureStackDescription; import com.sequenceiq.provisioning.domain.AzureTemplate; import com.sequenceiq.provisioning.domain.CloudPlatform; import com.sequenceiq.provisioning.domain.Credential; import com.sequenceiq.provisioning.domain.DetailedAzureStackDescription; import com.sequenceiq.provisioning.domain.Stack; import com.sequenceiq.provisioning.domain.StackDescription; import com.sequenceiq.provisioning.domain.User; import com.sequenceiq.provisioning.service.ProvisionService; import groovyx.net.http.HttpResponseDecorator; import groovyx.net.http.HttpResponseException; @Service public class AzureProvisionService implements ProvisionService { private static final Logger LOGGER = LoggerFactory.getLogger(AzureProvisionService.class); private static final String OK_STATUS = "ok"; private static final String LOCATION = "location"; private static final String NAME = "name"; private static final String DESCRIPTION = "description"; private static final String AFFINITYGROUP = "affinityGroup"; private static final String ADDRESSPREFIX = "addressPrefix"; private static final String SUBNETADDRESSPREFIX = "subnetAddressPrefix"; private static final String DEPLOYMENTSLOT = "deploymentSlot"; private static final String LABEL = "label"; private static final String IMAGENAME = "imageName"; private static final String IMAGESTOREURI = "imageStoreUri"; private static final String HOSTNAME = "hostname"; private static final String USERNAME = "username"; private static final String PASSWORD = "password"; private static final String SUBNETNAME = "subnetName"; private static final String VIRTUALNETWORKNAME = "virtualNetworkName"; private static final String VMTYPE = "vmType"; private static final String DATADIR = "userdatas"; private static final String SSHPUBLICKEYFINGERPRINT = "sshPublicKeyFingerprint"; private static final String SSHPUBLICKEYPATH = "sshPublicKeyPath"; private static final String SERVICENAME = "serviceName"; private static final String ERROR = "\"error\":\"Could not fetch data from azure\""; private static final int NOT_FOUND = 404; @Autowired private JsonHelper jsonHelper; @Override @Async public StackResult createStack(User user, Stack stack, Credential credential) { AzureTemplate azureTemplate = (AzureTemplate) stack.getTemplate(); String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); Map<String, String> props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(LOCATION, AzureLocation.valueOf(azureTemplate.getLocation()).location()); props.put(DESCRIPTION, azureTemplate.getDescription()); HttpResponseDecorator affinityResponse = (HttpResponseDecorator) azureClient.createAffinityGroup(props); String requestId = (String) azureClient.getRequestId(affinityResponse); azureClient.waitUntilComplete(requestId); props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(DESCRIPTION, azureTemplate.getDescription()); props.put(AFFINITYGROUP, azureTemplate.getName()); HttpResponseDecorator storageResponse = (HttpResponseDecorator) azureClient.createStorageAccount(props); requestId = (String) azureClient.getRequestId(storageResponse); azureClient.waitUntilComplete(requestId); props = new HashMap<>(); props.put(NAME, azureTemplate.getName()); props.put(AFFINITYGROUP, azureTemplate.getName()); props.put(SUBNETNAME, azureTemplate.getSubnetAddressPrefix()); props.put(ADDRESSPREFIX, azureTemplate.getAddressPrefix()); props.put(SUBNETADDRESSPREFIX, azureTemplate.getSubnetAddressPrefix()); HttpResponseDecorator virtualNetworkResponse = (HttpResponseDecorator) azureClient.createVirtualNetwork(props); requestId = (String) azureClient.getRequestId(virtualNetworkResponse); azureClient.waitUntilComplete(requestId); for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(azureTemplate.getName(), i); props = new HashMap<>(); props.put(NAME, vmName); props.put(DESCRIPTION, azureTemplate.getDescription()); props.put(AFFINITYGROUP, azureTemplate.getName()); HttpResponseDecorator cloudServiceResponse = (HttpResponseDecorator) azureClient.createCloudService(props); requestId = (String) azureClient.getRequestId(cloudServiceResponse); azureClient.waitUntilComplete(requestId); byte[] encoded = Base64.encodeBase64(vmName.getBytes()); String label = new String(encoded); props = new HashMap<>(); props.put(NAME, vmName); props.put(DEPLOYMENTSLOT, azureTemplate.getDeploymentSlot()); props.put(LABEL, label); props.put(IMAGENAME, azureTemplate.getImageName()); props.put(IMAGESTOREURI, String.format("http://%s.blob.core.windows.net/vhd-store/%s.vhd", azureTemplate.getName(), vmName) ); props.put(HOSTNAME, vmName); props.put(USERNAME, azureTemplate.getUserName()); if (azureTemplate.getPassword() != null) { props.put(PASSWORD, azureTemplate.getPassword()); } else { props.put(SSHPUBLICKEYFINGERPRINT, azureTemplate.getSshPublicKeyFingerprint()); props.put(SSHPUBLICKEYPATH, azureTemplate.getSshPublicKeyPath()); } props.put(SUBNETNAME, azureTemplate.getName()); props.put(VIRTUALNETWORKNAME, azureTemplate.getName()); props.put(VMTYPE, AzureVmType.valueOf(azureTemplate.getVmType()).vmType()); HttpResponseDecorator virtualMachineResponse = (HttpResponseDecorator) azureClient.createVirtualMachine(props); requestId = (String) azureClient.getRequestId(virtualMachineResponse); azureClient.waitUntilComplete(requestId); } return new AzureStackResult(OK_STATUS); } private String getVmName(String azureTemplate, int i) { return String.format("%s-%s", azureTemplate, i); } @Override public StackDescription describeStack(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); AzureStackDescription azureStackDescription = new AzureStackDescription(); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); try { Object cloudService = azureClient.getCloudService(templateName); azureStackDescription.setCloudService(jsonHelper.createJsonFromString(cloudService.toString())); } catch (Exception ex) { azureStackDescription.setCloudService(jsonHelper.createJsonFromString(String.format("{\"HostedService\": {%s}}", ERROR))); } for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object virtualMachine = azureClient.getVirtualMachine(props); azureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(virtualMachine.toString()).toString()); } catch (Exception ex) { azureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(String.format("{\"Deployment\": {%s}}", ERROR)).toString()); } } return azureStackDescription; } @Override public StackDescription describeStackWithResources(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); DetailedAzureStackDescription detailedAzureStackDescription = new DetailedAzureStackDescription(); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); try { Object affinityGroup = azureClient.getAffinityGroup(templateName); detailedAzureStackDescription.setAffinityGroup(jsonHelper.createJsonFromString(affinityGroup.toString())); } catch (Exception ex) { detailedAzureStackDescription.setAffinityGroup(jsonHelper.createJsonFromString(String.format("{\"AffinityGroup\": {%s}}", ERROR))); } try { Object cloudService = azureClient.getCloudService(templateName); detailedAzureStackDescription.setCloudService(jsonHelper.createJsonFromString(cloudService.toString()).toString()); } catch (Exception ex) { detailedAzureStackDescription.setCloudService(jsonHelper.createJsonFromString(String.format("{\"HostedService\": {%s}}", ERROR)).toString()); } try { Object storageAccount = azureClient.getStorageAccount(templateName); detailedAzureStackDescription.setStorageAccount(jsonHelper.createJsonFromString(storageAccount.toString())); } catch (Exception ex) { detailedAzureStackDescription.setStorageAccount(jsonHelper.createJsonFromString(String.format("{\"StorageService\": {%s}}", ERROR))); } for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object virtualMachine = azureClient.getVirtualMachine(props); detailedAzureStackDescription.getVirtualMachines().add(jsonHelper.createJsonFromString(virtualMachine.toString()).toString()); } catch (Exception ex) { detailedAzureStackDescription.getVirtualMachines().add( jsonHelper.createJsonFromString(String.format("{\"Deployment\": {%s}}", ERROR)).toString()); } } return detailedAzureStackDescription; } @Override public void deleteStack(User user, Stack stack, Credential credential) { String filePath = AzureCredentialService.getUserJksFileName(credential, user.emailAsFolder()); File file = new File(filePath); AzureClient azureClient = new AzureClient( ((AzureCredential) credential).getSubscriptionId(), file.getAbsolutePath(), ((AzureCredential) credential).getJks() ); String templateName = ((AzureTemplate) stack.getTemplate()).getName(); for (int i = 0; i < stack.getClusterSize(); i++) { String vmName = getVmName(templateName, i); Map<String, String> props = new HashMap<>(); props.put(SERVICENAME, templateName); props.put(NAME, vmName); try { Object deleteVirtualMachineResult = azureClient.deleteVirtualMachine(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object deleteCloudServiceResult = azureClient.deleteCloudService(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object deleteStorageAccountResult = azureClient.deleteStorageAccount(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } try { Map<String, String> props = new HashMap<>(); props.put(NAME, templateName); Object affinityGroup = azureClient.deleteAffinityGroup(props); } catch (HttpResponseException ex) { httpResponseExceptionHandler(ex); } catch (Exception ex) { throw new InternalServerException(ex.getMessage()); } } private void httpResponseExceptionHandler(HttpResponseException ex) { if (ex.getStatusCode() != NOT_FOUND) { throw new InternalServerException(ex.getMessage()); } else { throw new InternalServerException(ex.getMessage()); } } @Override public CloudPlatform getCloudPlatform() { return CloudPlatform.AZURE; } }
added proper exception handling
src/main/java/com/sequenceiq/provisioning/service/azure/AzureProvisionService.java
added proper exception handling
Java
apache-2.0
f64de17491b28b8901b635e74ea5157c70d9116a
0
bladeFury/proportional-layout
package com.wukongtv.utils; import java.lang.reflect.Field; /** * Some Reflections * Created by zhangge on 14-10-4. */ public class Reflections { public static void setField(Object target, String fieldName, Object value) { Class<?> clazz = target.getClass(); Field f = null; try { f = clazz.getDeclaredField(fieldName); f.setAccessible(true); f.set(target, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static Object getField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { Class<?> clazz = target.getClass(); Field f = clazz.getDeclaredField(fieldName); f.setAccessible(true); return f.get(target); } }
library/src/main/java/com/wukongtv/utils/Reflections.java
package com.wukongtv.utils; import android.view.LayoutInflater; import android.view.View; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Objects; /** * Some Reflections * Created by zhangge on 14-10-4. */ public class Reflections { public static void setField(Object target, String fieldName, Object value) { Class<?> clazz = target.getClass(); Field f = null; try { f = clazz.getDeclaredField(fieldName); f.setAccessible(true); f.set(target, value); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static Object getField(Object target, String fieldName) throws NoSuchFieldException, IllegalAccessException { Class<?> clazz = target.getClass(); Field f = clazz.getDeclaredField(fieldName); f.setAccessible(true); return f.get(target); } }
remove useless imports
library/src/main/java/com/wukongtv/utils/Reflections.java
remove useless imports
Java
apache-2.0
17697ec4361228e8805a78ab2354386f3423e230
0
Panda-Programming-Language/Panda
/* * Copyright (c) 2015-2018 Dzikoysk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.panda_lang.panda.utilities.redact.match.text; import java.util.List; public class TextHollowPatternCompiler { private final TextHollowPatternBuilder builder; protected TextHollowPatternCompiler(TextHollowPatternBuilder builder) { this.builder = builder; } public TextHollowPatternBuilder compile(String pattern) { List<String> fragments = TextHollowPatternUtils.toFragments(pattern); for (String fragment : fragments) { if (fragment.equals("+*")) { builder.hollow(); } else { builder.basis(fragment); } } return builder; } public TextHollowPatternBuilder getBuilder() { return builder; } }
panda-utilities/src/main/java/org/panda_lang/panda/utilities/redact/match/text/TextHollowPatternCompiler.java
/* * Copyright (c) 2015-2018 Dzikoysk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.panda_lang.panda.utilities.redact.match.text; import java.util.List; public class TextHollowPatternCompiler { private final TextHollowPatternBuilder builder; protected TextHollowPatternCompiler(TextHollowPatternBuilder builder) { this.builder = builder; } public TextHollowPatternBuilder compile(String pattern) { List<String> fragments = TextHollowPatternUtils.toFragments(pattern); for (String fragment : fragments) { if (fragment.equals("*")) { builder.hollow(); } else { builder.basis(fragment); } } return builder; } public TextHollowPatternBuilder getBuilder() { return builder; } }
Fix TextHollowPatternCompiler (* -> +*)
panda-utilities/src/main/java/org/panda_lang/panda/utilities/redact/match/text/TextHollowPatternCompiler.java
Fix TextHollowPatternCompiler (* -> +*)
Java
apache-2.0
09ae8c58287ce583c378887cc88c0b6b7dafb7f7
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.restapi.filter; import com.google.inject.Inject; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.SystemName; import com.yahoo.config.provision.TenantName; import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.filter.DiscFilterRequest; import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig; import com.yahoo.jdisc.http.filter.security.cors.CorsRequestFilterBase; import com.yahoo.log.LogLevel; import com.yahoo.restapi.Path; import com.yahoo.vespa.athenz.api.AthenzDomain; import com.yahoo.vespa.athenz.api.AthenzIdentity; import com.yahoo.vespa.athenz.api.AthenzPrincipal; import com.yahoo.vespa.athenz.api.AthenzUser; import com.yahoo.vespa.athenz.client.zms.ZmsClientException; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.TenantController; import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactory; import com.yahoo.vespa.hosted.controller.athenz.ApplicationAction; import com.yahoo.vespa.hosted.controller.athenz.impl.AthenzFacade; import com.yahoo.vespa.hosted.controller.role.Action; import com.yahoo.vespa.hosted.controller.role.Context; import com.yahoo.vespa.hosted.controller.role.Role; import com.yahoo.vespa.hosted.controller.role.RoleMembership; import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant; import com.yahoo.vespa.hosted.controller.tenant.Tenant; import com.yahoo.vespa.hosted.controller.tenant.UserTenant; import com.yahoo.yolean.chain.After; import com.yahoo.yolean.chain.Provides; import javax.ws.rs.ForbiddenException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.WebApplicationException; import java.security.Principal; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; import static com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities.SCREWDRIVER_DOMAIN; /** * A security filter protects all controller apis. * * @author bjorncs */ @After("com.yahoo.vespa.hosted.controller.athenz.filter.UserAuthWithAthenzPrincipalFilter") @Provides("ControllerAuthorizationFilter") public class ControllerAuthorizationFilter extends CorsRequestFilterBase { private static final Logger log = Logger.getLogger(ControllerAuthorizationFilter.class.getName()); private final AthenzFacade athenz; private final Controller controller; @Inject public ControllerAuthorizationFilter(AthenzClientFactory clientFactory, Controller controller, CorsFilterConfig corsConfig) { this(clientFactory, controller, Set.copyOf(corsConfig.allowedUrls())); } ControllerAuthorizationFilter(AthenzClientFactory clientFactory, Controller controller, Set<String> allowedUrls) { super(allowedUrls); this.athenz = new AthenzFacade(clientFactory);; this.controller = controller; } @Override public Optional<ErrorResponse> filterRequest(DiscFilterRequest request) { try { Principal principal = request.getUserPrincipal(); if (principal == null) throw new ForbiddenException("Access denied."); Path path = new Path(request.getRequestURI()); Action action = Action.from(HttpRequest.Method.valueOf(request.getMethod())); // Avoid expensive lookups when request is always legal. if (RoleMembership.everyone().allows(action, request.getRequestURI())) return Optional.empty(); RoleMembership roles = new AthenzRoleResolver(athenz, controller, path).membership(principal); if (!roles.allows(action, request.getRequestURI())) { throw new ForbiddenException("Access denied"); } return Optional.empty(); } catch (WebApplicationException e) { int statusCode = e.getResponse().getStatus(); String errorMessage = e.getMessage(); log.log(LogLevel.WARNING, String.format("Access denied (%d): %s", statusCode, errorMessage)); return Optional.of(new ErrorResponse(statusCode, errorMessage)); } } // TODO: Pull class up and resolve roles from roles defined in Athenz private static class AthenzRoleResolver implements RoleMembership.Resolver { private final AthenzFacade athenz; private final TenantController tenants; private final Path path; private final SystemName system; public AthenzRoleResolver(AthenzFacade athenz, Controller controller, Path path) { this.athenz = athenz; this.tenants = controller.tenants(); this.path = path; this.system = controller.system(); } private boolean isTenantAdmin(AthenzIdentity identity, Tenant tenant) { if (tenant instanceof AthenzTenant) { return athenz.hasTenantAdminAccess(identity, ((AthenzTenant) tenant).domain()); } else if (tenant instanceof UserTenant) { if (!(identity instanceof AthenzUser)) { return false; } AthenzUser user = (AthenzUser) identity; return ((UserTenant) tenant).is(user.getName()) || isHostedOperator(identity); } throw new InternalServerErrorException("Unknown tenant type: " + tenant.getClass().getSimpleName()); } private boolean hasDeployerAccess(AthenzIdentity identity, AthenzDomain tenantDomain, ApplicationName application) { try { return athenz.hasApplicationAccess(identity, ApplicationAction.deploy, tenantDomain, application); } catch (ZmsClientException e) { throw new InternalServerErrorException("Failed to authorize operation: (" + e.getMessage() + ")", e); } } private boolean isHostedOperator(AthenzIdentity identity) { return athenz.hasHostedOperatorAccess(identity); } @Override public RoleMembership membership(Principal principal) { if ( ! (principal instanceof AthenzPrincipal)) throw new IllegalStateException("Expected an AthenzPrincipal to be set on the request."); Map<Role, Set<Context>> memberships = new HashMap<>(); AthenzIdentity identity = ((AthenzPrincipal) principal).getIdentity(); Optional<Tenant> tenant = tenant(); Context context = context(tenant); // TODO this way of computing a context is wrong, but we must // do it until we ask properly for roles based on token. Set<Context> contexts = Set.of(context); if (isHostedOperator(identity)) { memberships.put(Role.hostedOperator, contexts); } if (tenant.isPresent() && isTenantAdmin(identity, tenant.get())) { memberships.put(Role.tenantAdmin, contexts); } AthenzDomain principalDomain = identity.getDomain(); if (principalDomain.equals(SCREWDRIVER_DOMAIN)) { // NOTE: Only fine-grained deploy authorization for Athenz tenants if (context.application().isPresent() && tenant.isPresent() && tenant.get() instanceof AthenzTenant) { AthenzDomain tenantDomain = ((AthenzTenant) tenant.get()).domain(); if (hasDeployerAccess(identity, tenantDomain, context.application().get())) { memberships.put(Role.tenantPipelineOperator, contexts); } } else { memberships.put(Role.tenantPipelineOperator, contexts); } } memberships.put(Role.everyone, contexts); return new RoleMembership(memberships); } private Optional<Tenant> tenant() { if (!path.matches("/application/v4/tenant/{tenant}/{*}")) { return Optional.empty(); } return tenants.get(TenantName.from(path.get("tenant"))); } // TODO: Currently there's only one context for each role, but this will change private Context context(Optional<Tenant> tenant) { if (tenant.isEmpty()) { return Context.unlimitedIn(system); } // TODO: Remove this. Current behaviour always allows tenant full access to all its applications, but with // the new role setup, each role will include a complete context (tenant + app) if (path.matches("/application/v4/tenant/{tenant}/application/{application}/{*}")) { return Context.limitedTo(tenant.get().name(), ApplicationName.from(path.get("application")), system); } return Context.limitedTo(tenant.get().name(), system); } } private static Optional<AthenzPrincipal> principalFrom(DiscFilterRequest request) { return Optional.ofNullable(request.getUserPrincipal()) .map(AthenzPrincipal.class::cast); } }
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilter.java
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.restapi.filter; import com.google.inject.Inject; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.SystemName; import com.yahoo.config.provision.TenantName; import com.yahoo.jdisc.http.HttpRequest; import com.yahoo.jdisc.http.filter.DiscFilterRequest; import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig; import com.yahoo.jdisc.http.filter.security.cors.CorsRequestFilterBase; import com.yahoo.log.LogLevel; import com.yahoo.restapi.Path; import com.yahoo.vespa.athenz.api.AthenzDomain; import com.yahoo.vespa.athenz.api.AthenzIdentity; import com.yahoo.vespa.athenz.api.AthenzPrincipal; import com.yahoo.vespa.athenz.api.AthenzUser; import com.yahoo.vespa.athenz.client.zms.ZmsClientException; import com.yahoo.vespa.hosted.controller.Controller; import com.yahoo.vespa.hosted.controller.TenantController; import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactory; import com.yahoo.vespa.hosted.controller.athenz.ApplicationAction; import com.yahoo.vespa.hosted.controller.athenz.impl.AthenzFacade; import com.yahoo.vespa.hosted.controller.role.Action; import com.yahoo.vespa.hosted.controller.role.Context; import com.yahoo.vespa.hosted.controller.role.Role; import com.yahoo.vespa.hosted.controller.role.RoleMembership; import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant; import com.yahoo.vespa.hosted.controller.tenant.Tenant; import com.yahoo.vespa.hosted.controller.tenant.UserTenant; import com.yahoo.yolean.chain.After; import com.yahoo.yolean.chain.Provides; import javax.ws.rs.ForbiddenException; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.WebApplicationException; import java.security.Principal; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.logging.Logger; import static com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities.SCREWDRIVER_DOMAIN; /** * A security filter protects all controller apis. * * @author bjorncs */ @After("com.yahoo.vespa.hosted.controller.athenz.filter.UserAuthWithAthenzPrincipalFilter") @Provides("ControllerAuthorizationFilter") public class ControllerAuthorizationFilter extends CorsRequestFilterBase { private static final Logger log = Logger.getLogger(ControllerAuthorizationFilter.class.getName()); private final AthenzFacade athenz; private final Controller controller; @Inject public ControllerAuthorizationFilter(AthenzClientFactory clientFactory, Controller controller, CorsFilterConfig corsConfig) { this(clientFactory, controller, Set.copyOf(corsConfig.allowedUrls())); } ControllerAuthorizationFilter(AthenzClientFactory clientFactory, Controller controller, Set<String> allowedUrls) { super(allowedUrls); this.athenz = new AthenzFacade(clientFactory);; this.controller = controller; } @Override public Optional<ErrorResponse> filterRequest(DiscFilterRequest request) { try { Principal principal = request.getUserPrincipal(); if (principal == null) throw new ForbiddenException("Access denied."); Path path = new Path(request.getRequestURI()); Action action = Action.from(HttpRequest.Method.valueOf(request.getMethod())); RoleMembership roles = new AthenzRoleResolver(athenz, controller, path).membership(principal); if (!roles.allows(action, request.getRequestURI())) { throw new ForbiddenException("Access denied"); } return Optional.empty(); } catch (WebApplicationException e) { int statusCode = e.getResponse().getStatus(); String errorMessage = e.getMessage(); log.log(LogLevel.WARNING, String.format("Access denied (%d): %s", statusCode, errorMessage)); return Optional.of(new ErrorResponse(statusCode, errorMessage)); } } // TODO: Pull class up and resolve roles from roles defined in Athenz private static class AthenzRoleResolver implements RoleMembership.Resolver { private final AthenzFacade athenz; private final TenantController tenants; private final Path path; private final SystemName system; public AthenzRoleResolver(AthenzFacade athenz, Controller controller, Path path) { this.athenz = athenz; this.tenants = controller.tenants(); this.path = path; this.system = controller.system(); } private boolean isTenantAdmin(AthenzIdentity identity, Tenant tenant) { if (tenant instanceof AthenzTenant) { return athenz.hasTenantAdminAccess(identity, ((AthenzTenant) tenant).domain()); } else if (tenant instanceof UserTenant) { if (!(identity instanceof AthenzUser)) { return false; } AthenzUser user = (AthenzUser) identity; return ((UserTenant) tenant).is(user.getName()) || isHostedOperator(identity); } throw new InternalServerErrorException("Unknown tenant type: " + tenant.getClass().getSimpleName()); } private boolean hasDeployerAccess(AthenzIdentity identity, AthenzDomain tenantDomain, ApplicationName application) { try { return athenz.hasApplicationAccess(identity, ApplicationAction.deploy, tenantDomain, application); } catch (ZmsClientException e) { throw new InternalServerErrorException("Failed to authorize operation: (" + e.getMessage() + ")", e); } } private boolean isHostedOperator(AthenzIdentity identity) { return athenz.hasHostedOperatorAccess(identity); } @Override public RoleMembership membership(Principal principal) { if ( ! (principal instanceof AthenzPrincipal)) throw new IllegalStateException("Expected an AthenzPrincipal to be set on the request."); Map<Role, Set<Context>> memberships = new HashMap<>(); AthenzIdentity identity = ((AthenzPrincipal) principal).getIdentity(); Optional<Tenant> tenant = tenant(); Context context = context(tenant); // TODO this way of computing a context is wrong, but we must // do it until we ask properly for roles based on token. Set<Context> contexts = Set.of(context); if (isHostedOperator(identity)) { memberships.put(Role.hostedOperator, contexts); } if (tenant.isPresent() && isTenantAdmin(identity, tenant.get())) { memberships.put(Role.tenantAdmin, contexts); } AthenzDomain principalDomain = identity.getDomain(); if (principalDomain.equals(SCREWDRIVER_DOMAIN)) { // NOTE: Only fine-grained deploy authorization for Athenz tenants if (context.application().isPresent() && tenant.isPresent() && tenant.get() instanceof AthenzTenant) { AthenzDomain tenantDomain = ((AthenzTenant) tenant.get()).domain(); if (hasDeployerAccess(identity, tenantDomain, context.application().get())) { memberships.put(Role.tenantPipelineOperator, contexts); } } else { memberships.put(Role.tenantPipelineOperator, contexts); } } memberships.put(Role.everyone, contexts); return new RoleMembership(memberships); } private Optional<Tenant> tenant() { if (!path.matches("/application/v4/tenant/{tenant}/{*}")) { return Optional.empty(); } return tenants.get(TenantName.from(path.get("tenant"))); } // TODO: Currently there's only one context for each role, but this will change private Context context(Optional<Tenant> tenant) { if (tenant.isEmpty()) { return Context.unlimitedIn(system); } // TODO: Remove this. Current behaviour always allows tenant full access to all its applications, but with // the new role setup, each role will include a complete context (tenant + app) if (path.matches("/application/v4/tenant/{tenant}/application/{application}/{*}")) { return Context.limitedTo(tenant.get().name(), ApplicationName.from(path.get("application")), system); } return Context.limitedTo(tenant.get().name(), system); } } private static Optional<AthenzPrincipal> principalFrom(DiscFilterRequest request) { return Optional.ofNullable(request.getUserPrincipal()) .map(AthenzPrincipal.class::cast); } }
Short-circuit when everyone is authorized for the request
controller-server/src/main/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilter.java
Short-circuit when everyone is authorized for the request
Java
apache-2.0
c4223d645dd6d78a2cebdccda069fa319a85deca
0
NetoDevel/spring-boot,AstaTus/spring-boot,meftaul/spring-boot,JiweiWong/spring-boot,bclozel/spring-boot,gauravbrills/spring-boot,xialeizhou/spring-boot,RainPlanter/spring-boot,jayeshmuralidharan/spring-boot,scottfrederick/spring-boot,bbrouwer/spring-boot,scottfrederick/spring-boot,vaseemahmed01/spring-boot,zhanhb/spring-boot,philwebb/spring-boot,deki/spring-boot,mosen11/spring-boot,bbrouwer/spring-boot,roberthafner/spring-boot,huangyugui/spring-boot,nandakishorm/spring-boot,neo4j-contrib/spring-boot,damoyang/spring-boot,vandan16/Vandan,hqrt/jenkins2-course-spring-boot,ilayaperumalg/spring-boot,srikalyan/spring-boot,izestrea/spring-boot,paweldolecinski/spring-boot,cmsandiga/spring-boot,roymanish/spring-boot,mouadtk/spring-boot,roymanish/spring-boot,bijukunjummen/spring-boot,fogone/spring-boot,bjornlindstrom/spring-boot,sebastiankirsch/spring-boot,afroje-reshma/spring-boot-sample,bjornlindstrom/spring-boot,sbcoba/spring-boot,xiaoleiPENG/my-project,donhuvy/spring-boot,rickeysu/spring-boot,M3lkior/spring-boot,ApiSecRay/spring-boot,dreis2211/spring-boot,navarrogabriela/spring-boot,axibase/spring-boot,DONIKAN/spring-boot,xialeizhou/spring-boot,kiranbpatil/spring-boot,felipeg48/spring-boot,jorgepgjr/spring-boot,shangyi0102/spring-boot,lingounet/spring-boot,neo4j-contrib/spring-boot,donhuvy/spring-boot,lcardito/spring-boot,eonezhang/spring-boot,wilkinsona/spring-boot,kdvolder/spring-boot,johnktims/spring-boot,bbrouwer/spring-boot,joshiste/spring-boot,izestrea/spring-boot,kiranbpatil/spring-boot,mbrukman/spring-boot,drumonii/spring-boot,ilayaperumalg/spring-boot,gorcz/spring-boot,damoyang/spring-boot,prasenjit-net/spring-boot,donhuvy/spring-boot,mackeprm/spring-boot,nurkiewicz/spring-boot,166yuan/spring-boot,VitDevelop/spring-boot,isopov/spring-boot,jrrickard/spring-boot,izeye/spring-boot,mdeinum/spring-boot,mlc0202/spring-boot,eliudiaz/spring-boot,duandf35/spring-boot,nareshmiriyala/spring-boot,navarrogabriela/spring-boot,SPNilsen/spring-boot,vaseemahmed01/spring-boot,yangdd1205/spring-boot,candrews/spring-boot,cmsandiga/spring-boot,srikalyan/spring-boot,lburgazzoli/spring-boot,sbcoba/spring-boot,trecloux/spring-boot,bbrouwer/spring-boot,AstaTus/spring-boot,mbrukman/spring-boot,eliudiaz/spring-boot,jayeshmuralidharan/spring-boot,coolcao/spring-boot,cmsandiga/spring-boot,mabernardo/spring-boot,afroje-reshma/spring-boot-sample,MrMitchellMoore/spring-boot,5zzang/spring-boot,mosoft521/spring-boot,axelfontaine/spring-boot,ojacquemart/spring-boot,hello2009chen/spring-boot,mbogoevici/spring-boot,hehuabing/spring-boot,herau/spring-boot,nghiavo/spring-boot,philwebb/spring-boot-concourse,Buzzardo/spring-boot,vandan16/Vandan,kamilszymanski/spring-boot,shakuzen/spring-boot,ptahchiev/spring-boot,bijukunjummen/spring-boot,nebhale/spring-boot,coolcao/spring-boot,smilence1986/spring-boot,Chomeh/spring-boot,christian-posta/spring-boot,imranansari/spring-boot,Chomeh/spring-boot,VitDevelop/spring-boot,liupugong/spring-boot,mike-kukla/spring-boot,5zzang/spring-boot,kiranbpatil/spring-boot,balajinsr/spring-boot,sbuettner/spring-boot,mabernardo/spring-boot,designreuse/spring-boot,gorcz/spring-boot,M3lkior/spring-boot,deki/spring-boot,fireshort/spring-boot,michael-simons/spring-boot,meftaul/spring-boot,ralenmandao/spring-boot,lif123/spring-boot,RobertNickens/spring-boot,mosen11/spring-boot,mdeinum/spring-boot,sbuettner/spring-boot,roberthafner/spring-boot,royclarkson/spring-boot,jbovet/spring-boot,rickeysu/spring-boot,dfa1/spring-boot,philwebb/spring-boot-concourse,krmcbride/spring-boot,sankin/spring-boot,mouadtk/spring-boot,lucassaldanha/spring-boot,trecloux/spring-boot,wwadge/spring-boot,keithsjohnson/spring-boot,existmaster/spring-boot,frost2014/spring-boot,master-slave/spring-boot,tiarebalbi/spring-boot,wwadge/spring-boot,jforge/spring-boot,isopov/spring-boot,auvik/spring-boot,satheeshmb/spring-boot,nebhale/spring-boot,krmcbride/spring-boot,nebhale/spring-boot,wilkinsona/spring-boot,mbnshankar/spring-boot,liupugong/spring-boot,brettwooldridge/spring-boot,izeye/spring-boot,sbcoba/spring-boot,smilence1986/spring-boot,nelswadycki/spring-boot,kamilszymanski/spring-boot,bjornlindstrom/spring-boot,orangesdk/spring-boot,Xaerxess/spring-boot,vpavic/spring-boot,jjankar/spring-boot,Nowheresly/spring-boot,habuma/spring-boot,joansmith/spring-boot,eonezhang/spring-boot,designreuse/spring-boot,i007422/jenkins2-course-spring-boot,rstirling/spring-boot,panbiping/spring-boot,na-na/spring-boot,AngusZhu/spring-boot,satheeshmb/spring-boot,ihoneymon/spring-boot,imranansari/spring-boot,johnktims/spring-boot,qerub/spring-boot,jforge/spring-boot,hehuabing/spring-boot,mike-kukla/spring-boot,RichardCSantana/spring-boot,buobao/spring-boot,Nowheresly/spring-boot,lif123/spring-boot,felipeg48/spring-boot,prasenjit-net/spring-boot,rajendra-chola/jenkins2-course-spring-boot,duandf35/spring-boot,mevasaroj/jenkins2-course-spring-boot,mbrukman/spring-boot,drumonii/spring-boot,JiweiWong/spring-boot,cbtpro/spring-boot,lexandro/spring-boot,nareshmiriyala/spring-boot,master-slave/spring-boot,MasterRoots/spring-boot,roberthafner/spring-boot,pvorb/spring-boot,balajinsr/spring-boot,linead/spring-boot,herau/spring-boot,joshthornhill/spring-boot,imranansari/spring-boot,RishikeshDarandale/spring-boot,herau/spring-boot,jorgepgjr/spring-boot,crackien/spring-boot,rstirling/spring-boot,htynkn/spring-boot,npcode/spring-boot,spring-projects/spring-boot,nghialunhaiha/spring-boot,olivergierke/spring-boot,drunklite/spring-boot,jorgepgjr/spring-boot,coolcao/spring-boot,ptahchiev/spring-boot,joshthornhill/spring-boot,hello2009chen/spring-boot,axelfontaine/spring-boot,mosen11/spring-boot,isopov/spring-boot,isopov/spring-boot,shakuzen/spring-boot,tbadie/spring-boot,xwjxwj30abc/spring-boot,kayelau/spring-boot,hklv/spring-boot,sungha/spring-boot,chrylis/spring-boot,fulvio-m/spring-boot,thomasdarimont/spring-boot,bsodzik/spring-boot,mohican0607/spring-boot,bjornlindstrom/spring-boot,kamilszymanski/spring-boot,mlc0202/spring-boot,ralenmandao/spring-boot,jxblum/spring-boot,frost2014/spring-boot,tsachev/spring-boot,artembilan/spring-boot,ollie314/spring-boot,xingguang2013/spring-boot,jmnarloch/spring-boot,sungha/spring-boot,ApiSecRay/spring-boot,rajendra-chola/jenkins2-course-spring-boot,ameraljovic/spring-boot,sbuettner/spring-boot,soul2zimate/spring-boot,jforge/spring-boot,zhanhb/spring-boot,liupd/spring-boot,aahlenst/spring-boot,eddumelendez/spring-boot,na-na/spring-boot,jack-luj/spring-boot,meftaul/spring-boot,nebhale/spring-boot,sebastiankirsch/spring-boot,mebinjacob/spring-boot,joshiste/spring-boot,tbadie/spring-boot,jack-luj/spring-boot,roberthafner/spring-boot,mackeprm/spring-boot,tiarebalbi/spring-boot,10045125/spring-boot,trecloux/spring-boot,Xaerxess/spring-boot,bijukunjummen/spring-boot,nurkiewicz/spring-boot,qq83387856/spring-boot,akmaharshi/jenkins,durai145/spring-boot,rmoorman/spring-boot,nandakishorm/spring-boot,spring-projects/spring-boot,mabernardo/spring-boot,mbenson/spring-boot,eric-stanley/spring-boot,peteyan/spring-boot,crackien/spring-boot,philwebb/spring-boot,spring-projects/spring-boot,MasterRoots/spring-boot,jcastaldoFoodEssentials/spring-boot,nelswadycki/spring-boot,Buzzardo/spring-boot,dnsw83/spring-boot,ractive/spring-boot,existmaster/spring-boot,sebastiankirsch/spring-boot,lokbun/spring-boot,fogone/spring-boot,cleverjava/jenkins2-course-spring-boot,SaravananParthasarathy/SPSDemo,jmnarloch/spring-boot,nareshmiriyala/spring-boot,durai145/spring-boot,end-user/spring-boot,JiweiWong/spring-boot,raiamber1/spring-boot,bclozel/spring-boot,scottfrederick/spring-boot,isopov/spring-boot,spring-projects/spring-boot,MrMitchellMoore/spring-boot,AstaTus/spring-boot,smilence1986/spring-boot,liupd/spring-boot,sbcoba/spring-boot,playleud/spring-boot,ChunPIG/spring-boot,htynkn/spring-boot,cleverjava/jenkins2-course-spring-boot,drumonii/spring-boot,michael-simons/spring-boot,rajendra-chola/jenkins2-course-spring-boot,jbovet/spring-boot,jeremiahmarks/spring-boot,mbnshankar/spring-boot,playleud/spring-boot,neo4j-contrib/spring-boot,fogone/spring-boot,clarklj001/spring-boot,yhj630520/spring-boot,johnktims/spring-boot,mevasaroj/jenkins2-course-spring-boot,DeezCashews/spring-boot,forestqqqq/spring-boot,eonezhang/spring-boot,mbogoevici/spring-boot,zhangshuangquan/spring-root,eric-stanley/spring-boot,vandan16/Vandan,lingounet/spring-boot,simonnordberg/spring-boot,xiaoleiPENG/my-project,RichardCSantana/spring-boot,hklv/spring-boot,forestqqqq/spring-boot,kayelau/spring-boot,liupd/spring-boot,xc145214/spring-boot,navarrogabriela/spring-boot,tsachev/spring-boot,lexandro/spring-boot,mosoft521/spring-boot,eddumelendez/spring-boot,buobao/spring-boot,MrMitchellMoore/spring-boot,tbadie/spring-boot,vakninr/spring-boot,pvorb/spring-boot,bclozel/spring-boot,5zzang/spring-boot,paddymahoney/spring-boot,johnktims/spring-boot,tsachev/spring-boot,murilobr/spring-boot,nevenc-pivotal/spring-boot,joansmith/spring-boot,frost2014/spring-boot,eric-stanley/spring-boot,cleverjava/jenkins2-course-spring-boot,nghialunhaiha/spring-boot,gauravbrills/spring-boot,zhanhb/spring-boot,prasenjit-net/spring-boot,xdweleven/spring-boot,jrrickard/spring-boot,hqrt/jenkins2-course-spring-boot,jvz/spring-boot,jjankar/spring-boot,jxblum/spring-boot,ChunPIG/spring-boot,jvz/spring-boot,xc145214/spring-boot,murilobr/spring-boot,tbadie/spring-boot,snicoll/spring-boot,SaravananParthasarathy/SPSDemo,royclarkson/spring-boot,chrylis/spring-boot,sbuettner/spring-boot,raiamber1/spring-boot,nelswadycki/spring-boot,VitDevelop/spring-boot,meftaul/spring-boot,yunbian/spring-boot,spring-projects/spring-boot,PraveenkumarShethe/spring-boot,tiarebalbi/spring-boot,nghiavo/spring-boot,buobao/spring-boot,vandan16/Vandan,bclozel/spring-boot,brettwooldridge/spring-boot,artembilan/spring-boot,duandf35/spring-boot,jcastaldoFoodEssentials/spring-boot,vpavic/spring-boot,xwjxwj30abc/spring-boot,forestqqqq/spring-boot,mbogoevici/spring-boot,xiaoleiPENG/my-project,wwadge/spring-boot,jeremiahmarks/spring-boot,mebinjacob/spring-boot,lingounet/spring-boot,RobertNickens/spring-boot,end-user/spring-boot,pnambiarsf/spring-boot,minmay/spring-boot,Charkui/spring-boot,domix/spring-boot,paddymahoney/spring-boot,srinivasan01/spring-boot,AngusZhu/spring-boot,ydsakyclguozi/spring-boot,tan9/spring-boot,RishikeshDarandale/spring-boot,jbovet/spring-boot,sungha/spring-boot,zhangshuangquan/spring-root,joansmith/spring-boot,paddymahoney/spring-boot,qq83387856/spring-boot,SPNilsen/spring-boot,Makhlab/spring-boot,mebinjacob/spring-boot,xiaoleiPENG/my-project,rizwan18/spring-boot,donthadineshkumar/spring-boot,hello2009chen/spring-boot,npcode/spring-boot,RichardCSantana/spring-boot,krmcbride/spring-boot,mouadtk/spring-boot,eric-stanley/spring-boot,mebinjacob/spring-boot,crackien/spring-boot,mrumpf/spring-boot,DeezCashews/spring-boot,Nowheresly/spring-boot,prasenjit-net/spring-boot,nandakishorm/spring-boot,Pokbab/spring-boot,herau/spring-boot,smayoorans/spring-boot,166yuan/spring-boot,yhj630520/spring-boot,deki/spring-boot,zorosteven/spring-boot,peteyan/spring-boot,Charkui/spring-boot,thomasdarimont/spring-boot,chrylis/spring-boot,NetoDevel/spring-boot,herau/spring-boot,NetoDevel/spring-boot,pnambiarsf/spring-boot,166yuan/spring-boot,drunklite/spring-boot,rmoorman/spring-boot,marcellodesales/spring-boot,cbtpro/spring-boot,zhanhb/spring-boot,jayarampradhan/spring-boot,hello2009chen/spring-boot,joansmith/spring-boot,chrylis/spring-boot,balajinsr/spring-boot,lburgazzoli/spring-boot,vaseemahmed01/spring-boot,prasenjit-net/spring-boot,M3lkior/spring-boot,na-na/spring-boot,jbovet/spring-boot,ptahchiev/spring-boot,qerub/spring-boot,lexandro/spring-boot,vpavic/spring-boot,Makhlab/spring-boot,domix/spring-boot,mouadtk/spring-boot,npcode/spring-boot,Charkui/spring-boot,Xaerxess/spring-boot,htynkn/spring-boot,tbbost/spring-boot,nghialunhaiha/spring-boot,ollie314/spring-boot,cleverjava/jenkins2-course-spring-boot,srikalyan/spring-boot,javyzheng/spring-boot,mebinjacob/spring-boot,xc145214/spring-boot,ChunPIG/spring-boot,ralenmandao/spring-boot,xwjxwj30abc/spring-boot,akmaharshi/jenkins,mdeinum/spring-boot,10045125/spring-boot,vpavic/spring-boot,joshiste/spring-boot,liupd/spring-boot,felipeg48/spring-boot,i007422/jenkins2-course-spring-boot,axibase/spring-boot,okba1/spring-boot,candrews/spring-boot,axelfontaine/spring-boot,shangyi0102/spring-boot,pnambiarsf/spring-boot,smayoorans/spring-boot,hklv/spring-boot,axelfontaine/spring-boot,auvik/spring-boot,Chomeh/spring-boot,philwebb/spring-boot-concourse,yuxiaole/spring-boot,VitDevelop/spring-boot,hqrt/jenkins2-course-spring-boot,minmay/spring-boot,Charkui/spring-boot,dfa1/spring-boot,bbrouwer/spring-boot,candrews/spring-boot,mosoft521/spring-boot,aahlenst/spring-boot,philwebb/spring-boot,peteyan/spring-boot,mosen11/spring-boot,liupugong/spring-boot,roymanish/spring-boot,huangyugui/spring-boot,ydsakyclguozi/spring-boot,ralenmandao/spring-boot,sebastiankirsch/spring-boot,bsodzik/spring-boot,zorosteven/spring-boot,rams2588/spring-boot,DeezCashews/spring-boot,sbcoba/spring-boot,allyjunio/spring-boot,chrylis/spring-boot,paweldolecinski/spring-boot,master-slave/spring-boot,liupd/spring-boot,christian-posta/spring-boot,nurkiewicz/spring-boot,axelfontaine/spring-boot,balajinsr/spring-boot,eliudiaz/spring-boot,rizwan18/spring-boot,jvz/spring-boot,ojacquemart/spring-boot,drumonii/spring-boot,marcellodesales/spring-boot,trecloux/spring-boot,johnktims/spring-boot,allyjunio/spring-boot,nandakishorm/spring-boot,mevasaroj/jenkins2-course-spring-boot,clarklj001/spring-boot,mouadtk/spring-boot,lucassaldanha/spring-boot,JiweiWong/spring-boot,smayoorans/spring-boot,yhj630520/spring-boot,fjlopez/spring-boot,clarklj001/spring-boot,philwebb/spring-boot,xialeizhou/spring-boot,ihoneymon/spring-boot,qq83387856/spring-boot,dreis2211/spring-boot,dfa1/spring-boot,ydsakyclguozi/spring-boot,michael-simons/spring-boot,rweisleder/spring-boot,frost2014/spring-boot,huangyugui/spring-boot,mrumpf/spring-boot,ilayaperumalg/spring-boot,ralenmandao/spring-boot,vakninr/spring-boot,Xaerxess/spring-boot,rweisleder/spring-boot,DONIKAN/spring-boot,gauravbrills/spring-boot,tbbost/spring-boot,meloncocoo/spring-boot,jjankar/spring-boot,playleud/spring-boot,yangdd1205/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,eddumelendez/spring-boot,navarrogabriela/spring-boot,RainPlanter/spring-boot,ChunPIG/spring-boot,nghiavo/spring-boot,AngusZhu/spring-boot,mevasaroj/jenkins2-course-spring-boot,lenicliu/spring-boot,mohican0607/spring-boot,javyzheng/spring-boot,mrumpf/spring-boot,ilayaperumalg/spring-boot,dreis2211/spring-boot,PraveenkumarShethe/spring-boot,bijukunjummen/spring-boot,yunbian/spring-boot,kdvolder/spring-boot,rmoorman/spring-boot,okba1/spring-boot,mbrukman/spring-boot,nevenc-pivotal/spring-boot,qerub/spring-boot,jayarampradhan/spring-boot,rajendra-chola/jenkins2-course-spring-boot,cbtpro/spring-boot,RainPlanter/spring-boot,aahlenst/spring-boot,lokbun/spring-boot,minmay/spring-boot,olivergierke/spring-boot,M3lkior/spring-boot,srikalyan/spring-boot,deki/spring-boot,okba1/spring-boot,izeye/spring-boot,mrumpf/spring-boot,jorgepgjr/spring-boot,sankin/spring-boot,nghialunhaiha/spring-boot,rams2588/spring-boot,zhangshuangquan/spring-root,nisuhw/spring-boot,linead/spring-boot,rmoorman/spring-boot,huangyugui/spring-boot,nevenc-pivotal/spring-boot,mbogoevici/spring-boot,rickeysu/spring-boot,qerub/spring-boot,royclarkson/spring-boot,meloncocoo/spring-boot,na-na/spring-boot,lokbun/spring-boot,166yuan/spring-boot,na-na/spring-boot,xingguang2013/spring-boot,mike-kukla/spring-boot,srinivasan01/spring-boot,patrikbeno/spring-boot,yuxiaole/spring-boot,scottfrederick/spring-boot,donhuvy/spring-boot,NetoDevel/spring-boot,clarklj001/spring-boot,patrikbeno/spring-boot,yhj630520/spring-boot,fireshort/spring-boot,pnambiarsf/spring-boot,bclozel/spring-boot,roberthafner/spring-boot,Makhlab/spring-boot,meloncocoo/spring-boot,master-slave/spring-boot,simonnordberg/spring-boot,hqrt/jenkins2-course-spring-boot,qerub/spring-boot,RishikeshDarandale/spring-boot,srinivasan01/spring-boot,lif123/spring-boot,xwjxwj30abc/spring-boot,allyjunio/spring-boot,durai145/spring-boot,bsodzik/spring-boot,ApiSecRay/spring-boot,soul2zimate/spring-boot,ptahchiev/spring-boot,kiranbpatil/spring-boot,xingguang2013/spring-boot,imranansari/spring-boot,sbuettner/spring-boot,RobertNickens/spring-boot,SPNilsen/spring-boot,ollie314/spring-boot,roymanish/spring-boot,vpavic/spring-boot,tbbost/spring-boot,RainPlanter/spring-boot,coolcao/spring-boot,MasterRoots/spring-boot,nareshmiriyala/spring-boot,NetoDevel/spring-boot,ameraljovic/spring-boot,olivergierke/spring-boot,liupugong/spring-boot,lenicliu/spring-boot,rams2588/spring-boot,DONIKAN/spring-boot,playleud/spring-boot,joansmith/spring-boot,mosoft521/spring-boot,lucassaldanha/spring-boot,prakashme/spring-boot,jmnarloch/spring-boot,aahlenst/spring-boot,minmay/spring-boot,auvik/spring-boot,orangesdk/spring-boot,lokbun/spring-boot,keithsjohnson/spring-boot,murilobr/spring-boot,marcellodesales/spring-boot,jcastaldoFoodEssentials/spring-boot,xingguang2013/spring-boot,christian-posta/spring-boot,nisuhw/spring-boot,neo4j-contrib/spring-boot,jxblum/spring-boot,thomasdarimont/spring-boot,fulvio-m/spring-boot,donhuvy/spring-boot,javyzheng/spring-boot,ameraljovic/spring-boot,joshthornhill/spring-boot,domix/spring-boot,kayelau/spring-boot,10045125/spring-boot,cbtpro/spring-boot,sebastiankirsch/spring-boot,scottfrederick/spring-boot,jayarampradhan/spring-boot,jorgepgjr/spring-boot,damoyang/spring-boot,mrumpf/spring-boot,jayeshmuralidharan/spring-boot,akmaharshi/jenkins,166yuan/spring-boot,paddymahoney/spring-boot,tiarebalbi/spring-boot,nandakishorm/spring-boot,brettwooldridge/spring-boot,nareshmiriyala/spring-boot,Pokbab/spring-boot,philwebb/spring-boot-concourse,izestrea/spring-boot,jjankar/spring-boot,nisuhw/spring-boot,ihoneymon/spring-boot,sungha/spring-boot,izestrea/spring-boot,xdweleven/spring-boot,tbbost/spring-boot,cleverjava/jenkins2-course-spring-boot,hehuabing/spring-boot,fulvio-m/spring-boot,imranansari/spring-boot,MrMitchellMoore/spring-boot,tsachev/spring-boot,srinivasan01/spring-boot,linead/spring-boot,eliudiaz/spring-boot,PraveenkumarShethe/spring-boot,lcardito/spring-boot,MasterRoots/spring-boot,gauravbrills/spring-boot,vakninr/spring-boot,habuma/spring-boot,cbtpro/spring-boot,sankin/spring-boot,crackien/spring-boot,felipeg48/spring-boot,artembilan/spring-boot,mlc0202/spring-boot,rweisleder/spring-boot,nurkiewicz/spring-boot,habuma/spring-boot,fjlopez/spring-boot,fireshort/spring-boot,Chomeh/spring-boot,Pokbab/spring-boot,dnsw83/spring-boot,rstirling/spring-boot,dnsw83/spring-boot,jxblum/spring-boot,fulvio-m/spring-boot,mbenson/spring-boot,mdeinum/spring-boot,bjornlindstrom/spring-boot,joshiste/spring-boot,mackeprm/spring-boot,vandan16/Vandan,cmsandiga/spring-boot,okba1/spring-boot,shakuzen/spring-boot,ameraljovic/spring-boot,snicoll/spring-boot,rickeysu/spring-boot,lenicliu/spring-boot,aahlenst/spring-boot,RobertNickens/spring-boot,dreis2211/spring-boot,axibase/spring-boot,smayoorans/spring-boot,lif123/spring-boot,jmnarloch/spring-boot,linead/spring-boot,nevenc-pivotal/spring-boot,vakninr/spring-boot,yuxiaole/spring-boot,Pokbab/spring-boot,DONIKAN/spring-boot,pvorb/spring-boot,SaravananParthasarathy/SPSDemo,philwebb/spring-boot,ollie314/spring-boot,candrews/spring-boot,qq83387856/spring-boot,coolcao/spring-boot,ojacquemart/spring-boot,SaravananParthasarathy/SPSDemo,nelswadycki/spring-boot,jeremiahmarks/spring-boot,brettwooldridge/spring-boot,RainPlanter/spring-boot,lexandro/spring-boot,JiweiWong/spring-boot,patrikbeno/spring-boot,auvik/spring-boot,clarklj001/spring-boot,thomasdarimont/spring-boot,shangyi0102/spring-boot,xdweleven/spring-boot,snicoll/spring-boot,rizwan18/spring-boot,drumonii/spring-boot,ihoneymon/spring-boot,prakashme/spring-boot,Makhlab/spring-boot,MrMitchellMoore/spring-boot,kayelau/spring-boot,jrrickard/spring-boot,i007422/jenkins2-course-spring-boot,keithsjohnson/spring-boot,nghiavo/spring-boot,ptahchiev/spring-boot,xingguang2013/spring-boot,axibase/spring-boot,duandf35/spring-boot,minmay/spring-boot,mohican0607/spring-boot,mbenson/spring-boot,auvik/spring-boot,tbbost/spring-boot,jbovet/spring-boot,smilence1986/spring-boot,meftaul/spring-boot,mohican0607/spring-boot,paweldolecinski/spring-boot,htynkn/spring-boot,michael-simons/spring-boot,rickeysu/spring-boot,bijukunjummen/spring-boot,Pokbab/spring-boot,huangyugui/spring-boot,shakuzen/spring-boot,rams2588/spring-boot,lif123/spring-boot,jayeshmuralidharan/spring-boot,xdweleven/spring-boot,dfa1/spring-boot,yunbian/spring-boot,izeye/spring-boot,brettwooldridge/spring-boot,jrrickard/spring-boot,tsachev/spring-boot,royclarkson/spring-boot,mbrukman/spring-boot,spring-projects/spring-boot,soul2zimate/spring-boot,paweldolecinski/spring-boot,qq83387856/spring-boot,jayeshmuralidharan/spring-boot,ilayaperumalg/spring-boot,mevasaroj/jenkins2-course-spring-boot,frost2014/spring-boot,dfa1/spring-boot,mackeprm/spring-boot,meloncocoo/spring-boot,cmsandiga/spring-boot,tan9/spring-boot,artembilan/spring-boot,rweisleder/spring-boot,tbadie/spring-boot,xc145214/spring-boot,axibase/spring-boot,peteyan/spring-boot,deki/spring-boot,mlc0202/spring-boot,hklv/spring-boot,habuma/spring-boot,trecloux/spring-boot,roymanish/spring-boot,bclozel/spring-boot,ojacquemart/spring-boot,fireshort/spring-boot,fjlopez/spring-boot,patrikbeno/spring-boot,afroje-reshma/spring-boot-sample,mbenson/spring-boot,lingounet/spring-boot,michael-simons/spring-boot,panbiping/spring-boot,sankin/spring-boot,wilkinsona/spring-boot,shangyi0102/spring-boot,nisuhw/spring-boot,ihoneymon/spring-boot,mosen11/spring-boot,rajendra-chola/jenkins2-course-spring-boot,dnsw83/spring-boot,lburgazzoli/spring-boot,joshthornhill/spring-boot,lucassaldanha/spring-boot,murilobr/spring-boot,htynkn/spring-boot,domix/spring-boot,prakashme/spring-boot,drumonii/spring-boot,jxblum/spring-boot,jxblum/spring-boot,akmaharshi/jenkins,fireshort/spring-boot,end-user/spring-boot,simonnordberg/spring-boot,hklv/spring-boot,RobertNickens/spring-boot,mdeinum/spring-boot,jack-luj/spring-boot,PraveenkumarShethe/spring-boot,lingounet/spring-boot,habuma/spring-boot,gorcz/spring-boot,shakuzen/spring-boot,isopov/spring-boot,mbenson/spring-boot,existmaster/spring-boot,wwadge/spring-boot,DeezCashews/spring-boot,yunbian/spring-boot,izestrea/spring-boot,jmnarloch/spring-boot,Nowheresly/spring-boot,eonezhang/spring-boot,yunbian/spring-boot,5zzang/spring-boot,Buzzardo/spring-boot,allyjunio/spring-boot,gorcz/spring-boot,ractive/spring-boot,hehuabing/spring-boot,eonezhang/spring-boot,gregturn/spring-boot,SPNilsen/spring-boot,ilayaperumalg/spring-boot,dreis2211/spring-boot,satheeshmb/spring-boot,fogone/spring-boot,xwjxwj30abc/spring-boot,Xaerxess/spring-boot,bsodzik/spring-boot,lcardito/spring-boot,fjlopez/spring-boot,murilobr/spring-boot,yhj630520/spring-boot,eric-stanley/spring-boot,pnambiarsf/spring-boot,joshiste/spring-boot,shangyi0102/spring-boot,krmcbride/spring-boot,mbenson/spring-boot,rams2588/spring-boot,lcardito/spring-boot,javyzheng/spring-boot,christian-posta/spring-boot,vaseemahmed01/spring-boot,thomasdarimont/spring-boot,orangesdk/spring-boot,gorcz/spring-boot,mbnshankar/spring-boot,navarrogabriela/spring-boot,ihoneymon/spring-boot,fogone/spring-boot,ChunPIG/spring-boot,designreuse/spring-boot,lexandro/spring-boot,drunklite/spring-boot,SPNilsen/spring-boot,dreis2211/spring-boot,DeezCashews/spring-boot,VitDevelop/spring-boot,htynkn/spring-boot,hehuabing/spring-boot,raiamber1/spring-boot,domix/spring-boot,rstirling/spring-boot,wilkinsona/spring-boot,wwadge/spring-boot,jvz/spring-boot,tsachev/spring-boot,durai145/spring-boot,ameraljovic/spring-boot,jjankar/spring-boot,end-user/spring-boot,balajinsr/spring-boot,philwebb/spring-boot-concourse,ollie314/spring-boot,nghialunhaiha/spring-boot,xialeizhou/spring-boot,dnsw83/spring-boot,xc145214/spring-boot,jeremiahmarks/spring-boot,felipeg48/spring-boot,tiarebalbi/spring-boot,orangesdk/spring-boot,rstirling/spring-boot,npcode/spring-boot,RichardCSantana/spring-boot,jeremiahmarks/spring-boot,hello2009chen/spring-boot,chrylis/spring-boot,izeye/spring-boot,jack-luj/spring-boot,srikalyan/spring-boot,forestqqqq/spring-boot,mabernardo/spring-boot,kiranbpatil/spring-boot,joshiste/spring-boot,kamilszymanski/spring-boot,philwebb/spring-boot,end-user/spring-boot,designreuse/spring-boot,ApiSecRay/spring-boot,RichardCSantana/spring-boot,prakashme/spring-boot,panbiping/spring-boot,lenicliu/spring-boot,zhangshuangquan/spring-root,buobao/spring-boot,lburgazzoli/spring-boot,jforge/spring-boot,satheeshmb/spring-boot,Makhlab/spring-boot,damoyang/spring-boot,mabernardo/spring-boot,simonnordberg/spring-boot,eddumelendez/spring-boot,Chomeh/spring-boot,smayoorans/spring-boot,xialeizhou/spring-boot,simonnordberg/spring-boot,soul2zimate/spring-boot,donthadineshkumar/spring-boot,sankin/spring-boot,jrrickard/spring-boot,master-slave/spring-boot,drunklite/spring-boot,jvz/spring-boot,eddumelendez/spring-boot,gregturn/spring-boot,mohican0607/spring-boot,jayarampradhan/spring-boot,olivergierke/spring-boot,aahlenst/spring-boot,pvorb/spring-boot,linead/spring-boot,existmaster/spring-boot,lburgazzoli/spring-boot,jack-luj/spring-boot,Buzzardo/spring-boot,tan9/spring-boot,eliudiaz/spring-boot,durai145/spring-boot,npcode/spring-boot,vaseemahmed01/spring-boot,marcellodesales/spring-boot,mosoft521/spring-boot,krmcbride/spring-boot,ractive/spring-boot,gregturn/spring-boot,yangdd1205/spring-boot,kayelau/spring-boot,eddumelendez/spring-boot,xiaoleiPENG/my-project,donhuvy/spring-boot,nevenc-pivotal/spring-boot,kdvolder/spring-boot,jforge/spring-boot,nebhale/spring-boot,candrews/spring-boot,kdvolder/spring-boot,mike-kukla/spring-boot,jayarampradhan/spring-boot,M3lkior/spring-boot,jcastaldoFoodEssentials/spring-boot,okba1/spring-boot,lcardito/spring-boot,allyjunio/spring-boot,meloncocoo/spring-boot,pvorb/spring-boot,Nowheresly/spring-boot,donthadineshkumar/spring-boot,ojacquemart/spring-boot,rmoorman/spring-boot,akmaharshi/jenkins,joshthornhill/spring-boot,PraveenkumarShethe/spring-boot,paweldolecinski/spring-boot,zhanhb/spring-boot,SaravananParthasarathy/SPSDemo,existmaster/spring-boot,tiarebalbi/spring-boot,raiamber1/spring-boot,donthadineshkumar/spring-boot,RishikeshDarandale/spring-boot,javyzheng/spring-boot,liupugong/spring-boot,mlc0202/spring-boot,MasterRoots/spring-boot,habuma/spring-boot,vakninr/spring-boot,afroje-reshma/spring-boot-sample,lucassaldanha/spring-boot,keithsjohnson/spring-boot,playleud/spring-boot,mike-kukla/spring-boot,rizwan18/spring-boot,fulvio-m/spring-boot,artembilan/spring-boot,Buzzardo/spring-boot,panbiping/spring-boot,lenicliu/spring-boot,wilkinsona/spring-boot,panbiping/spring-boot,ractive/spring-boot,fjlopez/spring-boot,forestqqqq/spring-boot,mbnshankar/spring-boot,tan9/spring-boot,xdweleven/spring-boot,ydsakyclguozi/spring-boot,mackeprm/spring-boot,kamilszymanski/spring-boot,mbnshankar/spring-boot,duandf35/spring-boot,wilkinsona/spring-boot,yuxiaole/spring-boot,srinivasan01/spring-boot,rizwan18/spring-boot,rweisleder/spring-boot,royclarkson/spring-boot,felipeg48/spring-boot,jcastaldoFoodEssentials/spring-boot,ptahchiev/spring-boot,olivergierke/spring-boot,scottfrederick/spring-boot,zorosteven/spring-boot,prakashme/spring-boot,Charkui/spring-boot,raiamber1/spring-boot,hqrt/jenkins2-course-spring-boot,AngusZhu/spring-boot,christian-posta/spring-boot,DONIKAN/spring-boot,soul2zimate/spring-boot,peteyan/spring-boot,sungha/spring-boot,lokbun/spring-boot,zhanhb/spring-boot,tan9/spring-boot,bsodzik/spring-boot,smilence1986/spring-boot,zhangshuangquan/spring-root,yuxiaole/spring-boot,AstaTus/spring-boot,kdvolder/spring-boot,satheeshmb/spring-boot,shakuzen/spring-boot,ractive/spring-boot,damoyang/spring-boot,AstaTus/spring-boot,patrikbeno/spring-boot,paddymahoney/spring-boot,orangesdk/spring-boot,marcellodesales/spring-boot,nelswadycki/spring-boot,zorosteven/spring-boot,michael-simons/spring-boot,ydsakyclguozi/spring-boot,zorosteven/spring-boot,gauravbrills/spring-boot,mdeinum/spring-boot,designreuse/spring-boot,ApiSecRay/spring-boot,rweisleder/spring-boot,nghiavo/spring-boot,donthadineshkumar/spring-boot,kdvolder/spring-boot,i007422/jenkins2-course-spring-boot,5zzang/spring-boot,drunklite/spring-boot,AngusZhu/spring-boot,crackien/spring-boot,RishikeshDarandale/spring-boot,neo4j-contrib/spring-boot,afroje-reshma/spring-boot-sample,mbogoevici/spring-boot,buobao/spring-boot,keithsjohnson/spring-boot,nisuhw/spring-boot,i007422/jenkins2-course-spring-boot,nurkiewicz/spring-boot
/* * Copyright 2012-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.websocket; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContainerInitializer; import org.apache.catalina.Context; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ClassUtils; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.server.config.EnableWebSocket; import org.springframework.web.socket.server.config.WebSocketConfigurer; import org.springframework.web.socket.server.config.WebSocketHandlerRegistry; import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService; /** * Auto configuration for websockets (and sockjs in particular). Users should be able to * just define beans of type {@link WebSocketHandler}. If <code>spring-websocket</code> is * detected on the classpath then we add a {@link DefaultSockJsService} and an MVC handler * mapping to <code>/&lt;beanName&gt;/**</code> for all of the * <code>WebSocketHandler</code> beans that have a bean name beginning with "/". * * @author Dave Syer */ @Configuration @ConditionalOnClass({ WebSocketHandler.class }) @AutoConfigureBefore(EmbeddedServletContainerAutoConfiguration.class) @ConditionalOnMissingBean(WebSocketConfigurer.class) @EnableWebSocket public class WebSocketAutoConfiguration { private static Log logger = LogFactory.getLog(WebSocketAutoConfiguration.class); // Nested class to avoid having to load WebSocketConfigurer before conditions are // evaluated @Configuration protected static class WebSocketRegistrationConfiguration implements BeanPostProcessor, BeanFactoryAware, WebSocketConfigurer { private Map<String, WebSocketHandler> prefixes = new HashMap<String, WebSocketHandler>(); private ListableBeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = (ListableBeanFactory) beanFactory; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebSocketHandler && beanName.startsWith("/")) { this.prefixes.put(beanName, (WebSocketHandler) bean); } return bean; } private WebSocketHandler getHandler(String prefix) { return this.prefixes.get(prefix); } private String[] getPrefixes() { return this.prefixes.keySet().toArray(new String[this.prefixes.size()]); } @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { // Force initialization of WebSocketHandler beans this.beanFactory.getBeansOfType(WebSocketHandler.class); for (String prefix : getPrefixes()) { logger.info("Adding SockJS handler: " + prefix); registry.addHandler(getHandler(prefix), prefix).withSockJS(); } } } @Configuration @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci") protected static class TomcatWebSocketConfiguration { @Bean public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { context.addServletContainerInitializer( (ServletContainerInitializer) BeanUtils .instantiate(ClassUtils.resolveClassName( "org.apache.tomcat.websocket.server.WsSci", null)), null); } }; return factory; } } }
spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java
/* * Copyright 2012-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.autoconfigure.websocket; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContainerInitializer; import org.apache.catalina.Context; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.util.ClassUtils; import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.sockjs.SockJsHttpRequestHandler; import org.springframework.web.socket.sockjs.SockJsService; import org.springframework.web.socket.sockjs.support.AbstractSockJsService; import org.springframework.web.socket.sockjs.transport.handler.DefaultSockJsService; /** * Auto configuration for websockets (and sockjs in particular). Users should be able to * just define beans of type {@link WebSocketHandler}. If <code>spring-websocket</code> is * detected on the classpath then we add a {@link DefaultSockJsService} and an MVC handler * mapping to <code>/&lt;beanName&gt;/**</code> for all of the * <code>WebSocketHandler</code> beans that have a bean name beginning with "/". * * @author Dave Syer */ @Configuration @ConditionalOnClass({ WebSocketHandler.class }) @AutoConfigureBefore(EmbeddedServletContainerAutoConfiguration.class) public class WebSocketAutoConfiguration { private static class WebSocketEndpointPostProcessor implements BeanPostProcessor { private Map<String, WebSocketHandler> prefixes = new HashMap<String, WebSocketHandler>(); @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebSocketHandler && beanName.startsWith("/")) { this.prefixes.put(beanName, (WebSocketHandler) bean); } return bean; } public WebSocketHandler getHandler(String prefix) { return this.prefixes.get(prefix); } public String[] getPrefixes() { return this.prefixes.keySet().toArray(new String[this.prefixes.size()]); } } @Bean public WebSocketEndpointPostProcessor webSocketEndpointPostProcessor() { return new WebSocketEndpointPostProcessor(); } @Bean @ConditionalOnMissingBean(SockJsService.class) public DefaultSockJsService sockJsService() { DefaultSockJsService service = new DefaultSockJsService(sockJsTaskScheduler()); service.setSockJsClientLibraryUrl("https://cdn.sockjs.org/sockjs-0.3.4.min.js"); service.setWebSocketsEnabled(true); return service; } @Bean public SimpleUrlHandlerMapping handlerMapping(SockJsService sockJsService, Collection<WebSocketHandler> handlers) { WebSocketEndpointPostProcessor processor = webSocketEndpointPostProcessor(); Map<String, Object> urlMap = new HashMap<String, Object>(); for (String prefix : webSocketEndpointPostProcessor().getPrefixes()) { urlMap.put(prefix + "/**", new SockJsHttpRequestHandler(sockJsService, processor.getHandler(prefix))); } if (sockJsService instanceof AbstractSockJsService) { ((AbstractSockJsService) sockJsService).setValidSockJsPrefixes(processor .getPrefixes()); } SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping(); handlerMapping.setOrder(-1); handlerMapping.setUrlMap(urlMap); return handlerMapping; } @Bean @ConditionalOnMissingBean(name = "sockJsTaskScheduler") public ThreadPoolTaskScheduler sockJsTaskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setThreadNamePrefix("SockJS-"); return taskScheduler; } @Configuration @ConditionalOnClass(name = "org.apache.tomcat.websocket.server.WsSci") protected static class TomcatWebSocketConfiguration { @Bean public TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory() { TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { context.addServletContainerInitializer( (ServletContainerInitializer) BeanUtils .instantiate(ClassUtils.resolveClassName( "org.apache.tomcat.websocket.server.WsSci", null)), null); } }; return factory; } } }
Updated WebSocketAutoConfiguration to use @EnableWebSocket
spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/websocket/WebSocketAutoConfiguration.java
Updated WebSocketAutoConfiguration to use @EnableWebSocket
Java
apache-2.0
2e34edb741a4b4f5fc195514d718d6e269f2f36a
0
nhl/link-rest
package io.agrest; import io.agrest.encoder.EntityEncoderFilter; import io.agrest.meta.AgAttribute; import io.agrest.meta.AgEntity; import io.agrest.meta.AgRelationship; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.query.Ordering; import org.apache.cayenne.query.SelectQuery; import org.apache.cayenne.util.ToStringBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A metadata object that describes a data structure of a given REST resource. Connected ResourceEntities form a * tree structure that usually overlays a certain Cayenne mapping subgraph (unless this is a non-persistent entity), * filtering and extending its properties to describe the data structure to be returned to the client. * <p> * ResourceEntity scope is a single request. It is usually created by Agrest based on request parameters and can be * optionally further customized by the application via custom stages. */ public class ResourceEntity<T> { private boolean idIncluded; private AgEntity<T> agEntity; private Map<String, AgAttribute> attributes; private Collection<String> defaultProperties; private String applicationBase; private String mapByPath; private ResourceEntity<?> mapBy; private Map<String, ResourceEntity<?>> children; private AgRelationship incoming; private List<Ordering> orderings; private Expression qualifier; private Map<String, EntityProperty> includedExtraProperties; private Map<String, EntityProperty> extraProperties; private int fetchOffset; private int fetchLimit; private List<EntityEncoderFilter> entityEncoderFilters; private SelectQuery<T> select; private List<T> result; private Map<AgObjectId, Object> parentToChildResult; public ResourceEntity(AgEntity<T> agEntity) { this.idIncluded = false; this.attributes = new HashMap<>(); this.defaultProperties = new HashSet<>(); this.children = new HashMap<>(); this.orderings = new ArrayList<>(2); this.extraProperties = new HashMap<>(); this.includedExtraProperties = new HashMap<>(); this.agEntity = agEntity; this.result = new ArrayList<>(); this.parentToChildResult = new LinkedHashMap<>(); this.entityEncoderFilters = new ArrayList<>(3); } public ResourceEntity(AgEntity<T> agEntity, AgRelationship incoming) { this(agEntity); this.incoming = incoming; } /** * @since 3.4 */ public String getName() { return agEntity.getName(); } /** * @since 1.12 */ public AgEntity<T> getAgEntity() { return agEntity; } public AgRelationship getIncoming() { return incoming; } public Expression getQualifier() { return qualifier; } /** * Resets the qualifier for the entity to a new one. * * @param qualifier a new qualifier expression. Can be null. * @since 2.7 */ public void setQualifier(Expression qualifier) { this.qualifier = qualifier; } public void andQualifier(Expression qualifier) { if (this.qualifier == null) { this.qualifier = qualifier; } else { this.qualifier = this.qualifier.andExp(qualifier); } } public List<Ordering> getOrderings() { return orderings; } public SelectQuery<T> getSelect() { return select; } public void setSelect(SelectQuery<T> select) { this.select = select; } /** * @since 3.1 */ public List<T> getResult() { return result; } /** * @param result objects * @since 3.1 */ public void setResult(List<T> result) { this.result = result; } /** * @param parentId * @return * @since 3.1 */ public Object getResult(AgObjectId parentId) { return parentToChildResult.get(parentId); } /** * @param parentId * @param object * @since 3.1 * Stores object related to particular parent object. * It is used for one-to-one relation between a parent and a child. */ public void setToOneResult(AgObjectId parentId, T object) { parentToChildResult.put(parentId, object); } /** * Stores result object as a List of objects. It is used for one-to-many relation between a parent and children. * * @param parentId * @param object * @since 3.1 */ public void addToManyResult(AgObjectId parentId, T object) { ((List<T>) parentToChildResult.computeIfAbsent(parentId, k -> new ArrayList<>())).add(object); } /** * @param parentId * @param objects * @since 3.1 */ public void setToManyResult(AgObjectId parentId, List<T> objects) { parentToChildResult.put(parentId, objects); } /** * @since 1.12 */ public Map<String, AgAttribute> getAttributes() { return attributes; } /** * @since 1.5 */ public Collection<String> getDefaultProperties() { return defaultProperties; } /** * @since 1.5 */ public boolean isDefault(String propertyName) { return defaultProperties.contains(propertyName); } public Map<String, ResourceEntity<?>> getChildren() { return children; } /** * @since 1.1 */ public ResourceEntity<?> getChild(String name) { return children.get(name); } public Map<String, EntityProperty> getExtraProperties() { return extraProperties; } public Map<String, EntityProperty> getIncludedExtraProperties() { return includedExtraProperties; } public boolean isIdIncluded() { return idIncluded; } public ResourceEntity<T> includeId(boolean include) { this.idIncluded = include; return this; } public ResourceEntity<T> includeId() { this.idIncluded = true; return this; } public ResourceEntity<T> excludeId() { this.idIncluded = false; return this; } public ResourceEntity<?> getMapBy() { return mapBy; } /** * @since 1.1 */ public ResourceEntity<T> mapBy(ResourceEntity<?> mapBy, String mapByPath) { this.mapByPath = mapByPath; this.mapBy = mapBy; return this; } public String getMapByPath() { return mapByPath; } @Override public String toString() { ToStringBuilder tsb = new ToStringBuilder(this); if (agEntity != null) { tsb.append("name", agEntity.getName()); } return tsb.toString(); } public Class<T> getType() { return agEntity.getType(); } /** * @since 1.20 */ public int getFetchOffset() { return fetchOffset; } /** * @since 1.20 */ public void setFetchOffset(int fetchOffset) { this.fetchOffset = fetchOffset; } /** * @since 1.20 */ public int getFetchLimit() { return fetchLimit; } /** * @since 1.20 */ public void setFetchLimit(int fetchLimit) { this.fetchLimit = fetchLimit; } /** * @since 1.20 */ public String getApplicationBase() { return applicationBase; } /** * @since 1.20 */ public void setApplicationBase(String applicationBase) { this.applicationBase = applicationBase; } /** * @since 1.23 */ public boolean isFiltered() { return !entityEncoderFilters.isEmpty(); } /** * @since 3.4 */ public List<EntityEncoderFilter> getEntityEncoderFilters() { return entityEncoderFilters; } }
agrest/src/main/java/io/agrest/ResourceEntity.java
package io.agrest; import io.agrest.encoder.EntityEncoderFilter; import io.agrest.meta.AgAttribute; import io.agrest.meta.AgEntity; import io.agrest.meta.AgRelationship; import org.apache.cayenne.exp.Expression; import org.apache.cayenne.query.Ordering; import org.apache.cayenne.query.SelectQuery; import org.apache.cayenne.util.ToStringBuilder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A metadata object that describes a data structure of a given REST resource. * Connected ResourceEntities form a tree-like structure that usually overlays a * certain Cayenne mapping subgraph (unless this is a non-persistent entity), * filtering and extending its properties to describe the data structure to be * returned to the client. * <p> * ResourceEntity scope is a single request. It is usually created by Agrest based on request parameters and can be * optionally further customized by the application via custom stages. */ public class ResourceEntity<T> { private boolean idIncluded; private AgEntity<T> agEntity; private Map<String, AgAttribute> attributes; private Collection<String> defaultProperties; private String applicationBase; private String mapByPath; private ResourceEntity<?> mapBy; private Map<String, ResourceEntity<?>> children; private AgRelationship incoming; private List<Ordering> orderings; private Expression qualifier; private Map<String, EntityProperty> includedExtraProperties; private Map<String, EntityProperty> extraProperties; private int fetchOffset; private int fetchLimit; private List<EntityEncoderFilter> entityEncoderFilters; private SelectQuery<T> select; private List<T> result; private Map<AgObjectId, Object> parentToChildResult; public ResourceEntity(AgEntity<T> agEntity) { this.idIncluded = false; this.attributes = new HashMap<>(); this.defaultProperties = new HashSet<>(); this.children = new HashMap<>(); this.orderings = new ArrayList<>(2); this.extraProperties = new HashMap<>(); this.includedExtraProperties = new HashMap<>(); this.agEntity = agEntity; this.result = new ArrayList<>(); this.parentToChildResult = new LinkedHashMap<>(); this.entityEncoderFilters = new ArrayList<>(3); } public ResourceEntity(AgEntity<T> agEntity, AgRelationship incoming) { this(agEntity); this.incoming = incoming; } /** * @since 3.4 */ public String getName() { return agEntity.getName(); } /** * @since 1.12 */ public AgEntity<T> getAgEntity() { return agEntity; } public AgRelationship getIncoming() { return incoming; } public Expression getQualifier() { return qualifier; } /** * Resets the qualifier for the entity to a new one. * * @param qualifier a new qualifier expression. Can be null. * @since 2.7 */ public void setQualifier(Expression qualifier) { this.qualifier = qualifier; } public void andQualifier(Expression qualifier) { if (this.qualifier == null) { this.qualifier = qualifier; } else { this.qualifier = this.qualifier.andExp(qualifier); } } public List<Ordering> getOrderings() { return orderings; } public SelectQuery<T> getSelect() { return select; } public void setSelect(SelectQuery<T> select) { this.select = select; } /** * @since 3.1 */ public List<T> getResult() { return result; } /** * @param result objects * @since 3.1 */ public void setResult(List<T> result) { this.result = result; } /** * @param parentId * @return * @since 3.1 */ public Object getResult(AgObjectId parentId) { return parentToChildResult.get(parentId); } /** * @param parentId * @param object * @since 3.1 * Stores object related to particular parent object. * It is used for one-to-one relation between a parent and a child. */ public void setToOneResult(AgObjectId parentId, T object) { parentToChildResult.put(parentId, object); } /** * Stores result object as a List of objects. It is used for one-to-many relation between a parent and children. * * @param parentId * @param object * @since 3.1 */ public void addToManyResult(AgObjectId parentId, T object) { ((List<T>) parentToChildResult.computeIfAbsent(parentId, k -> new ArrayList<>())).add(object); } /** * @param parentId * @param objects * @since 3.1 */ public void setToManyResult(AgObjectId parentId, List<T> objects) { parentToChildResult.put(parentId, objects); } /** * @since 1.12 */ public Map<String, AgAttribute> getAttributes() { return attributes; } /** * @since 1.5 */ public Collection<String> getDefaultProperties() { return defaultProperties; } /** * @since 1.5 */ public boolean isDefault(String propertyName) { return defaultProperties.contains(propertyName); } public Map<String, ResourceEntity<?>> getChildren() { return children; } /** * @since 1.1 */ public ResourceEntity<?> getChild(String name) { return children.get(name); } public Map<String, EntityProperty> getExtraProperties() { return extraProperties; } public Map<String, EntityProperty> getIncludedExtraProperties() { return includedExtraProperties; } public boolean isIdIncluded() { return idIncluded; } public ResourceEntity<T> includeId(boolean include) { this.idIncluded = include; return this; } public ResourceEntity<T> includeId() { this.idIncluded = true; return this; } public ResourceEntity<T> excludeId() { this.idIncluded = false; return this; } public ResourceEntity<?> getMapBy() { return mapBy; } /** * @since 1.1 */ public ResourceEntity<T> mapBy(ResourceEntity<?> mapBy, String mapByPath) { this.mapByPath = mapByPath; this.mapBy = mapBy; return this; } public String getMapByPath() { return mapByPath; } @Override public String toString() { ToStringBuilder tsb = new ToStringBuilder(this); if (agEntity != null) { tsb.append("name", agEntity.getName()); } return tsb.toString(); } public Class<T> getType() { return agEntity.getType(); } /** * @since 1.20 */ public int getFetchOffset() { return fetchOffset; } /** * @since 1.20 */ public void setFetchOffset(int fetchOffset) { this.fetchOffset = fetchOffset; } /** * @since 1.20 */ public int getFetchLimit() { return fetchLimit; } /** * @since 1.20 */ public void setFetchLimit(int fetchLimit) { this.fetchLimit = fetchLimit; } /** * @since 1.20 */ public String getApplicationBase() { return applicationBase; } /** * @since 1.20 */ public void setApplicationBase(String applicationBase) { this.applicationBase = applicationBase; } /** * @since 1.23 */ public boolean isFiltered() { return !entityEncoderFilters.isEmpty(); } /** * @since 3.4 */ public List<EntityEncoderFilter> getEntityEncoderFilters() { return entityEncoderFilters; } }
cleanup
agrest/src/main/java/io/agrest/ResourceEntity.java
cleanup
Java
bsd-3-clause
ef60b3ce58f6a33da320f641834862acb16efb86
0
NCIP/c3pr,NCIP/c3pr,NCIP/c3pr
package edu.duke.cabig.c3pr.domain.repository.impl; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.persistence.Transient; import org.apache.log4j.Logger; import org.springframework.context.MessageSource; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.constants.APIName; import edu.duke.cabig.c3pr.constants.RandomizationType; import edu.duke.cabig.c3pr.constants.RegistrationDataEntryStatus; import edu.duke.cabig.c3pr.constants.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.constants.ScheduledEpochDataEntryStatus; import edu.duke.cabig.c3pr.constants.ScheduledEpochWorkFlowStatus; import edu.duke.cabig.c3pr.constants.ServiceName; import edu.duke.cabig.c3pr.constants.WorkFlowStatusType; import edu.duke.cabig.c3pr.dao.EpochDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.StratumGroupDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Arm; import edu.duke.cabig.c3pr.domain.BookRandomization; import edu.duke.cabig.c3pr.domain.BookRandomizationEntry; import edu.duke.cabig.c3pr.domain.EndPoint; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.Study; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.SystemAssignedIdentifier; import edu.duke.cabig.c3pr.domain.factory.StudySubjectFactory; import edu.duke.cabig.c3pr.domain.repository.StudySubjectRepository; import edu.duke.cabig.c3pr.exception.C3PRBaseException; import edu.duke.cabig.c3pr.exception.C3PRBaseRuntimeException; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.service.StudySubjectService; import edu.duke.cabig.c3pr.utils.IdentifierGenerator; import edu.duke.cabig.c3pr.utils.StudyTargetAccrualNotificationEmail; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; @Transactional public class StudySubjectRepositoryImpl implements StudySubjectRepository { private StudySubjectDao studySubjectDao; private ParticipantDao participantDao; private EpochDao epochDao; private StratumGroupDao stratumGroupDao; private C3PRExceptionHelper exceptionHelper; private MessageSource c3prErrorMessages; private StudySubjectFactory studySubjectFactory; private StudySubjectService studySubjectService; private StudyTargetAccrualNotificationEmail notificationEmailer; private IdentifierGenerator identifierGenerator ; //private StudyService studyService; private Logger log = Logger.getLogger(StudySubjectRepositoryImpl.class.getName()); public void assignC3DIdentifier(StudySubject studySubject, String c3dIdentifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setC3DIdentifier(c3dIdentifierValue); studySubjectDao.save(loadedSubject); } public void assignCoOrdinatingCenterIdentifier(StudySubject studySubject, String identifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setCoOrdinatingCenterIdentifier(identifierValue); studySubjectDao.save(loadedSubject); } public boolean isEpochAccrualCeilingReached(int epochId) { Epoch epoch = epochDao.getById(epochId); if (epoch.isReserving()) { ScheduledEpoch scheduledEpoch = new ScheduledEpoch(true); scheduledEpoch.setEpoch(epoch); List<StudySubject> list = studySubjectDao.searchByScheduledEpoch(scheduledEpoch); Epoch nEpoch = epoch; if (nEpoch.getAccrualCeiling() != null && list.size() >= nEpoch.getAccrualCeiling().intValue()) { return true; } } return false; } public StudySubject doLocalRegistration(StudySubject studySubject) throws C3PRCodedException { continueEnrollment(studySubject); return studySubject; } /** * Saves the Imported StudySubject to the database. Moved it from the service as a part of the * refactoring effort. * * @param deserialedStudySubject * @return * @throws C3PRCodedException */ @Transactional(readOnly = false) public StudySubject importStudySubject(StudySubject deserialedStudySubject) throws C3PRCodedException { StudySubject studySubject = studySubjectFactory.buildStudySubject(deserialedStudySubject); if(studySubjectDao.getByIdentifiers(studySubject.getIdentifiers()).size()>0){ throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (studySubject.getParticipant().getId() != null) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(studySubject.getParticipant()); exampleSS.setStudySite(studySubject.getStudySite()); List<StudySubject> registrations = studySubjectDao.searchBySubjectAndStudySite(exampleSS); if (registrations.size() > 0) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE")); } } else { if (studySubject.getParticipant().validateParticipant()) participantDao.save(studySubject.getParticipant()); else { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE")); } } if (studySubject.getScheduledEpoch().getEpoch().getRequiresArm()) { ScheduledEpoch scheduledTreatmentEpoch = studySubject .getScheduledEpoch(); if (scheduledTreatmentEpoch.getScheduledArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm().getId() == null) throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.IMPORT.REQUIRED.ARM.NOTFOUND.CODE")); } studySubject.setRegDataEntryStatus(studySubject.evaluateRegistrationDataEntryStatus()); studySubject.getScheduledEpoch().setScEpochDataEntryStatus(studySubject.evaluateScheduledEpochDataEntryStatus((List)new ArrayList<Error>())); if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SCHEDULEDEPOCH.DATA_ENTRY_INCOMPLETE.CODE")); } boolean hasC3PRAssignedIdentifier=false; for(SystemAssignedIdentifier systemAssignedIdentifier: studySubject.getSystemAssignedIdentifiers()){ if(systemAssignedIdentifier.getSystemName().equals("C3PR")){ hasC3PRAssignedIdentifier=true; break; } } if(!hasC3PRAssignedIdentifier){ studySubject.addIdentifier(identifierGenerator.generateSystemAssignedIdentifier(studySubject)); } studySubject.getScheduledEpoch().setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.REGISTERED); if (studySubject.getScheduledEpoch().isReserving()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.RESERVED); } else if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.ENROLLED); studySubject.addIdentifier(identifierGenerator.generateOrganizationAssignedIdentifier(studySubject)); } else { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.REGISTERED_BUT_NOT_ENROLLED); } studySubjectDao.save(studySubject); log.debug("Registration saved with grid ID" + studySubject.getGridId()); return studySubject; } @Transient public Arm getNextArmForUnstratifiedStudy(StudySubject studySubject) throws C3PRBaseException { Arm arm = null; if ((studySubject.getScheduledEpoch()).getEpoch().hasBookRandomizationEntry()){ Iterator<BookRandomizationEntry> iter = ((BookRandomization)(studySubject.getScheduledEpoch()).getEpoch().getRandomization()).getBookRandomizationEntry().iterator(); BookRandomizationEntry breTemp; while (iter.hasNext()) { breTemp = iter.next(); if (breTemp.getPosition().equals((studySubject.getScheduledEpoch().getEpoch().getCurrentBookRandomizationEntryPosition()))) { synchronized (this) { (studySubject.getScheduledEpoch().getEpoch()).setCurrentBookRandomizationEntryPosition(breTemp.getPosition()+1); arm = breTemp.getArm(); break; } } } } if (arm == null) { throw this.exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.NO.ARM.AVAILABLE.BOOK.EXHAUSTED.CODE")); } return arm; } public void setStudySubjectDao(StudySubjectDao studySubjectDao) { this.studySubjectDao = studySubjectDao; } public void setEpochDao(EpochDao epochDao) { this.epochDao = epochDao; } public void setStratumGroupDao(StratumGroupDao stratumGroupDao) { this.stratumGroupDao = stratumGroupDao; } public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) { this.exceptionHelper = exceptionHelper; } public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } private int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null)); } public StudySubject save(StudySubject studySubject) { return studySubjectDao.merge(studySubject); } public void setStudySubjectFactory(StudySubjectFactory studySubjectFactory) { this.studySubjectFactory = studySubjectFactory; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public List<StudySubject> findRegistrations(StudySubject exampleStudySubject) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(exampleStudySubject.getParticipant()); exampleSS.setStudySite(exampleStudySubject.getStudySite()); return studySubjectDao.searchBySubjectAndStudySite(exampleSS); } public StudySubject enroll(List<Identifier> studySubjectIdentifiers) throws C3PRCodedException { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubjectDao.initialize(studySubject); this.continueEnrollment(studySubject); this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); studySubject = studySubjectDao.merge(studySubject); sendStudyAccrualNotification(studySubject); broadcastMessage(studySubject); return studySubject; } //Send out the CCTS broadcast Message private void broadcastMessage(StudySubject studySubjectAfterSave) { try { studySubjectService.broadcastMessage(studySubjectAfterSave); } catch (C3PRCodedException e) { log.error(e.getMessage()); studySubjectAfterSave.setCctsWorkflowStatus(WorkFlowStatusType.MESSAGE_SEND_FAILED); } catch (Exception e) { // TODO throw a C3PRCodedUncheckedException log.error(e.getMessage()); throw new RuntimeException(e); } } //Send out the study accrual notification. private void sendStudyAccrualNotification(StudySubject studySubjectAfterSave) { try { this.notificationEmailer.sendEmail(studySubjectAfterSave); } catch (Exception e) { // TODO throw a C3PRCodedUncheckedException log.error(e.getMessage()); throw new RuntimeException(e); } } public StudySubject enroll(StudySubject studySubject) throws C3PRCodedException { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); studySubjectDao.initialize(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } this.continueEnrollment(studySubject); this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); studySubject = studySubjectDao.merge(studySubject); sendStudyAccrualNotification(studySubject); broadcastMessage(studySubject); return studySubject; } public void continueEnrollment(StudySubject studySubject) throws C3PRCodedException { if(studySubject.getStudySite().getStudySiteStudyVersion(studySubject.getStartDate()) != studySubject.getStudySiteVersion()){ throw this.exceptionHelper.getException(getCode("C3PR.EXCEPTION.REGISTRATION.WRONG_STUDY_SITE_STUDY_VERSION_FOR_DATE.CODE"), new String[]{studySubject.getStudySiteVersion().getStudyVersion().getVersion().toString(),studySubject.getStartDateStr()}); } if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForEnrollment(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.ENROLL_SUBJECT, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteEnrollment(multisiteReturnedStudySubject.getScheduledEpoch(),multisiteReturnedStudySubject.getCoOrdinatingCenterIdentifier()); }else{ if (studySubject.getRegWorkflowStatus() != RegistrationWorkFlowStatus.ENROLLED) { studySubject.addIdentifier(identifierGenerator.generateOrganizationAssignedIdentifier(studySubject)); } studySubject.doLocalEnrollment(); } for (StudySubject childStudySubject : studySubject.getChildStudySubjects()) { if (childStudySubject.getRegWorkflowStatus() == RegistrationWorkFlowStatus.REGISTERED_BUT_NOT_ENROLLED && childStudySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.PENDING) { continueEnrollment(childStudySubject); } } } public StudySubject register(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } studySubject.register(); return save(studySubject); } public StudySubject register(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.register(); return save(studySubject); } public void takeSubjectOffStudy(List<Identifier> studySubjectIdentifiers, String offStudyReasonText, Date offStudyDate) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.takeSubjectOffStudy(offStudyReasonText,offStudyDate); save(studySubject); } public StudySubject transferSubject(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForTransfer(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.CHANGE_EPOCH, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteTransfer(multisiteReturnedStudySubject.getScheduledEpoch()); }else{ studySubject.doLocalTransfer(); } this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); return save(studySubject); } public StudySubject transferSubject(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForTransfer(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.CHANGE_EPOCH, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteTransfer(multisiteReturnedStudySubject.getScheduledEpoch()); }else{ studySubject.doLocalTransfer(); } this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); return save(studySubject); } public StudySubject create(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 0) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (!studySubject.hasC3PRSystemIdentifier()){ studySubject.addIdentifier(identifierGenerator.generateSystemAssignedIdentifier(studySubject)); } return save(studySubject); } public StudySubject reserve(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } studySubject.reserve(); return studySubject; } public StudySubject reserve(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.reserve(); return save(studySubject); } public StudySubject getUniqueStudySubjects(List<Identifier> studySubjectIdentifiers) { List<StudySubject> studySubjects = studySubjectDao.getByIdentifiers(studySubjectIdentifiers); if (studySubjects.size() == 0) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.NOT_FOUND_GIVEN_IDENTIFIERS.CODE")); } else if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } return studySubjects.get(0); } public EndPoint handleCoordinatingCenterBroadcast(Study study, APIName multisiteAPIName, List domainObjects) { for(EndPoint endPoint: study.getStudyCoordinatingCenters().get(0).getEndpoints()){ endPoint.getErrors().size(); studySubjectDao.evict(endPoint); } return studySubjectService.handleMultiSiteBroadcast(study.getStudyCoordinatingCenters() .get(0), ServiceName.REGISTRATION, multisiteAPIName, domainObjects); } public void setStudySubjectService(StudySubjectService studySubjectService) { this.studySubjectService = studySubjectService; } public StudyTargetAccrualNotificationEmail getNotificationEmailer() { return notificationEmailer; } public void setNotificationEmailer( StudyTargetAccrualNotificationEmail notificationEmailer) { this.notificationEmailer = notificationEmailer; } public void saveStratumGroup(StudySubject studySubject){ if(studySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && studySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && studySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ try { stratumGroupDao.merge(studySubject.getScheduledEpoch().getStratumGroup()); } catch (C3PRBaseException e) { e.printStackTrace(); throw new C3PRBaseRuntimeException(e.getMessage()); } } for(StudySubject childStudySubject: studySubject.getChildStudySubjects()){ if(childStudySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && childStudySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && childStudySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ try { stratumGroupDao.merge(childStudySubject.getScheduledEpoch().getStratumGroup()); } catch (C3PRBaseException e) { e.printStackTrace(); throw new C3PRBaseRuntimeException(e.getMessage()); } } } } public void updateEpoch(StudySubject studySubject){ if(studySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && !studySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && studySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ this.epochDao.merge(studySubject.getScheduledEpoch().getEpoch()); } } public void setIdentifierGenerator(IdentifierGenerator identifierGenerator) { this.identifierGenerator = identifierGenerator; } public IdentifierGenerator getIdentifierGenerator() { return identifierGenerator; } }
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/repository/impl/StudySubjectRepositoryImpl.java
package edu.duke.cabig.c3pr.domain.repository.impl; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.persistence.Transient; import org.apache.log4j.Logger; import org.springframework.context.MessageSource; import org.springframework.transaction.annotation.Transactional; import edu.duke.cabig.c3pr.constants.APIName; import edu.duke.cabig.c3pr.constants.RandomizationType; import edu.duke.cabig.c3pr.constants.RegistrationDataEntryStatus; import edu.duke.cabig.c3pr.constants.RegistrationWorkFlowStatus; import edu.duke.cabig.c3pr.constants.ScheduledEpochDataEntryStatus; import edu.duke.cabig.c3pr.constants.ScheduledEpochWorkFlowStatus; import edu.duke.cabig.c3pr.constants.ServiceName; import edu.duke.cabig.c3pr.constants.WorkFlowStatusType; import edu.duke.cabig.c3pr.dao.EpochDao; import edu.duke.cabig.c3pr.dao.ParticipantDao; import edu.duke.cabig.c3pr.dao.StratumGroupDao; import edu.duke.cabig.c3pr.dao.StudySubjectDao; import edu.duke.cabig.c3pr.domain.Arm; import edu.duke.cabig.c3pr.domain.BookRandomization; import edu.duke.cabig.c3pr.domain.BookRandomizationEntry; import edu.duke.cabig.c3pr.domain.EndPoint; import edu.duke.cabig.c3pr.domain.Epoch; import edu.duke.cabig.c3pr.domain.Identifier; import edu.duke.cabig.c3pr.domain.ScheduledEpoch; import edu.duke.cabig.c3pr.domain.Study; import edu.duke.cabig.c3pr.domain.StudySubject; import edu.duke.cabig.c3pr.domain.SystemAssignedIdentifier; import edu.duke.cabig.c3pr.domain.factory.StudySubjectFactory; import edu.duke.cabig.c3pr.domain.repository.StudySubjectRepository; import edu.duke.cabig.c3pr.exception.C3PRBaseException; import edu.duke.cabig.c3pr.exception.C3PRBaseRuntimeException; import edu.duke.cabig.c3pr.exception.C3PRCodedException; import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper; import edu.duke.cabig.c3pr.service.StudySubjectService; import edu.duke.cabig.c3pr.utils.IdentifierGenerator; import edu.duke.cabig.c3pr.utils.StudyTargetAccrualNotificationEmail; import gov.nih.nci.cabig.ctms.domain.AbstractMutableDomainObject; @Transactional public class StudySubjectRepositoryImpl implements StudySubjectRepository { private StudySubjectDao studySubjectDao; private ParticipantDao participantDao; private EpochDao epochDao; private StratumGroupDao stratumGroupDao; private C3PRExceptionHelper exceptionHelper; private MessageSource c3prErrorMessages; private StudySubjectFactory studySubjectFactory; private StudySubjectService studySubjectService; private StudyTargetAccrualNotificationEmail notificationEmailer; private IdentifierGenerator identifierGenerator ; //private StudyService studyService; private Logger log = Logger.getLogger(StudySubjectRepositoryImpl.class.getName()); public void assignC3DIdentifier(StudySubject studySubject, String c3dIdentifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setC3DIdentifier(c3dIdentifierValue); studySubjectDao.save(loadedSubject); } public void assignCoOrdinatingCenterIdentifier(StudySubject studySubject, String identifierValue) { StudySubject loadedSubject = studySubjectDao.getByGridId(studySubject.getGridId()); loadedSubject.setCoOrdinatingCenterIdentifier(identifierValue); studySubjectDao.save(loadedSubject); } public boolean isEpochAccrualCeilingReached(int epochId) { Epoch epoch = epochDao.getById(epochId); if (epoch.isReserving()) { ScheduledEpoch scheduledEpoch = new ScheduledEpoch(true); scheduledEpoch.setEpoch(epoch); List<StudySubject> list = studySubjectDao.searchByScheduledEpoch(scheduledEpoch); Epoch nEpoch = epoch; if (nEpoch.getAccrualCeiling() != null && list.size() >= nEpoch.getAccrualCeiling().intValue()) { return true; } } return false; } public StudySubject doLocalRegistration(StudySubject studySubject) throws C3PRCodedException { continueEnrollment(studySubject); return studySubject; } /** * Saves the Imported StudySubject to the database. Moved it from the service as a part of the * refactoring effort. * * @param deserialedStudySubject * @return * @throws C3PRCodedException */ @Transactional(readOnly = false) public StudySubject importStudySubject(StudySubject deserialedStudySubject) throws C3PRCodedException { StudySubject studySubject = studySubjectFactory.buildStudySubject(deserialedStudySubject); if(studySubjectDao.getByIdentifiers(studySubject.getIdentifiers()).size()>0){ throw exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (studySubject.getParticipant().getId() != null) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(studySubject.getParticipant()); exampleSS.setStudySite(studySubject.getStudySite()); List<StudySubject> registrations = studySubjectDao.searchBySubjectAndStudySite(exampleSS); if (registrations.size() > 0) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.STUDYSUBJECTS_ALREADY_EXISTS.CODE")); } } else { if (studySubject.getParticipant().validateParticipant()) participantDao.save(studySubject.getParticipant()); else { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SUBJECTS_INVALID_DETAILS.CODE")); } } if (studySubject.getScheduledEpoch().getEpoch().getRequiresArm()) { ScheduledEpoch scheduledTreatmentEpoch = studySubject .getScheduledEpoch(); if (scheduledTreatmentEpoch.getScheduledArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm() == null || scheduledTreatmentEpoch.getScheduledArm().getArm().getId() == null) throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.IMPORT.REQUIRED.ARM.NOTFOUND.CODE")); } studySubject.setRegDataEntryStatus(studySubject.evaluateRegistrationDataEntryStatus()); studySubject.getScheduledEpoch().setScEpochDataEntryStatus(studySubject.evaluateScheduledEpochDataEntryStatus((List)new ArrayList<Error>())); if (studySubject.getRegDataEntryStatus() == RegistrationDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.DATA_ENTRY_INCOMPLETE.CODE")); } if (studySubject.getScheduledEpoch().getScEpochDataEntryStatus() == ScheduledEpochDataEntryStatus.INCOMPLETE) { throw this.exceptionHelper .getException(getCode("C3PR.EXCEPTION.REGISTRATION.SCHEDULEDEPOCH.DATA_ENTRY_INCOMPLETE.CODE")); } boolean hasC3PRAssignedIdentifier=false; for(SystemAssignedIdentifier systemAssignedIdentifier: studySubject.getSystemAssignedIdentifiers()){ if(systemAssignedIdentifier.getSystemName().equals("C3PR")){ hasC3PRAssignedIdentifier=true; break; } } if(!hasC3PRAssignedIdentifier){ studySubject.addIdentifier(identifierGenerator.generateSystemAssignedIdentifier(studySubject)); } studySubject.getScheduledEpoch().setScEpochWorkflowStatus(ScheduledEpochWorkFlowStatus.REGISTERED); if (studySubject.getScheduledEpoch().isReserving()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.RESERVED); } else if (studySubject.getScheduledEpoch().getEpoch().isEnrolling()) { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.ENROLLED); studySubject.addIdentifier(identifierGenerator.generateOrganizationAssignedIdentifier(studySubject)); } else { studySubject.setRegWorkflowStatus(RegistrationWorkFlowStatus.REGISTERED_BUT_NOT_ENROLLED); } studySubjectDao.save(studySubject); log.debug("Registration saved with grid ID" + studySubject.getGridId()); return studySubject; } @Transient public Arm getNextArmForUnstratifiedStudy(StudySubject studySubject) throws C3PRBaseException { Arm arm = null; if ((studySubject.getScheduledEpoch()).getEpoch().hasBookRandomizationEntry()){ Iterator<BookRandomizationEntry> iter = ((BookRandomization)(studySubject.getScheduledEpoch()).getEpoch().getRandomization()).getBookRandomizationEntry().iterator(); BookRandomizationEntry breTemp; while (iter.hasNext()) { breTemp = iter.next(); if (breTemp.getPosition().equals((studySubject.getScheduledEpoch().getEpoch().getCurrentBookRandomizationEntryPosition()))) { synchronized (this) { (studySubject.getScheduledEpoch().getEpoch()).setCurrentBookRandomizationEntryPosition(breTemp.getPosition()+1); arm = breTemp.getArm(); break; } } } } if (arm == null) { throw this.exceptionHelper.getException( getCode("C3PR.EXCEPTION.REGISTRATION.NO.ARM.AVAILABLE.BOOK.EXHAUSTED.CODE")); } return arm; } public void setStudySubjectDao(StudySubjectDao studySubjectDao) { this.studySubjectDao = studySubjectDao; } public void setEpochDao(EpochDao epochDao) { this.epochDao = epochDao; } public void setStratumGroupDao(StratumGroupDao stratumGroupDao) { this.stratumGroupDao = stratumGroupDao; } public void setExceptionHelper(C3PRExceptionHelper exceptionHelper) { this.exceptionHelper = exceptionHelper; } public void setC3prErrorMessages(MessageSource errorMessages) { c3prErrorMessages = errorMessages; } private int getCode(String errortypeString) { return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null)); } public StudySubject save(StudySubject studySubject) { return studySubjectDao.merge(studySubject); } public void setStudySubjectFactory(StudySubjectFactory studySubjectFactory) { this.studySubjectFactory = studySubjectFactory; } public void setParticipantDao(ParticipantDao participantDao) { this.participantDao = participantDao; } public List<StudySubject> findRegistrations(StudySubject exampleStudySubject) { StudySubject exampleSS = new StudySubject(true); exampleSS.setParticipant(exampleStudySubject.getParticipant()); exampleSS.setStudySite(exampleStudySubject.getStudySite()); return studySubjectDao.searchBySubjectAndStudySite(exampleSS); } public StudySubject enroll(List<Identifier> studySubjectIdentifiers) throws C3PRCodedException { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubjectDao.initialize(studySubject); this.continueEnrollment(studySubject); this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); studySubject = studySubjectDao.merge(studySubject); sendStudyAccrualNotification(studySubject); broadcastMessage(studySubject); return studySubject; } //Send out the CCTS broadcast Message private void broadcastMessage(StudySubject studySubjectAfterSave) { try { studySubjectService.broadcastMessage(studySubjectAfterSave); } catch (C3PRCodedException e) { log.error(e.getMessage()); studySubjectAfterSave.setCctsWorkflowStatus(WorkFlowStatusType.MESSAGE_SEND_FAILED); } catch (Exception e) { // TODO throw a C3PRCodedUncheckedException log.error(e.getMessage()); throw new RuntimeException(e); } } //Send out the study accrual notification. private void sendStudyAccrualNotification(StudySubject studySubjectAfterSave) { try { this.notificationEmailer.sendEmail(studySubjectAfterSave); } catch (Exception e) { // TODO throw a C3PRCodedUncheckedException log.error(e.getMessage()); throw new RuntimeException(e); } } public StudySubject enroll(StudySubject studySubject) throws C3PRCodedException { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); studySubjectDao.initialize(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } this.continueEnrollment(studySubject); this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); studySubjectDao.save(studySubject); studySubject = studySubjectDao.getById(studySubject.getId()); studySubjectDao.initialize(studySubject); sendStudyAccrualNotification(studySubject); broadcastMessage(studySubject); return studySubject; } public void continueEnrollment(StudySubject studySubject) throws C3PRCodedException { if(studySubject.getStudySite().getStudySiteStudyVersion(studySubject.getStartDate()) != studySubject.getStudySiteVersion()){ throw this.exceptionHelper.getException(getCode("C3PR.EXCEPTION.REGISTRATION.WRONG_STUDY_SITE_STUDY_VERSION_FOR_DATE.CODE"), new String[]{studySubject.getStudySiteVersion().getStudyVersion().getVersion().toString(),studySubject.getStartDateStr()}); } if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForEnrollment(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.ENROLL_SUBJECT, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteEnrollment(multisiteReturnedStudySubject.getScheduledEpoch(),multisiteReturnedStudySubject.getCoOrdinatingCenterIdentifier()); }else{ if (studySubject.getRegWorkflowStatus() != RegistrationWorkFlowStatus.ENROLLED) { studySubject.addIdentifier(identifierGenerator.generateOrganizationAssignedIdentifier(studySubject)); } studySubject.doLocalEnrollment(); } for (StudySubject childStudySubject : studySubject.getChildStudySubjects()) { if (childStudySubject.getRegWorkflowStatus() == RegistrationWorkFlowStatus.REGISTERED_BUT_NOT_ENROLLED && childStudySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.PENDING) { continueEnrollment(childStudySubject); } } } public StudySubject register(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } studySubject.register(); return save(studySubject); } public StudySubject register(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.register(); return save(studySubject); } public void takeSubjectOffStudy(List<Identifier> studySubjectIdentifiers, String offStudyReasonText, Date offStudyDate) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.takeSubjectOffStudy(offStudyReasonText,offStudyDate); save(studySubject); } public StudySubject transferSubject(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForTransfer(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.CHANGE_EPOCH, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteTransfer(multisiteReturnedStudySubject.getScheduledEpoch()); }else{ studySubject.doLocalTransfer(); } this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); return save(studySubject); } public StudySubject transferSubject(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (studySubject.getScheduledEpoch().getScEpochWorkflowStatus() != ScheduledEpochWorkFlowStatus.REGISTERED) { studySubject.prepareForTransfer(); } if (!studySubject.getStudySite().getHostedMode() && !studySubject.getStudySite().getIsCoordinatingCenter() && !studySubject.getStudySite().getStudy().isCoOrdinatingCenter(studySubjectService.getLocalNCIInstituteCode())){ List<AbstractMutableDomainObject> domainObjects = new ArrayList<AbstractMutableDomainObject>(); domainObjects.add(studySubject); EndPoint endPoint=handleCoordinatingCenterBroadcast(studySubject.getStudySite().getStudy(), APIName.CHANGE_EPOCH, domainObjects); if(endPoint.getStatus()!=WorkFlowStatusType.MESSAGE_SEND_CONFIRMED){ throw this.exceptionHelper.getMultisiteException(endPoint.getLastAttemptError()); } StudySubject multisiteReturnedStudySubject=(StudySubject)((List) endPoint.getReturnValue()).get(0); studySubjectDao.initialize(multisiteReturnedStudySubject); //StudySubject multisiteReturnedStudySubject = studySubjectServiceImpl.getArmAndCoordinatingAssignedIdentifier(studySubject); studySubject.doMutiSiteTransfer(multisiteReturnedStudySubject.getScheduledEpoch()); }else{ studySubject.doLocalTransfer(); } this.saveStratumGroup(studySubject); this.updateEpoch(studySubject); return save(studySubject); } public StudySubject create(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 0) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } if (!studySubject.hasC3PRSystemIdentifier()){ studySubject.addIdentifier(identifierGenerator.generateSystemAssignedIdentifier(studySubject)); } return save(studySubject); } public StudySubject reserve(StudySubject studySubject) { List<StudySubject> studySubjects = new ArrayList<StudySubject>(); studySubjects=findRegistrations(studySubject); if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } studySubject.reserve(); return studySubject; } public StudySubject reserve(List<Identifier> studySubjectIdentifiers) { StudySubject studySubject = getUniqueStudySubjects(studySubjectIdentifiers); studySubject.reserve(); return save(studySubject); } public StudySubject getUniqueStudySubjects(List<Identifier> studySubjectIdentifiers) { List<StudySubject> studySubjects = studySubjectDao.getByIdentifiers(studySubjectIdentifiers); if (studySubjects.size() == 0) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.NOT_FOUND_GIVEN_IDENTIFIERS.CODE")); } else if (studySubjects.size() > 1) { throw this.exceptionHelper.getRuntimeException(getCode("C3PR.EXCEPTION.REGISTRATION.MULTIPLE_STUDYSUBJECTS_FOUND.CODE")); } return studySubjects.get(0); } public EndPoint handleCoordinatingCenterBroadcast(Study study, APIName multisiteAPIName, List domainObjects) { for(EndPoint endPoint: study.getStudyCoordinatingCenters().get(0).getEndpoints()){ endPoint.getErrors().size(); studySubjectDao.evict(endPoint); } return studySubjectService.handleMultiSiteBroadcast(study.getStudyCoordinatingCenters() .get(0), ServiceName.REGISTRATION, multisiteAPIName, domainObjects); } public void setStudySubjectService(StudySubjectService studySubjectService) { this.studySubjectService = studySubjectService; } public StudyTargetAccrualNotificationEmail getNotificationEmailer() { return notificationEmailer; } public void setNotificationEmailer( StudyTargetAccrualNotificationEmail notificationEmailer) { this.notificationEmailer = notificationEmailer; } public void saveStratumGroup(StudySubject studySubject){ if(studySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && studySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && studySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ try { stratumGroupDao.merge(studySubject.getScheduledEpoch().getStratumGroup()); } catch (C3PRBaseException e) { e.printStackTrace(); throw new C3PRBaseRuntimeException(e.getMessage()); } } for(StudySubject childStudySubject: studySubject.getChildStudySubjects()){ if(childStudySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && childStudySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && childStudySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ try { stratumGroupDao.merge(childStudySubject.getScheduledEpoch().getStratumGroup()); } catch (C3PRBaseException e) { e.printStackTrace(); throw new C3PRBaseRuntimeException(e.getMessage()); } } } } public void updateEpoch(StudySubject studySubject){ if(studySubject.getScheduledEpoch().getEpoch().getRandomizedIndicator() && !studySubject.getScheduledEpoch().getEpoch().getStratificationIndicator() && studySubject.getStudySite().getStudy().getRandomizationType()==RandomizationType.BOOK){ this.epochDao.merge(studySubject.getScheduledEpoch().getEpoch()); } } public void setIdentifierGenerator(IdentifierGenerator identifierGenerator) { this.identifierGenerator = identifierGenerator; } public IdentifierGenerator getIdentifierGenerator() { return identifierGenerator; } }
CPR-866: changed save to merge in enroll. might have to be done in other APIs too
codebase/projects/core/src/java/edu/duke/cabig/c3pr/domain/repository/impl/StudySubjectRepositoryImpl.java
CPR-866: changed save to merge in enroll. might have to be done in other APIs too
Java
bsd-3-clause
7ceaad0428a8af2d9ad641b13d58e40dd0a4091b
0
NCIP/cagrid-portal,NCIP/cagrid-portal,NCIP/cagrid-portal
/** * */ package gov.nih.nci.cagrid.portal.portlet.query; import gov.nih.nci.cagrid.portal.dao.QueryResultTableDao; import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQuery; import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQueryInstance; import gov.nih.nci.cagrid.portal.domain.table.QueryResultTable; import gov.nih.nci.cagrid.portal.portlet.query.results.QueryResultTableToDataTableMetadataBuilder; import gov.nih.nci.cagrid.portal.portlet.query.results.QueryResultTableToJSONObjectBuilder; import gov.nih.nci.cagrid.portal.portlet.query.results.XMLQueryResultToQueryResultTableHandler; import gov.nih.nci.cagrid.portal.portlet.util.PortletUtils; import gov.nih.nci.cagrid.portal.service.PortalFileService; import org.json.JSONObject; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; /** * @author <a href="mailto:[email protected]">Joshua Phillips</a> * @author <a href="mailto:[email protected]">Manav Kher</a> */ public class QueryResultTableToJSONTest { /** * */ QueryResultTableToDataTableMetadataBuilder builder; public QueryResultTableToJSONTest() { } @Before public void setup() { builder = new QueryResultTableToDataTableMetadataBuilder(); QueryResultTableDao mockResultTableDao = mock(QueryResultTableDao.class); when(mockResultTableDao.getRowCountForColumn(anyInt(), anyString())).thenReturn(2); builder.setQueryResultTableDao(mockResultTableDao); } @Test public void testCountQueryJSONMeta() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/count_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); PortalFileService mockFileService = mock(PortalFileService.class); File mockFile = mock(File.class); when(mockFile.getName()).thenReturn(anyString()); when(mockFileService.write(new byte[]{})).thenReturn(mockFile); when(mockFileService.read(anyString())).thenReturn(sb.toString().getBytes()); handler.setPortalFileService(mockFileService); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream("test/data/count_results.xml"), handler); QueryResultTable table = handler.getTable(); String expected = "{\"responseSchema\":{\"resultsList\":\"rows\",\"fields\":[\"count\",\"dataServiceUrl\"],\"metaFields\":{\"totalRecords\":\"numRows\"}},\"columnDefs\":[{\"key\":\"count\",\"resizeable\":true,\"sortable\":true},{\"key\":\"dataServiceUrl\",\"resizeable\":true,\"sortable\":true}]}"; assertEquals(expected, builder.build(table).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testCountQueryJSON() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/count_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setDataServiceUrl("http://service"); handler.setPersist(false); handler.getTable().setQueryInstance(queryInstance); PortalFileService mockFileService = mock(PortalFileService.class); File mockFile = mock(File.class); when(mockFile.getName()).thenReturn(anyString()); when(mockFileService.write(new byte[]{})).thenReturn(mockFile); when(mockFileService.read(anyString())).thenReturn(sb.toString().getBytes()); handler.setPortalFileService(mockFileService); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream("test/data/count_results.xml"), handler); QueryResultTable table = handler.getTable(); QueryResultTableToJSONObjectBuilder builder = new QueryResultTableToJSONObjectBuilder(); String expected = "{\"numRows\":1,\"rows\":[{\"dataServiceUrl\":\"http://service\",\"count\":\"1208\"}]}"; assertEquals(expected, builder.build(table.getRows()).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testSelectedAttributesQueryJSONMeta() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/selected_attribute_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(!PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); PortalFileService mockFileService = mock(PortalFileService.class); File mockFile = mock(File.class); when(mockFile.getName()).thenReturn(anyString()); when(mockFileService.write(new byte[]{})).thenReturn(mockFile); when(mockFileService.read(anyString())).thenReturn(sb.toString().getBytes()); handler.setPortalFileService(mockFileService); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream( "test/data/selected_attribute_results.xml"), handler); QueryResultTable table = handler.getTable(); String expected = "{\"responseSchema\":{\"resultsList\":\"rows\",\"fields\":[\"id\",\"ageOfOnset\",\"dataServiceUrl\"],\"metaFields\":{\"totalRecords\":\"numRows\"}},\"columnDefs\":[{\"key\":\"id\",\"resizeable\":true,\"sortable\":true},{\"key\":\"ageOfOnset\",\"resizeable\":true,\"sortable\":true},{\"key\":\"dataServiceUrl\",\"resizeable\":true,\"sortable\":true}]}"; assertEquals(expected, builder.build(table).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testSelectedAttributesQueryJSON() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/selected_attribute_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(!PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); PortalFileService mockFileService = mock(PortalFileService.class); File mockFile = mock(File.class); when(mockFile.getName()).thenReturn(anyString()); when(mockFileService.write(new byte[]{})).thenReturn(mockFile); when(mockFileService.read(anyString())).thenReturn(sb.toString().getBytes()); handler.setPortalFileService(mockFileService); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream( "test/data/selected_attribute_results.xml"), handler); QueryResultTable table = handler.getTable(); QueryResultTableToJSONObjectBuilder builder = new QueryResultTableToJSONObjectBuilder(); JSONObject out = builder.build(table.getRows()); assertEquals(1000, out.get("numRows")); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } }
cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/query/QueryResultTableToJSONTest.java
/** * */ package gov.nih.nci.cagrid.portal.portlet.query; import gov.nih.nci.cagrid.portal.dao.QueryResultTableDao; import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQuery; import gov.nih.nci.cagrid.portal.domain.dataservice.CQLQueryInstance; import gov.nih.nci.cagrid.portal.domain.table.QueryResultTable; import gov.nih.nci.cagrid.portal.portlet.query.results.QueryResultTableToDataTableMetadataBuilder; import gov.nih.nci.cagrid.portal.portlet.query.results.QueryResultTableToJSONObjectBuilder; import gov.nih.nci.cagrid.portal.portlet.query.results.XMLQueryResultToQueryResultTableHandler; import gov.nih.nci.cagrid.portal.portlet.util.PortletUtils; import org.json.JSONObject; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.*; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; /** * @author <a href="mailto:[email protected]">Joshua Phillips</a> * @author <a href="mailto:[email protected]">Manav Kher</a> */ public class QueryResultTableToJSONTest { /** * */ QueryResultTableToDataTableMetadataBuilder builder; public QueryResultTableToJSONTest() { } @Before public void setup() { builder = new QueryResultTableToDataTableMetadataBuilder(); QueryResultTableDao mockResultTableDao = mock(QueryResultTableDao.class); when(mockResultTableDao.getRowCountForColumn(anyInt(), anyString())).thenReturn(2); builder.setQueryResultTableDao(mockResultTableDao); } @Test public void testCountQueryJSONMeta() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/count_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream("test/data/count_results.xml"), handler); QueryResultTable table = handler.getTable(); String expected = "{\"responseSchema\":{\"resultsList\":\"rows\",\"fields\":[\"count\",\"dataServiceUrl\"],\"metaFields\":{\"totalRecords\":\"numRows\"}},\"columnDefs\":[{\"key\":\"count\",\"resizeable\":true,\"sortable\":true},{\"key\":\"dataServiceUrl\",\"resizeable\":true,\"sortable\":true}]}"; assertEquals(expected, builder.build(table).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testCountQueryJSON() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/count_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setDataServiceUrl("http://service"); handler.setPersist(false); handler.getTable().setQueryInstance(queryInstance); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream("test/data/count_results.xml"), handler); QueryResultTable table = handler.getTable(); QueryResultTableToJSONObjectBuilder builder = new QueryResultTableToJSONObjectBuilder(); String expected = "{\"numRows\":1,\"rows\":[{\"dataServiceUrl\":\"http://service\",\"count\":\"1208\"}]}"; assertEquals(expected, builder.build(table.getRows()).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testSelectedAttributesQueryJSONMeta() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/selected_attribute_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(!PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream( "test/data/selected_attribute_results.xml"), handler); QueryResultTable table = handler.getTable(); String expected = "{\"responseSchema\":{\"resultsList\":\"rows\",\"fields\":[\"id\",\"ageOfOnset\",\"dataServiceUrl\"],\"metaFields\":{\"totalRecords\":\"numRows\"}},\"columnDefs\":[{\"key\":\"id\",\"resizeable\":true,\"sortable\":true},{\"key\":\"ageOfOnset\",\"resizeable\":true,\"sortable\":true},{\"key\":\"dataServiceUrl\",\"resizeable\":true,\"sortable\":true}]}"; assertEquals(expected, builder.build(table).toString()); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } @Test public void testSelectedAttributesQueryJSON() { try { StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new FileReader( "test/data/selected_attribute_query.xml")); String line = null; while ((line = r.readLine()) != null) { sb.append(line); } String cql = sb.toString(); assertTrue(!PortletUtils.isCountQuery(cql)); CQLQuery query = new CQLQuery(); query.setXml(cql); CQLQueryInstance queryInstance = new CQLQueryInstance(); queryInstance.setResult("some data"); queryInstance.setQuery(query); XMLQueryResultToQueryResultTableHandler handler = new XMLQueryResultToQueryResultTableHandler(); handler.setPersist(false); handler.setDataServiceUrl("http://service"); handler.getTable().setQueryInstance(queryInstance); SAXParserFactory fact = SAXParserFactory.newInstance(); fact.setNamespaceAware(true); SAXParser parser = fact.newSAXParser(); parser.parse(new FileInputStream( "test/data/selected_attribute_results.xml"), handler); QueryResultTable table = handler.getTable(); QueryResultTableToJSONObjectBuilder builder = new QueryResultTableToJSONObjectBuilder(); JSONObject out = builder.build(table.getRows()); assertEquals(1000, out.get("numRows")); } catch (Exception ex) { ex.printStackTrace(); String msg = "Error encountered: " + ex.getMessage(); fail(msg); } } }
use mock file writer git-svn-id: 4ac7add7d81ed2bd05f1cd887829f573a8d7df68@14727 dd7b0c16-3c94-4492-92de-414b6a06f0b1
cagrid-portal/portlets/test/src/java/gov/nih/nci/cagrid/portal/portlet/query/QueryResultTableToJSONTest.java
use mock file writer
Java
mit
4df68bf33b42968692322af04ffad1cfcaf45cc0
0
InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service
package org.innovateuk.ifs.application.transactional; import org.innovateuk.ifs.applicant.resource.dashboard.ApplicantDashboardResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardInProgressRowResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardInSetupRowResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardRowResource; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.domain.ApplicationEoiEvidenceResponse; import org.innovateuk.ifs.application.domain.ApplicationExpressionOfInterestConfig; import org.innovateuk.ifs.application.repository.ApplicationEoiEvidenceResponseRepository; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.assessment.transactional.AssessmentService; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.domain.CompetitionEoiEvidenceConfig; import org.innovateuk.ifs.fundingdecision.domain.DecisionStatus; import org.innovateuk.ifs.interview.transactional.InterviewAssignmentService; import org.innovateuk.ifs.project.projectteam.domain.PendingPartnerProgress; import org.innovateuk.ifs.project.resource.ProjectState; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.competition.builder.CompetitionTypeBuilder.newCompetitionType; import static org.innovateuk.ifs.competition.resource.CompetitionResource.H2020_TYPE_NAME; import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry; import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation; import static org.innovateuk.ifs.project.core.builder.PartnerOrganisationBuilder.newPartnerOrganisation; import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.core.builder.ProjectProcessBuilder.newProjectProcess; import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser; import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ApplicationDashboardServiceImplTest { @InjectMocks private ApplicationDashboardServiceImpl applicationDashboardService; @Mock private ApplicationEoiEvidenceResponseRepository applicationEoiEvidenceResponseRepository; @Mock private InterviewAssignmentService interviewAssignmentService; @Mock private ApplicationRepository applicationRepository; @Mock private AssessmentService assessmentService; private final Competition closedCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().minusDays(1)) .withAlwaysOpen(false) .build(); private final Competition openCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withAlwaysOpen(false) .build(); private final Competition eoiCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withEnabledForExpressionOfInterest(true) .withCompetitionEoiEvidenceConfig((CompetitionEoiEvidenceConfig.builder() .evidenceRequired(true) .build())) .withAlwaysOpen(false) .build(); private final Competition alwaysOpenCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withAlwaysOpen(true) .withEnabledForExpressionOfInterest(true) .build(); private static final long USER_ID = 1L; private final User user = newUser().withId(USER_ID).build(); private final ProcessRole processRole = newProcessRole().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).withOrganisationId(1234L).build(); @Test public void getApplicantDashboard() { Application h2020Application = h2020Application(); Application projectInSetupApplication = projectInSetupApplication(); Application pendingPartnerInSetupApplication = pendingPartnerInSetupApplication(); Application completedProjectApplication = completedProjectApplication(); Application inProgressOpenCompApplication = inProgressOpenCompApplication(); Application inProgressAlwaysOpenCompApplicationInAssessment = inProgressAlwaysOpenCompApplication(); Application inProgressClosedCompApplication = inProgressClosedCompApplication(); Application onHoldNotifiedApplication = onHoldNotifiedApplication(); Application unsuccessfulNotifiedApplication = unsuccessfulNotifiedApplication(); Application ineligibleApplication = ineligibleApplication(); Application submittedAwaitingDecisionApplication = submittedAwaitingDecisionApplication(); Application eoiApplicationWithoutEvidence = eoiApplication(); Application eoiApplicationWithEvidence = eoiApplication(); when(interviewAssignmentService.isApplicationAssigned(anyLong())).thenReturn(serviceSuccess(true)); List<Application> applications = asList(h2020Application, projectInSetupApplication, pendingPartnerInSetupApplication, completedProjectApplication, inProgressOpenCompApplication, inProgressClosedCompApplication, inProgressAlwaysOpenCompApplicationInAssessment, onHoldNotifiedApplication, unsuccessfulNotifiedApplication, ineligibleApplication, submittedAwaitingDecisionApplication, eoiApplicationWithoutEvidence, eoiApplicationWithEvidence); when(applicationRepository.findApplicationsForDashboard(USER_ID)) .thenReturn(applications); when(applicationEoiEvidenceResponseRepository.findOneByApplicationId(eoiApplicationWithoutEvidence.getId())).thenReturn(Optional.empty()); ApplicationEoiEvidenceResponse applicationEoiEvidenceResponse = ApplicationEoiEvidenceResponse.builder() .application(newApplication().build()) .organisation(newOrganisation().build()) .fileEntry(newFileEntry().build()) .build(); when(applicationEoiEvidenceResponseRepository.findOneByApplicationId(eoiApplicationWithEvidence.getId())).thenReturn(Optional.of(applicationEoiEvidenceResponse)); ApplicantDashboardResource dashboardResource = applicationDashboardService.getApplicantDashboard(USER_ID).getSuccess(); assertEquals(1, dashboardResource.getEuGrantTransfer().size()); assertEquals(6, dashboardResource.getInProgress().size()); assertEquals(2, dashboardResource.getInSetup().size()); assertEquals(4, dashboardResource.getPrevious().size()); assertListContainsApplication(h2020Application, dashboardResource.getEuGrantTransfer()); DashboardInSetupRowResource notPendingResource = assertListContainsApplication(projectInSetupApplication, dashboardResource.getInSetup()); DashboardInSetupRowResource pendingResource = assertListContainsApplication(pendingPartnerInSetupApplication, dashboardResource.getInSetup()); assertListContainsApplication(completedProjectApplication, dashboardResource.getPrevious()); assertListContainsApplication(inProgressOpenCompApplication, dashboardResource.getInProgress()); assertListContainsApplication(inProgressClosedCompApplication, dashboardResource.getPrevious()); assertListContainsApplication(onHoldNotifiedApplication, dashboardResource.getInProgress()); assertListContainsApplication(inProgressAlwaysOpenCompApplicationInAssessment, dashboardResource.getInProgress()); assertListContainsApplication(unsuccessfulNotifiedApplication, dashboardResource.getPrevious()); assertListContainsApplication(ineligibleApplication, dashboardResource.getPrevious()); assertListContainsApplication(submittedAwaitingDecisionApplication, dashboardResource.getInProgress()); assertFalse(dashboardResource.getInProgress().stream() .filter(DashboardInProgressRowResource::isAlwaysOpen) .findFirst().get() .isShowReopenLink()); assertTrue(pendingResource.isPendingPartner()); assertFalse(notPendingResource.isPendingPartner()); assertTrue(dashboardResource.getInProgress().stream() .filter(DashboardInProgressRowResource::isAlwaysOpen) .findFirst().get() .isExpressionOfInterest()); List<DashboardInProgressRowResource> inProgressRowResourceList = dashboardResource.getInProgress(); assertNull(inProgressRowResourceList.get(0).getEvidenceUploaded()); assertNull(inProgressRowResourceList.get(1).getEvidenceUploaded()); assertNull(inProgressRowResourceList.get(2).getEvidenceUploaded()); assertNull(inProgressRowResourceList.get(3).getEvidenceUploaded()); assertFalse(inProgressRowResourceList.get(4).getEvidenceUploaded()); assertTrue(inProgressRowResourceList.get(5).getEvidenceUploaded()); } private Application inProgressAlwaysOpenCompApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(alwaysOpenCompetition) .withApplicationState(ApplicationState.SUBMITTED) .withDecision((DecisionStatus) null) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig .builder().enabledForExpressionOfInterest(true).build()) .build(); } private <R extends DashboardRowResource> R assertListContainsApplication(Application application, List<R> applications) { Optional<R> resource = applications.stream().filter(row -> application.getId().equals(row.getApplicationId())).findFirst(); assertTrue(resource.isPresent()); return resource.get(); } private Application submittedAwaitingDecisionApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.SUBMITTED) .build(); } private Application ineligibleApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.INELIGIBLE_INFORMED) .build(); } private Application unsuccessfulNotifiedApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.REJECTED) .withDecision(DecisionStatus.UNFUNDED) .withManageDecisionEmailDate(ZonedDateTime.now()) .build(); } private Application onHoldNotifiedApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.SUBMITTED) .withDecision(DecisionStatus.ON_HOLD) .withManageDecisionEmailDate(ZonedDateTime.now()) .build(); } private Application inProgressClosedCompApplication() { return newApplication() .withProcessRole(processRole) .withApplicationState(ApplicationState.OPENED) .withCompetition(closedCompetition) .build(); } private Application inProgressOpenCompApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(openCompetition) .withApplicationState(ApplicationState.OPENED) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig.builder() .enabledForExpressionOfInterest(true) .build()) .build(); } private Application eoiApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(eoiCompetition) .withApplicationState(ApplicationState.OPENED) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig.builder() .enabledForExpressionOfInterest(true) .build()) .build(); } private Application completedProjectApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject().withProjectProcess(newProjectProcess().withActivityState(ProjectState.LIVE).build()).build()) .build(); } private Application projectInSetupApplication() { return newApplication() .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject() .withName("projectInSetupApplication") .withProjectProcess(newProjectProcess().withActivityState(ProjectState.SETUP).build()) .withProjectUsers(newProjectUser().withUser(newUser().withId(USER_ID).build()) .withPartnerOrganisation(newPartnerOrganisation() .withOrganisation(newOrganisation().build()) .build()) .build(1)) .build()) .build(); } private Application pendingPartnerInSetupApplication() { PendingPartnerProgress progress = new PendingPartnerProgress(null); return newApplication() .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject() .withName("pendingPartnerInSetupApplication") .withProjectProcess(newProjectProcess().withActivityState(ProjectState.SETUP).build()) .withProjectUsers(newProjectUser().withUser(newUser().withId(USER_ID).build()) .withPartnerOrganisation(newPartnerOrganisation() .withOrganisation(newOrganisation().build()) .withPendingPartnerProgress(progress).build()) .build(1)) .build()) .build(); } private Application h2020Application() { return newApplication() .withApplicationState(ApplicationState.SUBMITTED) .withCompetition(newCompetition().withCompetitionType(newCompetitionType().withName(H2020_TYPE_NAME).build()).withAlwaysOpen(false).build()) .build(); } }
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/application/transactional/ApplicationDashboardServiceImplTest.java
package org.innovateuk.ifs.application.transactional; import org.innovateuk.ifs.applicant.resource.dashboard.ApplicantDashboardResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardInProgressRowResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardInSetupRowResource; import org.innovateuk.ifs.applicant.resource.dashboard.DashboardRowResource; import org.innovateuk.ifs.application.domain.Application; import org.innovateuk.ifs.application.domain.ApplicationEoiEvidenceResponse; import org.innovateuk.ifs.application.domain.ApplicationExpressionOfInterestConfig; import org.innovateuk.ifs.application.repository.ApplicationEoiEvidenceResponseRepository; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.assessment.transactional.AssessmentService; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.domain.CompetitionEoiEvidenceConfig; import org.innovateuk.ifs.fundingdecision.domain.DecisionStatus; import org.innovateuk.ifs.interview.transactional.InterviewAssignmentService; import org.innovateuk.ifs.project.projectteam.domain.PendingPartnerProgress; import org.innovateuk.ifs.project.resource.ProjectState; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.resource.ProcessRoleType; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.time.ZonedDateTime; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.competition.builder.CompetitionTypeBuilder.newCompetitionType; import static org.innovateuk.ifs.competition.resource.CompetitionResource.H2020_TYPE_NAME; import static org.innovateuk.ifs.file.builder.FileEntryBuilder.newFileEntry; import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation; import static org.innovateuk.ifs.project.core.builder.PartnerOrganisationBuilder.newPartnerOrganisation; import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject; import static org.innovateuk.ifs.project.core.builder.ProjectProcessBuilder.newProjectProcess; import static org.innovateuk.ifs.project.core.builder.ProjectUserBuilder.newProjectUser; import static org.innovateuk.ifs.user.builder.ProcessRoleBuilder.newProcessRole; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class ApplicationDashboardServiceImplTest { @InjectMocks private ApplicationDashboardServiceImpl applicationDashboardService; @Mock private ApplicationEoiEvidenceResponseRepository applicationEoiEvidenceResponseRepository; @Mock private InterviewAssignmentService interviewAssignmentService; @Mock private ApplicationRepository applicationRepository; @Mock private AssessmentService assessmentService; private final Competition closedCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().minusDays(1)) .withAlwaysOpen(false) .build(); private final Competition openCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withAlwaysOpen(false) .build(); private final Competition eoiCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withEnabledForExpressionOfInterest(true) .withCompetitionEoiEvidenceConfig((CompetitionEoiEvidenceConfig.builder() .evidenceRequired(true) .build())) .withAlwaysOpen(false) .build(); private final Competition alwaysOpenCompetition = newCompetition().withSetupComplete(true) .withStartDate(ZonedDateTime.now().minusDays(2)) .withEndDate(ZonedDateTime.now().plusDays(1)) .withAlwaysOpen(true) .withEnabledForExpressionOfInterest(true) .build(); private static final long USER_ID = 1L; private final User user = newUser().withId(USER_ID).build(); private final ProcessRole processRole = newProcessRole().withRole(ProcessRoleType.LEADAPPLICANT).withUser(user).withOrganisationId(1234L).build(); @Test public void getApplicantDashboard() { Application h2020Application = h2020Application(); Application projectInSetupApplication = projectInSetupApplication(); Application pendingPartnerInSetupApplication = pendingPartnerInSetupApplication(); Application completedProjectApplication = completedProjectApplication(); Application inProgressOpenCompApplication = inProgressOpenCompApplication(); Application inProgressAlwaysOpenCompApplicationInAssessment = inProgressAlwaysOpenCompApplication(); Application inProgressClosedCompApplication = inProgressClosedCompApplication(); Application onHoldNotifiedApplication = onHoldNotifiedApplication(); Application unsuccessfulNotifiedApplication = unsuccessfulNotifiedApplication(); Application ineligibleApplication = ineligibleApplication(); Application submittedAwaitingDecisionApplication = submittedAwaitingDecisionApplication(); Application eoiApplicationWithoutEvidence = eoiApplication(); Application eoiApplicationWithEvidence = eoiApplication(); when(interviewAssignmentService.isApplicationAssigned(anyLong())).thenReturn(serviceSuccess(true)); List<Application> applications = asList(h2020Application, projectInSetupApplication, pendingPartnerInSetupApplication, completedProjectApplication, inProgressOpenCompApplication, inProgressClosedCompApplication, inProgressAlwaysOpenCompApplicationInAssessment, onHoldNotifiedApplication, unsuccessfulNotifiedApplication, ineligibleApplication, submittedAwaitingDecisionApplication,eoiApplicationWithoutEvidence,eoiApplicationWithEvidence); when(applicationRepository.findApplicationsForDashboard(USER_ID)) .thenReturn(applications); when(applicationEoiEvidenceResponseRepository.findOneByApplicationId (eoiApplicationWithoutEvidence.getId())).thenReturn(Optional.empty()); ApplicationEoiEvidenceResponse applicationEoiEvidenceResponse = ApplicationEoiEvidenceResponse.builder() .application(newApplication().build()) .organisation(newOrganisation().build()) .fileEntry(newFileEntry().build()) .build(); when(applicationEoiEvidenceResponseRepository.findOneByApplicationId (eoiApplicationWithEvidence.getId())).thenReturn(Optional.of(applicationEoiEvidenceResponse)); ApplicantDashboardResource dashboardResource = applicationDashboardService.getApplicantDashboard(USER_ID).getSuccess(); assertEquals(1, dashboardResource.getEuGrantTransfer().size()); assertEquals(6, dashboardResource.getInProgress().size()); assertEquals(2, dashboardResource.getInSetup().size()); assertEquals(4, dashboardResource.getPrevious().size()); assertListContainsApplication(h2020Application, dashboardResource.getEuGrantTransfer()); DashboardInSetupRowResource notPendingResource = assertListContainsApplication(projectInSetupApplication, dashboardResource.getInSetup()); DashboardInSetupRowResource pendingResource = assertListContainsApplication(pendingPartnerInSetupApplication, dashboardResource.getInSetup()); assertListContainsApplication(completedProjectApplication, dashboardResource.getPrevious()); assertListContainsApplication(inProgressOpenCompApplication, dashboardResource.getInProgress()); assertListContainsApplication(inProgressClosedCompApplication, dashboardResource.getPrevious()); assertListContainsApplication(onHoldNotifiedApplication, dashboardResource.getInProgress()); assertListContainsApplication(inProgressAlwaysOpenCompApplicationInAssessment, dashboardResource.getInProgress()); assertListContainsApplication(unsuccessfulNotifiedApplication, dashboardResource.getPrevious()); assertListContainsApplication(ineligibleApplication, dashboardResource.getPrevious()); assertListContainsApplication(submittedAwaitingDecisionApplication, dashboardResource.getInProgress()); assertFalse(dashboardResource.getInProgress().stream() .filter(DashboardInProgressRowResource::isAlwaysOpen) .findFirst().get() .isShowReopenLink()); assertTrue(pendingResource.isPendingPartner()); assertFalse(notPendingResource.isPendingPartner()); assertTrue(dashboardResource.getInProgress().stream() .filter(DashboardInProgressRowResource::isAlwaysOpen) .findFirst().get() .isExpressionOfInterest()); List<DashboardInProgressRowResource> inProgressRowResourceList = dashboardResource.getInProgress(); assertFalse(inProgressRowResourceList.get(4).getEvidenceUploaded()); assertTrue(inProgressRowResourceList.get(5).getEvidenceUploaded()); } private Application inProgressAlwaysOpenCompApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(alwaysOpenCompetition) .withApplicationState(ApplicationState.SUBMITTED) .withDecision((DecisionStatus) null) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig .builder().enabledForExpressionOfInterest(true).build()) .build(); } private <R extends DashboardRowResource> R assertListContainsApplication(Application application, List<R> applications) { Optional<R> resource = applications.stream().filter(row -> application.getId().equals(row.getApplicationId())).findFirst(); assertTrue(resource.isPresent()); return resource.get(); } private Application submittedAwaitingDecisionApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.SUBMITTED) .build(); } private Application ineligibleApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.INELIGIBLE_INFORMED) .build(); } private Application unsuccessfulNotifiedApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.REJECTED) .withDecision(DecisionStatus.UNFUNDED) .withManageDecisionEmailDate(ZonedDateTime.now()) .build(); } private Application onHoldNotifiedApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.SUBMITTED) .withDecision(DecisionStatus.ON_HOLD) .withManageDecisionEmailDate(ZonedDateTime.now()) .build(); } private Application inProgressClosedCompApplication() { return newApplication() .withProcessRole(processRole) .withApplicationState(ApplicationState.OPENED) .withCompetition(closedCompetition) .build(); } private Application inProgressOpenCompApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(openCompetition) .withApplicationState(ApplicationState.OPENED) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig.builder() .enabledForExpressionOfInterest(true) .build()) .build(); } private Application eoiApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(eoiCompetition) .withApplicationState(ApplicationState.OPENED) .withApplicationExpressionOfInterestConfig(ApplicationExpressionOfInterestConfig.builder() .enabledForExpressionOfInterest(true) .build()) .build(); } private Application completedProjectApplication() { return newApplication() .withProcessRole(processRole) .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject().withProjectProcess(newProjectProcess().withActivityState(ProjectState.LIVE).build()).build()) .build(); } private Application projectInSetupApplication() { return newApplication() .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject() .withName("projectInSetupApplication") .withProjectProcess(newProjectProcess().withActivityState(ProjectState.SETUP).build()) .withProjectUsers(newProjectUser().withUser(newUser().withId(USER_ID).build()) .withPartnerOrganisation(newPartnerOrganisation() .withOrganisation(newOrganisation().build()) .build()) .build(1)) .build()) .build(); } private Application pendingPartnerInSetupApplication() { PendingPartnerProgress progress = new PendingPartnerProgress(null); return newApplication() .withCompetition(closedCompetition) .withApplicationState(ApplicationState.APPROVED) .withProject(newProject() .withName("pendingPartnerInSetupApplication") .withProjectProcess(newProjectProcess().withActivityState(ProjectState.SETUP).build()) .withProjectUsers(newProjectUser().withUser(newUser().withId(USER_ID).build()) .withPartnerOrganisation(newPartnerOrganisation() .withOrganisation(newOrganisation().build()) .withPendingPartnerProgress(progress).build()) .build(1)) .build()) .build(); } private Application h2020Application() { return newApplication() .withApplicationState(ApplicationState.SUBMITTED) .withCompetition(newCompetition().withCompetitionType(newCompetitionType().withName(H2020_TYPE_NAME).build()).withAlwaysOpen(false).build()) .build(); } }
IFS-12522 ut updated for EOI evidence
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/application/transactional/ApplicationDashboardServiceImplTest.java
IFS-12522 ut updated for EOI evidence
Java
mit
9fa68d27583d907b0e93f8a3edf0121aa9eaefc3
0
raygomez/diacoder
package com.opensource.diacoder.avp; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class Unsigned32Test { @Test public void testUnsigned32EncodeWithoutVendorId() { Unsigned32 avp = new Unsigned32(); avp.setAvpCode(0x11223344); avp.setData(0x88776655); avp.setMandatory(true); byte[] expected = { 0x11, 0x22, 0x33, 0x44, 0x40, 0x00, 0x00, (byte) 0x0C, (byte) 0x88, 0x77, 0x66, 0x55 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testUnsigned32EncodeWithVendorId() { Unsigned32 avp = new Unsigned32(); avp.setAvpCode(0x11223344); avp.setVendorId(0xFFEEDDCC); avp.setData(0x88776655); avp.setMandatory(false); byte[] expected = { 0x11, 0x22, 0x33, 0x44, (byte) 0x80, 0x00, 0x00, (byte) 0x10, (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0x88, 0x77, 0x66, 0x55 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testUnsigned32DecodeWithoutVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, 0x40, 0x00, 0x00, (byte) 0x0C, (byte) 0x88, 0x77, 0x66, 0x55 }; Unsigned32 avp = new Unsigned32(); avp.decode(input); assertEquals(0x88776655, avp.getAvpCode()); assertEquals(0x88776655, avp.getData()); assertFalse(avp.hasVendorId()); assertTrue(avp.isMandatory()); assertFalse(avp.isEncrypted()); } @Test public void testUnsigned32DecodeWithVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, (byte) 0x80, 0x00, 0x00, (byte) 0x10, (byte) 0x87, 0x65, 0x43, 0x21, (byte) 0x88, 0x77, 0x66, 0x55 }; Unsigned32 avp = new Unsigned32(); avp.decode(input); assertEquals(0x88776655, avp.getAvpCode()); assertEquals(0x88776655, avp.getData()); assertTrue(avp.hasVendorId()); assertEquals(0x87654321, avp.getVendorId()); assertFalse(avp.isMandatory()); assertFalse(avp.isEncrypted()); } }
src/test/java/com/opensource/diacoder/avp/Unsigned32Test.java
package com.opensource.diacoder.avp; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Assert; import org.junit.Test; public class Unsigned32Test { @Test public void testUnsigned32EncodeWithoutVendorId() { Unsigned32 avp = new Unsigned32(); avp.setAvpCode(0x11223344); avp.setData(0x88776655); avp.setMandatory(true); byte[] expected = { 0x11, 0x22, 0x33, 0x44, 0x40, 0x00, 0x00, (byte) 0x0C, (byte) 0x88, 0x77, 0x66, 0x55 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testUnsigned32EncodeWithVendorId() { Unsigned32 avp = new Unsigned32(); avp.setAvpCode(0x11223344); avp.setVendorId(0xFFEEDDCC); avp.setData(0x88776655); avp.setMandatory(false); byte[] expected = { 0x11, 0x22, 0x33, 0x44, (byte) 0x80, 0x00, 0x00, (byte) 0x10, (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0x88, 0x77, 0x66, 0x55 }; byte[] actual = avp.encode(); assertArrayEquals(expected, actual); } @Test public void testUnsigned32DecodeWithoutVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, 0x40, 0x00, 0x00, (byte) 0x0C, (byte) 0x88, 0x77, 0x66, 0x55 }; Unsigned32 avp = new Unsigned32(); avp.decode(input); assertEquals(0x88776655, avp.getAvpCode()); assertEquals(0x88776655, avp.getData()); assertFalse(avp.hasVendorId()); assertTrue(avp.isMandatory()); assertFalse(avp.isEncrypted()); } @Test public void testUnsigned32DecodeWithVendorId() { byte[] input = { (byte) 0x88, 0x77, 0x66, 0x55, 0x40, 0x00, 0x00, (byte) 0x10, (byte) 0x87, 0x65, 0x43, 0x21, (byte) 0x88, 0x77, 0x66, 0x55 }; Unsigned32 avp = new Unsigned32(); avp.decode(input); assertEquals(0x88776655, avp.getAvpCode()); assertEquals(0x88776655, avp.getData()); assertTrue(avp.hasVendorId()); assertEquals(0x87654321, avp.getVendorId()); assertFalse(avp.isMandatory()); assertFalse(avp.isEncrypted()); } }
fix test
src/test/java/com/opensource/diacoder/avp/Unsigned32Test.java
fix test
Java
mit
27cc6cc5e14c0ebe6ca0312c44731d8e35079ac5
0
Backendless/Android-SDK,Backendless/Android-SDK
package com.backendless; import android.app.Application; import android.content.Context; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Created by dzidzoiev on 11/10/15. */ public class ContextHandler { static private Context appContext; private ContextHandler() { throw new IllegalStateException( "static" ); } public synchronized static Context getAppContext() { if(appContext == null) appContext = recoverAppContext(); return appContext; } public synchronized static void setContext( Object anyContext ) { if( Backendless.isAndroid() ) appContext = ( (Context) anyContext ).getApplicationContext(); } /** * Magic methods */ private synchronized static Context recoverAppContext() { try { final Class<?> activityThreadClass = Class.forName( "android.app.ActivityThread" ); final Method method = activityThreadClass.getMethod( "currentApplication" ); Application app = (Application) method.invoke( null, (Object[]) null ); return app.getApplicationContext(); } catch ( NoSuchMethodException e ) { return recoverAppContextOldAndroid(); } catch ( Throwable e ) { e.printStackTrace(); } return null; } private synchronized static Context recoverAppContextOldAndroid() { try { final Class<?> activityThreadClass = Class.forName( "android.app.ActivityThread" ); final Method method = activityThreadClass.getMethod( "currentActivityThread" ); Object activityThread = method.invoke( null, (Object[]) null ); final Field field = activityThreadClass.getDeclaredField( "mInitialApplication" ); field.setAccessible( true ); Application app = (Application) field.get( activityThread ); return app.getApplicationContext(); } catch ( Throwable e ) { e.printStackTrace(); } return null; } }
src/com/backendless/ContextHandler.java
package com.backendless; import android.app.Application; import android.content.Context; import java.lang.reflect.Field; import java.lang.reflect.Method; /** * Created by dzidzoiev on 11/10/15. */ public class ContextHandler { static private Context appContext; private ContextHandler() { throw new IllegalStateException( "static" ); } public synchronized static Context getAppContext() { if(appContext == null) { appContext = recoverAppContext(); } return appContext; } public synchronized static void setContext( Object anyContext ) { if( Backendless.isAndroid() ) appContext = ( (Context) anyContext ).getApplicationContext(); } /** * Magic methods */ private synchronized static Context recoverAppContext() { try { final Class<?> activityThreadClass = Class.forName( "android.app.ActivityThread" ); final Method method = activityThreadClass.getMethod( "currentApplication" ); Application app = (Application) method.invoke( null, (Object[]) null ); return app.getApplicationContext(); } catch ( NoSuchMethodException e ) { return recoverAppContextOldAndroid(); } catch ( Throwable e ) { e.printStackTrace(); } return null; } private synchronized static Context recoverAppContextOldAndroid() { try { final Class<?> activityThreadClass = Class.forName( "android.app.ActivityThread" ); final Method method = activityThreadClass.getMethod( "currentActivityThread" ); Object activityThread = method.invoke( null, (Object[]) null ); final Field field = activityThreadClass.getDeclaredField( "mInitialApplication" ); field.setAccessible( true ); Application app = (Application) field.get( activityThread ); return app.getApplicationContext(); } catch ( Throwable e ) { e.printStackTrace(); } return null; } }
BKNDLSS-10508 reformatting
src/com/backendless/ContextHandler.java
BKNDLSS-10508 reformatting
Java
mit
2931346d1332bfd3f86c97afd41e624e8e54f007
0
greboid/DMDirc,greboid/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,csmith/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,DMDirc/DMDirc,greboid/DMDirc,greboid/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client
/* * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs.error; import com.dmdirc.addons.ui_swing.MainFrame; import com.dmdirc.addons.ui_swing.components.StandardDialog; import com.dmdirc.logger.ErrorManager; import com.dmdirc.logger.ErrorReportStatus; import com.dmdirc.logger.ProgramError; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import net.miginfocom.layout.PlatformDefaults; import net.miginfocom.swing.MigLayout; /** * Error list dialog. */ public final class ErrorListDialog extends StandardDialog implements ActionListener, ListSelectionListener, TableModelListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 5; /** Table model. */ private final ErrorTableModel tableModel; /** Table scrollpane. */ private JScrollPane scrollPane; /** Error table. */ private ErrorTable table; /** Error detail panel. */ private ErrorDetailPanel errorDetails; /** Send button. */ private JButton sendButton; /** Delete button. */ private JButton deleteButton; /** Delete all button. */ private JButton deleteAllButton; /** Selected row. */ private final AtomicInteger selectedRow = new AtomicInteger(-1); /** Row being deleted. */ private boolean rowBeingDeleted = false; /** * Creates a new instance of ErrorListDialog. * * @param mainFrame Main frame */ public ErrorListDialog(final MainFrame mainFrame) { super(mainFrame, ModalityType.MODELESS); setTitle("DMDirc: Error list"); tableModel = new ErrorTableModel(); initComponents(); layoutComponents(); initListeners(); selectedRow.set(table.getSelectedRow()); pack(); } /** Initialises the components. */ private void initComponents() { initButtons(); scrollPane = new JScrollPane(); table = new ErrorTable(tableModel, scrollPane); table.setPreferredScrollableViewportSize(new Dimension(600, 150)); scrollPane.setViewportView(table); errorDetails = new ErrorDetailPanel(); } /** Initialises the buttons. */ private void initButtons() { orderButtons(new JButton(), new JButton()); getCancelButton().setText("Close"); sendButton = new JButton("Send"); deleteButton = new JButton("Delete"); deleteAllButton = new JButton("Delete All"); sendButton.setEnabled(false); deleteButton.setEnabled(false); if (tableModel.getRowCount() > 0) { deleteAllButton.setEnabled(true); } else { deleteAllButton.setEnabled(false); } } /** Initialises the listeners. */ private void initListeners() { tableModel.addTableModelListener(this); table.getSelectionModel().addListSelectionListener(this); sendButton.addActionListener(this); deleteButton.addActionListener(this); deleteAllButton.addActionListener(this); getOkButton().addActionListener(this); getCancelButton().addActionListener(this); } /** Lays out the components. */ private void layoutComponents() { final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); final JPanel panel = new JPanel(); panel.setLayout(new MigLayout("fill")); panel.add(errorDetails, "wrap, grow, push"); panel.add(deleteAllButton, "split 4, tag left, sgx button"); panel.add(deleteButton, "tag other, sgx button"); panel.add(sendButton, "tag other, sgx button"); panel.add(getCancelButton(), "tag ok, sgx button"); splitPane.setTopComponent(scrollPane); splitPane.setBottomComponent(panel); splitPane.setDividerSize((int) PlatformDefaults.getPanelInsets(0). getValue()); getContentPane().add(splitPane); } /** {@inheritDoc}. */ @Override public void valueChanged(final ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { final int localRow = table.getSelectedRow(); if (localRow > -1) { final ProgramError error = tableModel.getError( table.getRowSorter().convertRowIndexToModel(localRow)); errorDetails.setError(error); deleteButton.setEnabled(true); if (error.getReportStatus() == ErrorReportStatus.NOT_APPLICABLE || error.getReportStatus() == ErrorReportStatus.FINISHED) { sendButton.setEnabled(false); } else { sendButton.setEnabled(true); } } else { errorDetails.setError(null); deleteButton.setEnabled(false); sendButton.setEnabled(false); } synchronized (selectedRow) { if (rowBeingDeleted) { table.getSelectionModel().setSelectionInterval(selectedRow. get(), selectedRow.get()); rowBeingDeleted = false; } selectedRow.set(localRow); } } } /** * {@inheritDoc}. * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == getCancelButton()) { setVisible(false); } else if (e.getSource() == deleteButton) { synchronized (selectedRow) { ErrorManager.getErrorManager().deleteError(tableModel.getError( table.getRowSorter().convertRowIndexToModel( table.getSelectedRow()))); } } else if (e.getSource() == sendButton) { synchronized (selectedRow) { ErrorManager.getErrorManager().sendError(tableModel.getError( table.getRowSorter().convertRowIndexToModel( table.getSelectedRow()))); } } else if (e.getSource() == deleteAllButton) { ErrorManager.getErrorManager().deleteAll(); } } /** * {@inheritDoc} * * @param e Table model event */ @Override public void tableChanged(final TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: synchronized (selectedRow) { if (selectedRow.get() >= tableModel.getRowCount()) { selectedRow.set(tableModel.getRowCount() - 1); } table.getSelectionModel().setSelectionInterval(selectedRow. get(), selectedRow.get()); rowBeingDeleted = true; } break; case TableModelEvent.INSERT: synchronized (selectedRow) { table.getSelectionModel().setSelectionInterval(selectedRow. get(), selectedRow.get()); } break; case TableModelEvent.UPDATE: final int errorRow = e.getFirstRow(); final ProgramError error = tableModel.getError(errorRow); if (errorRow == table.getSelectedRow()) { if (error.getReportStatus() == ErrorReportStatus.NOT_APPLICABLE || error.getReportStatus() == ErrorReportStatus.FINISHED) { sendButton.setEnabled(false); } else { sendButton.setEnabled(true); } } break; } if (tableModel.getRowCount() > 0) { deleteAllButton.setEnabled(true); } else { deleteAllButton.setEnabled(false); } } }
src/com/dmdirc/addons/ui_swing/dialogs/error/ErrorListDialog.java
/* * Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.dmdirc.addons.ui_swing.dialogs.error; import com.dmdirc.addons.ui_swing.MainFrame; import com.dmdirc.addons.ui_swing.components.StandardDialog; import com.dmdirc.logger.ErrorManager; import com.dmdirc.logger.ErrorReportStatus; import com.dmdirc.logger.ProgramError; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import net.miginfocom.layout.PlatformDefaults; import net.miginfocom.swing.MigLayout; /** * Error list dialog. */ public final class ErrorListDialog extends StandardDialog implements ActionListener, ListSelectionListener, TableModelListener { /** * A version number for this class. It should be changed whenever the class * structure is changed (or anything else that would prevent serialized * objects being unserialized with the new class). */ private static final long serialVersionUID = 5; /** Table model. */ private final ErrorTableModel tableModel; /** Table scrollpane. */ private JScrollPane scrollPane; /** Error table. */ private ErrorTable table; /** Error detail panel. */ private ErrorDetailPanel errorDetails; /** Send button. */ private JButton sendButton; /** Delete button. */ private JButton deleteButton; /** Delete all button. */ private JButton deleteAllButton; /** Selected row. */ private int selectedRow = -1; /** Row being deleted. */ private boolean rowBeingDeleted = false; /** * Creates a new instance of ErrorListDialog. * * @param mainFrame Main frame */ public ErrorListDialog(final MainFrame mainFrame) { super(mainFrame, ModalityType.MODELESS); setTitle("DMDirc: Error list"); tableModel = new ErrorTableModel(); initComponents(); layoutComponents(); initListeners(); selectedRow = table.getSelectedRow(); pack(); } /** Initialises the components. */ private void initComponents() { initButtons(); scrollPane = new JScrollPane(); table = new ErrorTable(tableModel, scrollPane); table.setPreferredScrollableViewportSize(new Dimension(600, 150)); scrollPane.setViewportView(table); errorDetails = new ErrorDetailPanel(); } /** Initialises the buttons. */ private void initButtons() { orderButtons(new JButton(), new JButton()); getCancelButton().setText("Close"); sendButton = new JButton("Send"); deleteButton = new JButton("Delete"); deleteAllButton = new JButton("Delete All"); sendButton.setEnabled(false); deleteButton.setEnabled(false); if (tableModel.getRowCount() > 0) { deleteAllButton.setEnabled(true); } else { deleteAllButton.setEnabled(false); } } /** Initialises the listeners. */ private void initListeners() { tableModel.addTableModelListener(this); table.getSelectionModel().addListSelectionListener(this); sendButton.addActionListener(this); deleteButton.addActionListener(this); deleteAllButton.addActionListener(this); getOkButton().addActionListener(this); getCancelButton().addActionListener(this); } /** Lays out the components. */ private void layoutComponents() { final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true); final JPanel panel = new JPanel(); panel.setLayout(new MigLayout("fill")); panel.add(errorDetails, "wrap, grow, push"); panel.add(deleteAllButton, "split 4, tag left, sgx button"); panel.add(deleteButton, "tag other, sgx button"); panel.add(sendButton, "tag other, sgx button"); panel.add(getCancelButton(), "tag ok, sgx button"); splitPane.setTopComponent(scrollPane); splitPane.setBottomComponent(panel); splitPane.setDividerSize((int) PlatformDefaults.getPanelInsets(0). getValue()); getContentPane().add(splitPane); } /** {@inheritDoc}. */ @Override public void valueChanged(final ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { final int localRow = table.getSelectedRow(); if (localRow > -1) { final ProgramError error = tableModel.getError( table.getRowSorter().convertRowIndexToModel(localRow)); errorDetails.setError(error); deleteButton.setEnabled(true); if (error.getReportStatus() == ErrorReportStatus.NOT_APPLICABLE || error.getReportStatus() == ErrorReportStatus.FINISHED) { sendButton.setEnabled(false); } else { sendButton.setEnabled(true); } } else { errorDetails.setError(null); deleteButton.setEnabled(false); sendButton.setEnabled(false); } if (rowBeingDeleted) { table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); rowBeingDeleted = false; } selectedRow = localRow; } } /** * {@inheritDoc}. * * @param e Action event */ @Override public void actionPerformed(final ActionEvent e) { if (e.getSource() == getCancelButton()) { setVisible(false); } else if (e.getSource() == deleteButton) { synchronized (tableModel) { ErrorManager.getErrorManager().deleteError(tableModel.getError( table.getRowSorter().convertRowIndexToModel(selectedRow))); } } else if (e.getSource() == sendButton) { synchronized (tableModel) { ErrorManager.getErrorManager().sendError(tableModel.getError( table.getRowSorter().convertRowIndexToModel(selectedRow))); } } else if (e.getSource() == deleteAllButton) { ErrorManager.getErrorManager().deleteAll(); } } /** * {@inheritDoc} * * @param e Table model event */ @Override public void tableChanged(final TableModelEvent e) { switch (e.getType()) { case TableModelEvent.DELETE: if (selectedRow >= tableModel.getRowCount()) { selectedRow = tableModel.getRowCount() - 1; } table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); rowBeingDeleted = true; break; case TableModelEvent.INSERT: table.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); break; case TableModelEvent.UPDATE: final int errorRow = e.getFirstRow(); final ProgramError error = tableModel.getError(errorRow); if (errorRow == table.getSelectedRow()) { if (error.getReportStatus() == ErrorReportStatus.NOT_APPLICABLE || error.getReportStatus() == ErrorReportStatus.FINISHED) { sendButton.setEnabled(false); } else { sendButton.setEnabled(true); } } break; } if (tableModel.getRowCount() > 0) { deleteAllButton.setEnabled(true); } else { deleteAllButton.setEnabled(false); } } }
fixes issue 2585; fixes issue 2584
src/com/dmdirc/addons/ui_swing/dialogs/error/ErrorListDialog.java
fixes issue 2585; fixes issue 2584
Java
mit
0ea0f7812dd4f4699f38b77cf41a8e0ed398a9ad
0
asavonic/DotsBoxes,asavonic/DotsBoxes
package dotsboxes; /** * @file GameSession.java * @brief This file implement game logic ( add edge, add player's mark, win, lose, ...) */ import java.util.Vector; import dotsboxes.callbacks.EventCallback; import dotsboxes.events.Event; import dotsboxes.events.EventType; import dotsboxes.events.GUI_GameOverEvent; import dotsboxes.events.GameStartEvent; import dotsboxes.events.GameTurnEvent; import dotsboxes.events.SleepEvent; import dotsboxes.game.TurnDesc; import dotsboxes.utils.Debug; public class GameSession implements EventCallback { /** * @name GameSession * @brief Constructor GameSession. * Init game logic objects. * @param field_size - size of game field. * @param players_number - number of players. */ GameSession( int field_height, int field_width, int players_number, int begin__player_tag ) { EventManager.Subscribe( EventType.game_Turn, this); //Subscribe on game_Turn event. EventManager.Subscribe( EventType.GUI_game_Turn, this); EventManager.Subscribe( EventType.game_Start, this); EventManager.Subscribe( EventType.turn_unlock, this); EventManager.Subscribe( EventType.show_history, this); Init( field_height, field_width, players_number, begin__player_tag); } private void Init(int field_height, int field_width, int players_number, int begin__player_tag) { m_fieldHeight = field_height; m_fieldWidth = field_width; m_numberOfPlayers = players_number; m_current_player_tag = begin__player_tag; m_edgesH = new int[m_fieldHeight + 1][m_fieldWidth]; m_edgesV = new int[m_fieldHeight][m_fieldWidth + 1]; m_vertex = new int[m_fieldHeight][m_fieldWidth]; m_counters = new int[m_numberOfPlayers + 1]; m_history = new Vector<Event>(); for(int i = 0; i < m_fieldHeight + 1; ++i) for( int j = 0; j < m_fieldWidth; ++j) m_edgesH[i][j] = empty; for(int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth + 1; ++j) m_edgesV[i][j] = empty; for(int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth; ++j) m_vertex[i][j] = empty; for( int i = 0; i < m_fieldWidth; ++i) { m_edgesH[0][i] = border; m_edgesH[m_fieldHeight][i] = border; } for( int j = 0; j < m_fieldHeight; ++j) { m_edgesV[j][0] = border; m_edgesV[j][m_fieldWidth] = border; } Debug.log("GameSassion initializated."); } private void SendTurnEvent(GameTurnEvent event, boolean isSwitchTurn) { TurnDesc desc = new TurnDesc(event.getI(), event.getJ(), m_current_player_tag, event.getVert()); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, event.isEdgeChanged(),desc, isSwitchTurn); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, event.isEdgeChanged(),desc, isSwitchTurn); EventManager.NewEvent(ev, this); EventManager.NewEvent(ev_GUI, this); } private int GUITurn(Event ev) { GameTurnEvent game_event = (GameTurnEvent) ev; if (game_event.isEdgeChanged()) { int result = AddEdge( game_event.getI(), game_event.getJ(), game_event.getVert(), m_current_player_tag); if (0 != result) { if(1 == result) { SendTurnEvent(game_event, true); m_turnBlock = true; } else { SendTurnEvent(game_event, false); m_turnBlock = false; } m_history.add(game_event); return result; } } return 0; } private void Turn(Event ev) { GameTurnEvent game_event1 = (GameTurnEvent) ev; if (m_history.contains(ev)) // I can do that better. { Debug.log("Turn already exist."); return; } if (game_event1.isEdgeChanged()) { int result = AddEdge( game_event1.getI(), game_event1.getJ(), game_event1.getVert(), game_event1.getPlrTag()); if (0 != result) { TurnDesc desc = game_event1.getTurnDesc(); GameTurnEvent game_turn_GUI = new GameTurnEvent(EventType.GUI_game_Turn, true, desc); EventManager.NewEvent(game_turn_GUI, this); m_history.add(game_event1); } } else { //boolean result = AddMark( game_event1.getJ(), game_event1.getI(), game_event1.getPlrTag()); //if (result) //{ // //SendEvent(game_event1); // m_history.add(game_event1); //} } } void ShowRevertHistory(int history_indx) { Event event = m_history.elementAt(history_indx); switch(event.GetType()) { case GUI_game_Turn: case game_Turn: GameTurnEvent game_turn = (GameTurnEvent) event; TurnDesc desc = new TurnDesc(game_turn.getI(), game_turn.getJ(), empty, game_turn.getVert()); GameTurnEvent revert_event = new GameTurnEvent(EventType.GUI_game_Turn, game_turn.isEdgeChanged(), desc , false); EventManager.NewEvent(revert_event, this); EventManager.NewAnonimEvent(new Event(EventType.show_history)); break; } } void ShowHistory(int history_indx) { Event event = m_history.elementAt(history_indx); switch(event.GetType()) { case GUI_game_Turn: case game_Turn: GameTurnEvent game_turn = (GameTurnEvent) event; TurnDesc desc = new TurnDesc(game_turn.getI(), game_turn.getJ(), game_turn.getPlrTag(), game_turn.getVert()); GameTurnEvent revert_event = new GameTurnEvent(EventType.GUI_game_Turn, game_turn.isEdgeChanged(), desc , false); EventManager.NewEvent(revert_event, this); EventManager.NewAnonimEvent(new Event(EventType.show_history)); break; } } private void CheckWinAndSend() { if(m_gameOver) return; Vector<Integer> winners = CheckWin(); if(null != winners) { EventManager.NewEvent( new GUI_GameOverEvent( winners), this); m_gameOver = true; EventManager.NewAnonimEvent(new Event(EventType.show_history)); m_history_indx = m_history.size() - 1; } } private void SwitchCurrentPlayer() { m_current_player_tag++; m_current_player_tag %= m_numberOfPlayers; } /** * @name HandleEvent * @brief Handle event. * Receive and handle event. * @param Event - event that needs to handled into GameSession. * @retval void */ public void HandleEvent( Event ev) { switch(ev.GetType()) { case GUI_game_Turn: if(!m_turnBlock) switch(GUITurn(ev)) { case 1: SwitchCurrentPlayer(); break; } CheckWinAndSend(); break; case show_history: if( !m_reverse) { ShowHistory(m_history_indx); if( m_history_indx == m_history.size() - 1) m_reverse = true; else m_history_indx++; } else { ShowRevertHistory(m_history_indx); if( 0 == m_history_indx) m_reverse = false; else m_history_indx--; } EventManager.NewEvent(new SleepEvent(delay_show_history), this); break; case turn_unlock: Debug.log("You have not turn."); m_turnBlock = false; break; case game_Turn: GameTurnEvent turn_event = (GameTurnEvent) ev; Turn(ev); if( turn_event.isSwitchTurn()) SwitchCurrentPlayer(); CheckWinAndSend(); break; case game_Start: GameStartEvent g = (GameStartEvent)ev; Init(g.getFieldHeight(), g.getFieldWidth(), g.getNumPlayers(), g.getBeginPlayer()); break; default: Debug.log("Unknown event in GameSession!"); return; } } private int AddEdge( int i, int j, boolean vert, int player_tag) { int result = 0; int max_number_height = ( vert ) ? (m_fieldHeight + 1) : m_fieldHeight; int max_number_width = ( !vert ) ? (m_fieldWidth + 1) : m_fieldWidth; if( player_tag < 0 || player_tag >= m_numberOfPlayers) { Debug.log("Invalid value(player)! Player tag = " + player_tag + "."); return result; } if( i < 0 || j < 0 || i > max_number_height || j > max_number_width) { Debug.log("Invalid value(edge)! Player tag = " + player_tag + ". i = " + i + "(max = " + max_number_height + "); j = " + j + "(max = " + max_number_width + ")."); return result; } if ( vert ) { if (empty == m_edgesV[i][j]) { m_edgesV[i][j] = player_tag; Debug.log("Player " + player_tag + " mark edge [" + i + "][" + j + "](vertical)."); if (AddMark(j, i, player_tag)) { TurnDesc desc = new TurnDesc(j , i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); result = 1; m_history.addElement(ev); } if (AddMark(j - 1, i, player_tag)) { TurnDesc desc = new TurnDesc(j - 1, i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); result = 1; m_history.addElement(ev); } return ++result; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] (vertical) but edge busy already."); return result; } } else { if (empty == m_edgesH[i][j]) { m_edgesH[i][j] = player_tag; Debug.log("Player " + player_tag + " mark edge [" + i + "][" + j + "](horizontal)."); if (AddMark(j, i, player_tag)) { TurnDesc desc = new TurnDesc(j , i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); m_history.addElement(ev); result = 1; } if (AddMark(j, i - 1, player_tag)) { TurnDesc desc = new TurnDesc(j , i - 1, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false ,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); m_history.addElement(ev); result = 1; } return ++result; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] (horizontal) but edge busy already."); return result; } } } private boolean AddMark( int i, int j, int player_tag) { if (player_tag < 0 || player_tag >= m_numberOfPlayers) { Debug.log("Invalid value(player)! Player tag = " + player_tag + "."); return false; } if (i < 0 || j < 0 || i > m_fieldWidth || j > m_fieldHeight) { Debug.log("Invalid value (mark)! Player tag = " + player_tag + ". i = " + i + "(max = " + m_fieldHeight + "); j = " + j + "(max = " + m_fieldWidth + ")."); return false; } if (((empty == m_edgesV[j][i]) & (border != m_edgesV[j][i])) || ((empty == m_edgesH[j][i]) & (border != m_edgesH[j][i])) || //Check for edges around. ((empty == m_edgesH[j + 1][i]) & (border != m_edgesH[j + 1][i])) || ((empty == m_edgesV[j][i + 1]) & (border != m_edgesV[j][i + 1])) ) { Debug.log("Player " + player_tag + " try to mark vertex [" + i + "][" + j + "] but edges around this vertex doesn't mark as him."); return false; } if (empty == m_vertex[j][i]) { m_vertex[j][i] = player_tag; m_counters[player_tag] += 1; Debug.log("Player " + player_tag + " mark vertex [" + i + "][" + j + "]."); return true; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] but edge busy already."); return false; } } private Vector<Integer> CheckWin() { //Go across horizontal edges. for( int i = 1; i < m_fieldHeight; ++i) for( int j = 1; j < m_fieldWidth; ++j) { if ((empty == m_edgesH[i][j])) { return null; } } //Go across vertical edges. for( int i = 0; i < m_fieldHeight; ++i) for( int j = 1; j < m_fieldWidth; ++j) { if ((empty == m_edgesV[i][j])) { return null; } } // OK. All edges marked. //Check for all vertex marked. for( int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth; ++j) { if (empty == m_vertex[i][j]) { return null; } } int max = 0; Vector<Integer> winners = new Vector<Integer>(); for( int i = 0; i < m_numberOfPlayers; ++i) if ( m_counters[i] > max) { max = m_counters[i]; winners.clear(); winners.add(i); } else if (m_counters[i] == max) { winners.add(i); } Debug.log("Player " + winners + " win!."); return winners; } public void Draw() { Debug.log("========================================"); Debug.log("Nuber of players = " + m_numberOfPlayers); Debug.log("Height = " + m_fieldHeight); Debug.log("Width = " + m_fieldWidth); Debug.log(""); String horizontalLines = new String(); String hor_lin = new String("---------"); String ver_lin = new String("|"); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalLines += hor_lin; } for( int i = 0; i < m_fieldHeight; ++i ) { String horizontalValue = new String(" "); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalValue += ver_lin; if (border == m_edgesV[i][j]) { horizontalValue += String.valueOf(m_edgesV[i][j]); } else { horizontalValue += " "; horizontalValue += String.valueOf(m_edgesV[i][j]); } horizontalValue += ver_lin; horizontalValue += " "; } Debug.log(horizontalLines); Debug.log(horizontalValue); Debug.log(horizontalLines); horizontalValue = new String(); for( int j = 0; j < m_fieldHeight; ++j ) { horizontalValue += ver_lin; horizontalValue += " "; horizontalValue += String.valueOf(m_edgesH[i][j]); horizontalValue += ver_lin; horizontalValue += "*"; horizontalValue += String.valueOf(m_vertex[i][j]); } horizontalValue += ver_lin; horizontalValue += String.valueOf(m_edgesH[i][m_fieldHeight]); horizontalValue += ver_lin; Debug.log(horizontalValue); } String horizontalValue = new String(" "); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalValue += ver_lin; if (border == m_edgesV[m_fieldHeight][j]) { horizontalValue += String.valueOf(m_edgesV[m_fieldHeight][j]); } else { horizontalValue += " "; horizontalValue += String.valueOf(m_edgesV[m_fieldHeight][j]); } horizontalValue += ver_lin; horizontalValue += " "; } Debug.log(horizontalLines); Debug.log(horizontalValue); Debug.log(horizontalLines); Debug.log(""); Debug.log("========================================"); } int m_history_indx = 0; boolean m_reverse = true; boolean m_gameOver = false; int m_fieldHeight; int m_fieldWidth; int m_numberOfPlayers; boolean m_turnBlock = true; int m_current_player_tag; int m_edgesV[][]; // List of vertical edges. int m_edgesH[][]; // List of horizontal edges. int m_vertex[][]; int m_counters[]; // List of number of marked vertex. Vector<Event> m_history; static int border = -1; static int empty = -2; static int delay_show_history = 200; }
src/dotsboxes/GameSession.java
package dotsboxes; /** * @file GameSession.java * @brief This file implement game logic ( add edge, add player's mark, win, lose, ...) */ import java.util.Vector; import dotsboxes.callbacks.EventCallback; import dotsboxes.events.Event; import dotsboxes.events.EventType; import dotsboxes.events.GUI_GameOverEvent; import dotsboxes.events.GameStartEvent; import dotsboxes.events.GameTurnEvent; import dotsboxes.events.SleepEvent; import dotsboxes.game.TurnDesc; import dotsboxes.utils.Debug; public class GameSession implements EventCallback { /** * @name GameSession * @brief Constructor GameSession. * Init game logic objects. * @param field_size - size of game field. * @param players_number - number of players. */ GameSession( int field_height, int field_width, int players_number, int begin__player_tag ) { EventManager.Subscribe( EventType.game_Turn, this); //Subscribe on game_Turn event. EventManager.Subscribe( EventType.GUI_game_Turn, this); EventManager.Subscribe( EventType.game_Start, this); EventManager.Subscribe( EventType.turn_unlock, this); EventManager.Subscribe( EventType.show_history, this); Init( field_height, field_width, players_number, begin__player_tag); } private void Init(int field_height, int field_width, int players_number, int begin__player_tag) { m_fieldHeight = field_height; m_fieldWidth = field_width; m_numberOfPlayers = players_number; m_current_player_tag = begin__player_tag; m_edgesH = new int[m_fieldHeight + 1][m_fieldWidth]; m_edgesV = new int[m_fieldHeight][m_fieldWidth + 1]; m_vertex = new int[m_fieldHeight][m_fieldWidth]; m_counters = new int[m_numberOfPlayers + 1]; m_history = new Vector<Event>(); for(int i = 0; i < m_fieldHeight + 1; ++i) for( int j = 0; j < m_fieldWidth; ++j) m_edgesH[i][j] = empty; for(int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth + 1; ++j) m_edgesV[i][j] = empty; for(int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth; ++j) m_vertex[i][j] = empty; for( int i = 0; i < m_fieldWidth; ++i) { m_edgesH[0][i] = border; m_edgesH[m_fieldHeight][i] = border; } for( int j = 0; j < m_fieldHeight; ++j) { m_edgesV[j][0] = border; m_edgesV[j][m_fieldWidth] = border; } Debug.log("GameSassion initializated."); } private void SendTurnEvent(GameTurnEvent event, boolean isSwitchTurn) { TurnDesc desc = new TurnDesc(event.getI(), event.getJ(), m_current_player_tag, event.getVert()); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, event.isEdgeChanged(),desc, isSwitchTurn); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, event.isEdgeChanged(),desc, isSwitchTurn); EventManager.NewEvent(ev, this); EventManager.NewEvent(ev_GUI, this); } private int GUITurn(Event ev) { GameTurnEvent game_event = (GameTurnEvent) ev; if (game_event.isEdgeChanged()) { int result = AddEdge( game_event.getI(), game_event.getJ(), game_event.getVert(), m_current_player_tag); if (0 != result) { if(1 == result) { SendTurnEvent(game_event, true); m_turnBlock = true; } else { SendTurnEvent(game_event, false); m_turnBlock = false; } m_history.add(game_event); return result; } } return 0; } private void Turn(Event ev) { GameTurnEvent game_event1 = (GameTurnEvent) ev; if (m_history.contains(ev)) // I can do that better. { Debug.log("Turn already exist."); return; } if (game_event1.isEdgeChanged()) { int result = AddEdge( game_event1.getI(), game_event1.getJ(), game_event1.getVert(), game_event1.getPlrTag()); if (0 != result) { TurnDesc desc = game_event1.getTurnDesc(); GameTurnEvent game_turn_GUI = new GameTurnEvent(EventType.GUI_game_Turn, true, desc); EventManager.NewEvent(game_turn_GUI, this); m_history.add(game_event1); } } else { //boolean result = AddMark( game_event1.getJ(), game_event1.getI(), game_event1.getPlrTag()); //if (result) //{ // //SendEvent(game_event1); // m_history.add(game_event1); //} } } void ShowRevertHistory(int history_indx) { Event event = m_history.elementAt(history_indx); switch(event.GetType()) { case GUI_game_Turn: case game_Turn: GameTurnEvent game_turn = (GameTurnEvent) event; TurnDesc desc = new TurnDesc(game_turn.getI(), game_turn.getJ(), empty, game_turn.getVert()); GameTurnEvent revert_event = new GameTurnEvent(EventType.GUI_game_Turn, game_turn.isEdgeChanged(), desc , false); EventManager.NewEvent(revert_event, this); EventManager.NewAnonimEvent(new Event(EventType.show_history)); break; } } void ShowHistory(int history_indx) { Event event = m_history.elementAt(history_indx); switch(event.GetType()) { case GUI_game_Turn: case game_Turn: GameTurnEvent game_turn = (GameTurnEvent) event; TurnDesc desc = new TurnDesc(game_turn.getI(), game_turn.getJ(), game_turn.getPlrTag(), game_turn.getVert()); GameTurnEvent revert_event = new GameTurnEvent(EventType.GUI_game_Turn, game_turn.isEdgeChanged(), desc , false); EventManager.NewEvent(revert_event, this); EventManager.NewAnonimEvent(new Event(EventType.show_history)); break; } } private void CheckWinAndSend() { Vector<Integer> winners = CheckWin(); if(null != winners) { EventManager.NewEvent( new GUI_GameOverEvent( winners), this); EventManager.NewAnonimEvent(new Event(EventType.show_history)); m_history_indx = m_history.size() - 1; } } private void SwitchCurrentPlayer() { m_current_player_tag++; m_current_player_tag %= m_numberOfPlayers; } /** * @name HandleEvent * @brief Handle event. * Receive and handle event. * @param Event - event that needs to handled into GameSession. * @retval void */ public void HandleEvent( Event ev) { switch(ev.GetType()) { case GUI_game_Turn: if(!m_turnBlock) switch(GUITurn(ev)) { case 1: SwitchCurrentPlayer(); break; } CheckWinAndSend(); break; case show_history: if( !m_reverse) { ShowHistory(m_history_indx); if( m_history_indx == m_history.size() - 1) m_reverse = true; else m_history_indx++; } else { ShowRevertHistory(m_history_indx); if( 0 == m_history_indx) m_reverse = false; else m_history_indx--; } EventManager.NewEvent(new SleepEvent(delay_show_history), this); break; case turn_unlock: Debug.log("You have not turn."); m_turnBlock = false; break; case game_Turn: GameTurnEvent turn_event = (GameTurnEvent) ev; Turn(ev); if( turn_event.isSwitchTurn()) SwitchCurrentPlayer(); CheckWinAndSend(); break; case game_Start: GameStartEvent g = (GameStartEvent)ev; Init(g.getFieldHeight(), g.getFieldWidth(), g.getNumPlayers(), g.getBeginPlayer()); break; default: Debug.log("Unknown event in GameSession!"); return; } } private int AddEdge( int i, int j, boolean vert, int player_tag) { int result = 0; int max_number_height = ( vert ) ? (m_fieldHeight + 1) : m_fieldHeight; int max_number_width = ( !vert ) ? (m_fieldWidth + 1) : m_fieldWidth; if( player_tag < 0 || player_tag >= m_numberOfPlayers) { Debug.log("Invalid value(player)! Player tag = " + player_tag + "."); return result; } if( i < 0 || j < 0 || i > max_number_height || j > max_number_width) { Debug.log("Invalid value(edge)! Player tag = " + player_tag + ". i = " + i + "(max = " + max_number_height + "); j = " + j + "(max = " + max_number_width + ")."); return result; } if ( vert ) { if (empty == m_edgesV[i][j]) { m_edgesV[i][j] = player_tag; Debug.log("Player " + player_tag + " mark edge [" + i + "][" + j + "](vertical)."); if (AddMark(j, i, player_tag)) { TurnDesc desc = new TurnDesc(j , i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); result = 1; m_history.addElement(ev); } if (AddMark(j - 1, i, player_tag)) { TurnDesc desc = new TurnDesc(j - 1, i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); result = 1; m_history.addElement(ev); } return ++result; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] (vertical) but edge busy already."); return result; } } else { if (empty == m_edgesH[i][j]) { m_edgesH[i][j] = player_tag; Debug.log("Player " + player_tag + " mark edge [" + i + "][" + j + "](horizontal)."); if (AddMark(j, i, player_tag)) { TurnDesc desc = new TurnDesc(j , i, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); m_history.addElement(ev); result = 1; } if (AddMark(j, i - 1, player_tag)) { TurnDesc desc = new TurnDesc(j , i - 1, player_tag); GameTurnEvent ev = new GameTurnEvent(EventType.game_Turn, false ,desc, false); EventManager.NewEvent(ev, this); GameTurnEvent ev_GUI = new GameTurnEvent(EventType.GUI_game_Turn, false,desc, false); EventManager.NewEvent(ev_GUI, this); m_history.addElement(ev); result = 1; } return ++result; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] (horizontal) but edge busy already."); return result; } } } private boolean AddMark( int i, int j, int player_tag) { if (player_tag < 0 || player_tag >= m_numberOfPlayers) { Debug.log("Invalid value(player)! Player tag = " + player_tag + "."); return false; } if (i < 0 || j < 0 || i > m_fieldWidth || j > m_fieldHeight) { Debug.log("Invalid value (mark)! Player tag = " + player_tag + ". i = " + i + "(max = " + m_fieldHeight + "); j = " + j + "(max = " + m_fieldWidth + ")."); return false; } if (((empty == m_edgesV[j][i]) & (border != m_edgesV[j][i])) || ((empty == m_edgesH[j][i]) & (border != m_edgesH[j][i])) || //Check for edges around. ((empty == m_edgesH[j + 1][i]) & (border != m_edgesH[j + 1][i])) || ((empty == m_edgesV[j][i + 1]) & (border != m_edgesV[j][i + 1])) ) { Debug.log("Player " + player_tag + " try to mark vertex [" + i + "][" + j + "] but edges around this vertex doesn't mark as him."); return false; } if (empty == m_vertex[j][i]) { m_vertex[j][i] = player_tag; m_counters[player_tag] += 1; Debug.log("Player " + player_tag + " mark vertex [" + i + "][" + j + "]."); return true; } else { Debug.log("Player " + player_tag + " try to mark edge [" + i + "][" + j + "] but edge busy already."); return false; } } private Vector<Integer> CheckWin() { //Go across horizontal edges. for( int i = 1; i < m_fieldHeight; ++i) for( int j = 1; j < m_fieldWidth; ++j) { if ((empty == m_edgesH[i][j])) { return null; } } //Go across vertical edges. for( int i = 0; i < m_fieldHeight; ++i) for( int j = 1; j < m_fieldWidth; ++j) { if ((empty == m_edgesV[i][j])) { return null; } } // OK. All edges marked. //Check for all vertex marked. for( int i = 0; i < m_fieldHeight; ++i) for( int j = 0; j < m_fieldWidth; ++j) { if (empty == m_vertex[i][j]) { return null; } } int max = 0; Vector<Integer> winners = new Vector<Integer>(); for( int i = 0; i < m_numberOfPlayers; ++i) if ( m_counters[i] > max) { max = m_counters[i]; winners.clear(); winners.add(i); } else if (m_counters[i] == max) { winners.add(i); } Debug.log("Player " + winners + " win!."); return winners; } public void Draw() { Debug.log("========================================"); Debug.log("Nuber of players = " + m_numberOfPlayers); Debug.log("Height = " + m_fieldHeight); Debug.log("Width = " + m_fieldWidth); Debug.log(""); String horizontalLines = new String(); String hor_lin = new String("---------"); String ver_lin = new String("|"); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalLines += hor_lin; } for( int i = 0; i < m_fieldHeight; ++i ) { String horizontalValue = new String(" "); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalValue += ver_lin; if (border == m_edgesV[i][j]) { horizontalValue += String.valueOf(m_edgesV[i][j]); } else { horizontalValue += " "; horizontalValue += String.valueOf(m_edgesV[i][j]); } horizontalValue += ver_lin; horizontalValue += " "; } Debug.log(horizontalLines); Debug.log(horizontalValue); Debug.log(horizontalLines); horizontalValue = new String(); for( int j = 0; j < m_fieldHeight; ++j ) { horizontalValue += ver_lin; horizontalValue += " "; horizontalValue += String.valueOf(m_edgesH[i][j]); horizontalValue += ver_lin; horizontalValue += "*"; horizontalValue += String.valueOf(m_vertex[i][j]); } horizontalValue += ver_lin; horizontalValue += String.valueOf(m_edgesH[i][m_fieldHeight]); horizontalValue += ver_lin; Debug.log(horizontalValue); } String horizontalValue = new String(" "); for( int j = 0; j < m_fieldWidth; ++j ) { horizontalValue += ver_lin; if (border == m_edgesV[m_fieldHeight][j]) { horizontalValue += String.valueOf(m_edgesV[m_fieldHeight][j]); } else { horizontalValue += " "; horizontalValue += String.valueOf(m_edgesV[m_fieldHeight][j]); } horizontalValue += ver_lin; horizontalValue += " "; } Debug.log(horizontalLines); Debug.log(horizontalValue); Debug.log(horizontalLines); Debug.log(""); Debug.log("========================================"); } int m_history_indx = 0; boolean m_reverse = true; int m_fieldHeight; int m_fieldWidth; int m_numberOfPlayers; boolean m_turnBlock = true; int m_current_player_tag; int m_edgesV[][]; // List of vertical edges. int m_edgesH[][]; // List of horizontal edges. int m_vertex[][]; int m_counters[]; // List of number of marked vertex. Vector<Event> m_history; static int border = -1; static int empty = -2; static int delay_show_history = 200; }
Fix multimple game over event.
src/dotsboxes/GameSession.java
Fix multimple game over event.
Java
mit
9588350b5593c8751aeb69678a0ba220499adf9a
0
Lydwen/CentralTrafficLightManagement-SmartCity,Lydwen/CentralTrafficLightManagement-SmartCity
package fr.unice.polytech.al.trafficlight.central; import fr.unice.polytech.al.trafficlight.central.business.ScenarioChecker; import fr.unice.polytech.al.trafficlight.utils.RuleGroup; import fr.unice.polytech.al.trafficlight.utils.Scenario; import fr.unice.polytech.al.trafficlight.utils.TrafficLightId; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * Created by rhoo on 14/11/16. */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = Application.class) public class TestScenarioChecker { @Autowired private ScenarioChecker checker; private Scenario ScenarioTrue; private Scenario ScenarioFalse; private String falseCrossroadName = "00000"; @Before public void init() { ScenarioTrue = new Scenario("basicScenario"); RuleGroup group1 = new RuleGroup("group1", 20,20); RuleGroup group2 = new RuleGroup("group2", 40,40); TrafficLightId id1 = new TrafficLightId("feu de l'avenue des orangers"); TrafficLightId id2 = new TrafficLightId("feu de l'avenue du tapis vert"); group1.addTrafficLight(id1); group2.addTrafficLight(id2); ScenarioTrue.addRuleGroup(0, group1); ScenarioTrue.addRuleGroup(1, group2); ScenarioTrue.setTransitionTime(5); ScenarioFalse = new Scenario("basicScenario"); group1 = new RuleGroup("group1", 20,20); group2 = new RuleGroup("group2", 40,20); group1.addTrafficLight(id1); group1.addTrafficLight(id2); group2.addTrafficLight(id2); ScenarioFalse.addRuleGroup(0, group1); ScenarioFalse.addRuleGroup(1, group2); ScenarioFalse.setTransitionTime(5); } @Test public void testScenario() { assertEquals("OK",checker.checkScenario(ScenarioTrue)); assertEquals("All trafficLight green at same time",checker.checkScenario(ScenarioFalse)); } @Test public void testCheckAndSet() { assertEquals("The specified crossroad name doesn't exist : " + falseCrossroadName, checker.checkAndSetScenario(ScenarioTrue,falseCrossroadName)); } }
central/src/test/java/fr/unice/polytech/al/trafficlight/central/TestScenarioChecker.java
package fr.unice.polytech.al.trafficlight.central; import fr.unice.polytech.al.trafficlight.central.business.ScenarioChecker; import fr.unice.polytech.al.trafficlight.utils.RuleGroup; import fr.unice.polytech.al.trafficlight.utils.Scenario; import fr.unice.polytech.al.trafficlight.utils.TrafficLightId; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; /** * Created by rhoo on 14/11/16. */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(classes = Application.class) public class TestScenarioChecker { @Autowired private ScenarioChecker checker; private Scenario ScenarioTrue; private Scenario ScenarioFalse; private String falseCrossroadName = "00000"; @Before public void init() { ScenarioTrue = new Scenario("basicScenario"); RuleGroup group1 = new RuleGroup("group1", 20); RuleGroup group2 = new RuleGroup("group2", 40); TrafficLightId id1 = new TrafficLightId("feu de l'avenue des orangers"); TrafficLightId id2 = new TrafficLightId("feu de l'avenue du tapis vert"); group1.addTrafficLight(id1); group2.addTrafficLight(id2); ScenarioTrue.addRuleGroup(0, group1); ScenarioTrue.addRuleGroup(1, group2); ScenarioTrue.setTransitionTime(5); ScenarioFalse = new Scenario("basicScenario"); group1 = new RuleGroup("group1", 20); group2 = new RuleGroup("group2", 40); group1.addTrafficLight(id1); group1.addTrafficLight(id2); group2.addTrafficLight(id2); ScenarioFalse.addRuleGroup(0, group1); ScenarioFalse.addRuleGroup(1, group2); ScenarioFalse.setTransitionTime(5); } @Test public void testScenario() { assertEquals("OK",checker.checkScenario(ScenarioTrue)); assertEquals("All trafficLight green at same time",checker.checkScenario(ScenarioFalse)); } @Test public void testCheckAndSet() { assertEquals("The specified crossroad name doesn't exist : " + falseCrossroadName, checker.checkAndSetScenario(ScenarioTrue,falseCrossroadName)); } }
fix build errors
central/src/test/java/fr/unice/polytech/al/trafficlight/central/TestScenarioChecker.java
fix build errors
Java
mit
f586056b42f4d440cc40a81949bf8f8bcb305731
0
gmammolo/OpenDFA
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package opendfa.GUI; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import opendfa.DFA.Edge; import opendfa.DFA.Move; import opendfa.OpenDFA; /** * * @author terasud */ public class AddMoveGump extends javax.swing.JDialog { private OpenDFA dfa; private Edge edge; /** * Creates new form AddMoveGump */ public AddMoveGump(java.awt.Frame parent, boolean modal, OpenDFA dfa) { this(parent, modal, dfa, new Edge(0, 0, new ArrayList<Character>(Arrays.asList('a')), "a")); } /** * Creates new form AddMoveGump */ public AddMoveGump(java.awt.Frame parent, boolean modal, OpenDFA dfa, Edge e) { super(parent, modal); initComponents(); buttonGroup1.add(jRadioButton1); buttonGroup1.add(jRadioButton2); this.dfa = dfa; this.edge = e; startInput.setText(e.start.toString()); endInput.setText(e.end.toString()); arrayText.setText(e.label); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel2 = new javax.swing.JLabel(); endInput = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); startInput = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); singleText = new javax.swing.JTextField(); jRadioButton2 = new javax.swing.JRadioButton(); arrayText = new javax.swing.JTextField(); okButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Add New Transitions"); jLabel2.setText("Start"); endInput.setText("0"); jLabel3.setText("end"); startInput.setText("0"); startInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startInputActionPerformed(evt); } }); jLabel4.setText("=====[simboli]======>"); jRadioButton1.setText("Simbolo Singolo:"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); singleText.setText("a"); singleText.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { singleTextFocusGained(evt); } }); jRadioButton2.setText("Range di Simboli:"); arrayText.setText("a,b,c,d,s,r,e"); arrayText.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { arrayTextFocusGained(evt); } }); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); cancelButton.setText("CANCEL"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(startInput, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(endInput, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3))) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(cancelButton)) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(singleText, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(arrayText))))) .addGap(51, 51, 51)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(endInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(startInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton1) .addComponent(singleText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton2) .addComponent(arrayText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(77, 77, 77) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(okButton) .addComponent(cancelButton)) .addContainerGap(14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton1ActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed // TODO add your handling code here: Integer start = 0; try { start = Integer.parseInt(startInput.getText()); if (!dfa.isValidState(start)) { WarningError.generateWarningMessage("lo start deve essere uno stato valido!"); return; } } catch (NumberFormatException e) { WarningError.generateWarningMessage("lo start deve essere un'intero!"); return; } Integer end = 0; try { end = Integer.parseInt(endInput.getText()); if (!dfa.isValidState(end)) { WarningError.generateWarningMessage("l' end deve essere uno stato valido!"); return; } } catch (NumberFormatException e) { WarningError.generateWarningMessage("l'end deve essere un'intero!"); return; } if (jRadioButton1.isSelected()) { if (singleText.getText().length() != 1) { //TODO: verificare che sia un carattere valido WarningError.generateWarningMessage("deve contenere solo un carattere"); return; } else { Character c = singleText.getText().charAt(0); dfa.remove(edge.start, edge.alphabet); dfa.setMove(start, c, end); dispose(); } } else if (jRadioButton2.isSelected()) { String text = arrayText.getText(); if (text.length() == 0) { WarningError.generateWarningMessage("inserire almeno un carattere"); return; } else { ArrayList<Character> list = new ArrayList<>(); Pattern p = Pattern.compile("\\w-\\w"); Matcher m = p.matcher(arrayText.getText()); while (m.find()) { char _start = text.charAt(m.start()); char _end = text.charAt(m.end() - 1); char _index = _start; while (_index <= _end) { list.add(_index++); } } text = m.replaceAll(""); for (Character c : text.toCharArray()) { if (c != ' ' && c != ',') { list.add(c); } } dfa.remove(edge.start, edge.alphabet); dfa.setMove(start, list, end); dispose(); } } else { WarningError.generateWarningMessage("seleziona almeno un metodo di input per l'alfabeto"); } }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_cancelButtonActionPerformed private void singleTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_singleTextFocusGained jRadioButton1.setSelected(true); }//GEN-LAST:event_singleTextFocusGained private void arrayTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_arrayTextFocusGained jRadioButton2.setSelected(true); }//GEN-LAST:event_arrayTextFocusGained private void startInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_startInputActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, new OpenDFA(0)); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } public static void generateAddMoveGump(OpenDFA dfa) { /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, dfa); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } public static void generateAddMoveGump(OpenDFA dfa, int index) { /* Create and display the dialog */ Edge e = dfa.getEdgeAt(index); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, dfa, e); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField arrayText; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton cancelButton; private javax.swing.JTextField endInput; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JButton okButton; private javax.swing.JTextField singleText; private javax.swing.JTextField startInput; // End of variables declaration//GEN-END:variables }
src/opendfa/GUI/AddMoveGump.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package opendfa.GUI; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; import java.util.regex.Pattern; import opendfa.DFA.Edge; import opendfa.DFA.Move; import opendfa.OpenDFA; /** * * @author terasud */ public class AddMoveGump extends javax.swing.JDialog { private OpenDFA dfa; private Edge edge; /** * Creates new form AddMoveGump */ public AddMoveGump(java.awt.Frame parent, boolean modal, OpenDFA dfa) { this(parent, modal, dfa, new Edge(0, 0, new ArrayList<Character>(Arrays.asList('a')), "a")); } /** * Creates new form AddMoveGump */ public AddMoveGump(java.awt.Frame parent, boolean modal, OpenDFA dfa, Edge e) { super(parent, modal); initComponents(); buttonGroup1.add(jRadioButton1); buttonGroup1.add(jRadioButton2); this.dfa = dfa; this.edge = e; startInput.setText(e.start.toString()); endInput.setText(e.end.toString()); arrayText.setText(e.label); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel2 = new javax.swing.JLabel(); endInput = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); startInput = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); singleText = new javax.swing.JTextField(); jRadioButton2 = new javax.swing.JRadioButton(); arrayText = new javax.swing.JTextField(); okButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Add New Transitions"); jLabel2.setText("Start"); endInput.setText("0"); jLabel3.setText("end"); startInput.setText("0"); startInput.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startInputActionPerformed(evt); } }); jLabel4.setText("=====[simboli]======>"); jRadioButton1.setText("Simbolo Singolo:"); jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); singleText.setText("a"); singleText.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { singleTextFocusGained(evt); } }); jRadioButton2.setText("Range di Simboli:"); arrayText.setText("a,b,c,d,s,r,e"); arrayText.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { arrayTextFocusGained(evt); } }); okButton.setText("OK"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); cancelButton.setText("CANCEL"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(54, 54, 54) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(startInput, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(endInput, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3))) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(48, 48, 48) .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(cancelButton)) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(singleText, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(arrayText))))) .addGap(51, 51, 51)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(endInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(startInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton1) .addComponent(singleText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jRadioButton2) .addComponent(arrayText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(77, 77, 77) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(okButton) .addComponent(cancelButton)) .addContainerGap(14, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jRadioButton1ActionPerformed private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed // TODO add your handling code here: Integer start = 0; try { start = Integer.parseInt(startInput.getText()); if (!dfa.isValidState(start)) { WarningError.generateWarningMessage("lo start deve essere uno stato valido!"); return; } } catch (NumberFormatException e) { WarningError.generateWarningMessage("lo start deve essere un'intero!"); return; } Integer end = 0; try { end = Integer.parseInt(endInput.getText()); if (!dfa.isValidState(end)) { WarningError.generateWarningMessage("l' end deve essere uno stato valido!"); return; } } catch (NumberFormatException e) { WarningError.generateWarningMessage("l'end deve essere un'intero!"); return; } if (jRadioButton1.isSelected()) { if (singleText.getText().length() != 1) { //TODO: verificare che sia un carattere valido WarningError.generateWarningMessage("deve contenere solo un carattere"); return; } else { Character c = singleText.getText().charAt(0); dfa.remove(edge.start, edge.alphabet); dfa.setMove(start, c, end); dispose(); } } else if (jRadioButton2.isSelected()) { Pattern p = Pattern.compile("^(\\w(-\\w|,\\w)?)+$", Pattern.MULTILINE); Matcher m = p.matcher(arrayText.getText()); if (arrayText.getText().length() == 0 || !m.find()) { WarningError.generateWarningMessage("caratteri non validi"); return; } else { ArrayList<Character> list = new ArrayList<>(); for (Character c : arrayText.getText().toCharArray()) { if (c != ' ' && c != ',') { list.add(c); dfa.remove(edge.start, edge.alphabet); dfa.setMove(start, list, end); dispose(); } } } } else { WarningError.generateWarningMessage("seleziona almeno un metodo di input per l'alfabeto"); } }//GEN-LAST:event_okButtonActionPerformed private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed // TODO add your handling code here: dispose(); }//GEN-LAST:event_cancelButtonActionPerformed private void singleTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_singleTextFocusGained jRadioButton1.setSelected(true); }//GEN-LAST:event_singleTextFocusGained private void arrayTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_arrayTextFocusGained jRadioButton2.setSelected(true); }//GEN-LAST:event_arrayTextFocusGained private void startInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startInputActionPerformed // TODO add your handling code here: }//GEN-LAST:event_startInputActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AddMoveGump.class .getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, new OpenDFA(0)); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } public static void generateAddMoveGump(OpenDFA dfa) { /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, dfa); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } public static void generateAddMoveGump(OpenDFA dfa, int index) { /* Create and display the dialog */ Edge e = dfa.getEdgeAt(index); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { AddMoveGump dialog = new AddMoveGump(new javax.swing.JFrame(), true, dfa, e); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { dialog.dispose(); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField arrayText; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton cancelButton; private javax.swing.JTextField endInput; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JButton okButton; private javax.swing.JTextField singleText; private javax.swing.JTextField startInput; // End of variables declaration//GEN-END:variables }
-modifica transizioni
src/opendfa/GUI/AddMoveGump.java
-modifica transizioni
Java
mit
2743eeab870dc53adc838731b1a94bc88af6c21e
0
samarth-math/project-connect
package LogMaintainence; import globalfunctions.Contact; import java.io.*; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import GuiElements.ChatWindowPanelReceiver; import GuiElements.ChatWindowPanelSender; import serverclient.MainStart; public class GettingChatLogs extends Object{ @SuppressWarnings("unchecked") public static void readLog(String userId) { String chatFileName = userId+".json"; // file name based on userId String oldPathString = System.getProperty("user.dir"); String newPathString = oldPathString+"/chatlogs"; File newPath = new File(newPathString); File chatFilePath = new File(newPath,chatFileName); String myId = MainStart.myID; Contact person = MainStart.people.get(userId); //person needed to get the correct chat window long sessionTraversalCount = 0; JSONParser parser = new JSONParser(); if(chatFilePath.exists()) { try { Object obj = parser.parse(new FileReader(chatFilePath)); JSONObject logInfo = (JSONObject)obj; long sessionValue = (long)logInfo.get("lastUpdatedSession"); sessionTraversalCount = sessionValue; JSONObject oldSessionObject = (JSONObject)logInfo.get("session"); JSONArray oldMessageArray; int i=1; while(i<=sessionTraversalCount) { //System.out.println("session : "+i); oldMessageArray = (JSONArray)oldSessionObject.get(""+i); Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator(); while (oldMessageIterator.hasNext()) { JSONObject messageObject = (JSONObject)oldMessageIterator.next(); if(messageObject.get("userId").equals(myId)) { String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText")); ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString()); person.getWindow().chatconsole(cwsp); } else { String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText")); ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString()); person.getWindow().chatconsole(cwrp); } } System.out.println(); i++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } else { //System.out.println("No chats exist\n"); } } }
IPml/src/LogMaintainence/GettingChatLogs.java
package LogMaintainence; import globalfunctions.Contact; import java.io.*; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import GuiElements.ChatWindowPanelReceiver; import GuiElements.ChatWindowPanelSender; import serverclient.MainStart; public class GettingChatLogs extends Object{ @SuppressWarnings("unchecked") public static void readLog(String userId) { String chatFileName = userId+".json"; // file name based on userId String oldPathString = System.getProperty("user.dir"); String newPathString = oldPathString+"/chatlogs"; File newPath = new File(newPathString); File chatFilePath = new File(newPath,chatFileName); String myId = MainStart.myID; Contact person = MainStart.people.get(userId); //person needed to get the correct chat window long sessionTraversalCount = 0; JSONParser parser = new JSONParser(); if(chatFilePath.exists()) { try { Object obj = parser.parse(new FileReader(chatFilePath)); JSONObject logInfo = (JSONObject)obj; long sessionValue = (long)logInfo.get("lastUpdatedSession"); sessionTraversalCount = sessionValue; JSONObject oldSessionObject = (JSONObject)logInfo.get("session"); JSONArray oldMessageArray; int i=1; while(i<=sessionTraversalCount) { //System.out.println("session : "+i); oldMessageArray = (JSONArray)oldSessionObject.get(""+i); Iterator<JSONObject> oldMessageIterator = oldMessageArray.iterator(); while (oldMessageIterator.hasNext()) { JSONObject messageObject = (JSONObject)oldMessageIterator.next(); if(messageObject.get("userId").equals(myId)) { String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText")); ChatWindowPanelSender cwsp = new ChatWindowPanelSender(s1, messageObject.get("timeStamp").toString()); person.getWindow().chatconsole(cwsp); } else { String s1 = new String(messageObject.get("userName")+": "+messageObject.get("messageText")); ChatWindowPanelReceiver cwrp = new ChatWindowPanelReceiver(s1, messageObject.get("timeStamp").toString()); person.getWindow().chatconsole(cwrp); } } System.out.println(); i++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } else { System.out.println("No chats exist\n"); } } }
Minor change in GeetingChatLogs
IPml/src/LogMaintainence/GettingChatLogs.java
Minor change in GeetingChatLogs
Java
mit
30d364408ac6096708cdbe1d2cf145fae004a68a
0
DMDirc/DMDirc,DMDirc/DMDirc,csmith/DMDirc,greboid/DMDirc,greboid/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,DMDirc/DMDirc,DMDirc/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,csmith/DMDirc,csmith/DMDirc,greboid/DMDirc,csmith/DMDirc,ShaneMcC/DMDirc-Client
/* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package uk.org.ownage.dmdirc.ui.framemanager.tree; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Hashtable; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import uk.org.ownage.dmdirc.Channel; import uk.org.ownage.dmdirc.FrameContainer; import uk.org.ownage.dmdirc.Query; import uk.org.ownage.dmdirc.Raw; import uk.org.ownage.dmdirc.Server; import uk.org.ownage.dmdirc.logger.ErrorLevel; import uk.org.ownage.dmdirc.logger.Logger; import uk.org.ownage.dmdirc.ui.framemanager.FrameManager; /** * Manages open windows in the application in a tree style view */ public class TreeFrameManager implements FrameManager, TreeModelListener, TreeSelectionListener, TreeExpansionListener, TreeWillExpandListener, MouseListener, ActionListener { /** * display tree */ private JTree tree; /** * Scrollpane for the tree */ private JScrollPane scrollPane; /** * root node */ private DefaultMutableTreeNode root; /** * node renderer */ private TreeViewTreeCellRenderer renderer; /** * data model */ private DefaultTreeModel model; /** * node storage, used for adding and deleting nodes correctly */ private Hashtable<FrameContainer, DefaultMutableTreeNode> nodes; /** * stores colour associated with a node, cheap hack till i rewrite the model */ private Hashtable<FrameContainer, Color> nodeColours; /** * popup menu for menu items on nodes */ private JPopupMenu popup; /** * close menu item used in popup menus */ private JMenuItem closeMenuItem; /** * creates a new instance of the TreeFrameManager */ public TreeFrameManager() { nodes = new Hashtable<FrameContainer, DefaultMutableTreeNode>(); nodeColours = new Hashtable<FrameContainer, Color>(); popup = new JPopupMenu(); closeMenuItem = new JMenuItem("Close window"); closeMenuItem.addActionListener(this); root = new DefaultMutableTreeNode("DMDirc"); model = new DefaultTreeModel(root); tree = new JTree(model); tree.addMouseListener(this); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(this); renderer = new TreeViewTreeCellRenderer(); tree.setCellRenderer(renderer); tree.setRootVisible(false); tree.setBorder(new EmptyBorder(5, 5, 5, 5)); } /** * Indicates whether this frame manager can be positioned vertically * (i.e., at the side of the screen) * @return True iff the frame manager can be positioned vertically */ public boolean canPositionVertically() { return true; } /** * Indicates whether this frame manager can be positioned horizontally * (i.e., at the top or bottom of the screen) * @return True iff the frame manager can be positioned horizontally */ public boolean canPositionHorizontally() { return false; } /** * Shows an event notification to the user by colouring the corresponding * element to the source a specific colour * @param source The object requesting notification * @param colour The colour that should be used to indicate the notification */ public void showNotification(FrameContainer source, Color colour) { if (nodeColours != null) { nodeColours.put(source, colour); tree.invalidate(); } } public void clearNotification(FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { nodeColours.remove(source); } } public Color getNodeColour(FrameContainer source) { if (nodeColours != null && nodeColours.containsKey(source)) { return nodeColours.get(source); } return null; } /** * Sets the parent component in the main UI * @param parent parent component */ public void setParent(JComponent parent) { scrollPane = new JScrollPane(tree); parent.setLayout(new BorderLayout()); parent.add(scrollPane); parent.setPreferredSize(new Dimension(150, Integer.MAX_VALUE)); parent.setMinimumSize(new Dimension(150, Integer.MAX_VALUE)); tree.setBackground(parent.getBackground()); tree.setForeground(parent.getForeground()); tree.setVisible(true); parent.setVisible(true); } /** * adds a server to the tree * @param server associated server */ public void addServer(Server server) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(server, node); node.setUserObject(server); model.insertNodeInto(node, (MutableTreeNode)root, root.getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * removes a server from the tree * @param server associated server */ public void delServer(Server server) { model.removeNodeFromParent(nodes.get(server)); } /** * adds a channel to the tree * @param server associated server * @param channel associated framecontainer */ public void addChannel(Server server, Channel channel) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(channel, node); node.setUserObject(channel); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a channel from the tree * @param server associated server * @param channel associated framecontainer */ public void delChannel(Server server, Channel channel) { model.removeNodeFromParent(nodes.get(channel)); } /** * adds a query to the tree * @param server associated server * @param query associated framecontainer */ public void addQuery(Server server, Query query) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(query, node); node.setUserObject(query); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a query from the tree * @param server associated server * @param query associated framecontainer */ public void delQuery(Server server, Query query) { model.removeNodeFromParent(nodes.get(query)); } /** * adds a raw to the tree * @param server associated server * @param raw associated framecontainer */ public void addRaw(Server server, Raw raw) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(raw, node); node.setUserObject(raw); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a raw from the tree * @param server associated server * @param raw associated framecontainer */ public void delRaw(Server server, Raw raw) { model.removeNodeFromParent(nodes.get(raw)); } /** * valled whenever the value of the selection changes * @param e selection event */ public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof FrameContainer) { ((FrameContainer)nodeInfo).activateFrame(); } else { Logger.error(ErrorLevel.WARNING, "Unknown node type."); } } /** * Called after the tree has been expanded * @param event expansion event */ public void treeExpanded(TreeExpansionEvent event) { } /** * Called after the tree has been collapsed * @param event expansion event */ public void treeCollapsed(TreeExpansionEvent event) { } /** * Called when the tree is about to expand * @param event expansion event * @throws javax.swing.tree.ExpandVetoException thrown to prevent node expanding */ public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { } /** * Called when the tree is about to collapse * @param event expansion event * @throws javax.swing.tree.ExpandVetoException throw to prevent node collapsing */ public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { } /** * called after a node, or set of nodes, changes * @param e change event */ public void treeNodesChanged(TreeModelEvent e) { } /** * called after a node has been inserted into the tree * @param e change event */ public void treeNodesInserted(TreeModelEvent e) { } /** * Called when a node is removed from the tree * @param e change event */ public void treeNodesRemoved(TreeModelEvent e) { } /** * Called when a tree changes structure * @param e change event */ public void treeStructureChanged(TreeModelEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void actionPerformed(ActionEvent e) { } }
src/uk/org/ownage/dmdirc/ui/framemanager/tree/TreeFrameManager.java
/* * Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package uk.org.ownage.dmdirc.ui.framemanager.tree; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Hashtable; import javax.swing.JComponent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.MutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import uk.org.ownage.dmdirc.Channel; import uk.org.ownage.dmdirc.FrameContainer; import uk.org.ownage.dmdirc.Query; import uk.org.ownage.dmdirc.Raw; import uk.org.ownage.dmdirc.Server; import uk.org.ownage.dmdirc.logger.ErrorLevel; import uk.org.ownage.dmdirc.logger.Logger; import uk.org.ownage.dmdirc.ui.framemanager.FrameManager; /** * Manages open windows in the application in a tree style view */ public class TreeFrameManager implements FrameManager, TreeModelListener, TreeSelectionListener, TreeExpansionListener, TreeWillExpandListener, MouseListener, ActionListener { /** * display tree */ private JTree tree; /** * Scrollpane for the tree */ private JScrollPane scrollPane; /** * root node */ private DefaultMutableTreeNode root; /** * node renderer */ private TreeViewTreeCellRenderer renderer; /** * data model */ private DefaultTreeModel model; /** * node storage, used for adding and deleting nodes correctly */ private Hashtable<FrameContainer, DefaultMutableTreeNode> nodes; /** * stores colour associated with a node, cheap hack till i rewrite the model */ private Hashtable<FrameContainer, Color> nodeColours; /** * popup menu for menu items on nodes */ private JPopupMenu popup; /** * close menu item used in popup menus */ private JMenuItem closeMenuItem; /** * creates a new instance of the TreeFrameManager */ public TreeFrameManager() { nodes = new Hashtable<FrameContainer, DefaultMutableTreeNode>(); nodeColours = new Hashtable<FrameContainer, Color>(); popup = new JPopupMenu(); closeMenuItem = new JMenuItem("Close window"); closeMenuItem.addActionListener(this); root = new DefaultMutableTreeNode("DMDirc"); model = new DefaultTreeModel(root); tree = new JTree(model); tree.addMouseListener(this); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); tree.addTreeSelectionListener(this); renderer = new TreeViewTreeCellRenderer(); tree.setCellRenderer(renderer); tree.setRootVisible(false); tree.setBorder(new EmptyBorder(5, 5, 5, 5)); } /** * Indicates whether this frame manager can be positioned vertically * (i.e., at the side of the screen) * @return True iff the frame manager can be positioned vertically */ public boolean canPositionVertically() { return true; } /** * Indicates whether this frame manager can be positioned horizontally * (i.e., at the top or bottom of the screen) * @return True iff the frame manager can be positioned horizontally */ public boolean canPositionHorizontally() { return false; } /** * Shows an event notification to the user by colouring the corresponding * element to the source a specific colour * @param source The object requesting notification * @param colour The colour that should be used to indicate the notification */ public void showNotification(FrameContainer source, Color colour) { if (nodeColours != null) { nodeColours.put(source, colour); tree.revalidate(); } } public void clearNotification(FrameContainer source) { if (nodeColours != null && nodeColours.contains(source)) { nodeColours.remove(source); } } public Color getNodeColour(FrameContainer source) { if (nodeColours != null && nodeColours.contains(source)) { return nodeColours.get(source); } return null; } /** * Sets the parent component in the main UI * @param parent parent component */ public void setParent(JComponent parent) { scrollPane = new JScrollPane(tree); parent.setLayout(new BorderLayout()); parent.add(scrollPane); parent.setPreferredSize(new Dimension(150, Integer.MAX_VALUE)); parent.setMinimumSize(new Dimension(150, Integer.MAX_VALUE)); tree.setBackground(parent.getBackground()); tree.setForeground(parent.getForeground()); tree.setVisible(true); parent.setVisible(true); } /** * adds a server to the tree * @param server associated server */ public void addServer(Server server) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(server, node); node.setUserObject(server); model.insertNodeInto(node, (MutableTreeNode)root, root.getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * removes a server from the tree * @param server associated server */ public void delServer(Server server) { model.removeNodeFromParent(nodes.get(server)); } /** * adds a channel to the tree * @param server associated server * @param channel associated framecontainer */ public void addChannel(Server server, Channel channel) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(channel, node); node.setUserObject(channel); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a channel from the tree * @param server associated server * @param channel associated framecontainer */ public void delChannel(Server server, Channel channel) { model.removeNodeFromParent(nodes.get(channel)); } /** * adds a query to the tree * @param server associated server * @param query associated framecontainer */ public void addQuery(Server server, Query query) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(query, node); node.setUserObject(query); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a query from the tree * @param server associated server * @param query associated framecontainer */ public void delQuery(Server server, Query query) { model.removeNodeFromParent(nodes.get(query)); } /** * adds a raw to the tree * @param server associated server * @param raw associated framecontainer */ public void addRaw(Server server, Raw raw) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); nodes.put(raw, node); node.setUserObject(raw); model.insertNodeInto(node, (MutableTreeNode)nodes.get(server), nodes.get(server).getChildCount()); tree.scrollPathToVisible(new TreePath(node.getPath())); } /** * deletes a raw from the tree * @param server associated server * @param raw associated framecontainer */ public void delRaw(Server server, Raw raw) { model.removeNodeFromParent(nodes.get(raw)); } /** * valled whenever the value of the selection changes * @param e selection event */ public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); if (nodeInfo instanceof FrameContainer) { ((FrameContainer)nodeInfo).activateFrame(); } else { Logger.error(ErrorLevel.WARNING, "Unknown node type."); } } /** * Called after the tree has been expanded * @param event expansion event */ public void treeExpanded(TreeExpansionEvent event) { } /** * Called after the tree has been collapsed * @param event expansion event */ public void treeCollapsed(TreeExpansionEvent event) { } /** * Called when the tree is about to expand * @param event expansion event * @throws javax.swing.tree.ExpandVetoException thrown to prevent node expanding */ public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { } /** * Called when the tree is about to collapse * @param event expansion event * @throws javax.swing.tree.ExpandVetoException throw to prevent node collapsing */ public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { } /** * called after a node, or set of nodes, changes * @param e change event */ public void treeNodesChanged(TreeModelEvent e) { } /** * called after a node has been inserted into the tree * @param e change event */ public void treeNodesInserted(TreeModelEvent e) { } /** * Called when a node is removed from the tree * @param e change event */ public void treeNodesRemoved(TreeModelEvent e) { } /** * Called when a tree changes structure * @param e change event */ public void treeStructureChanged(TreeModelEvent e) { } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void actionPerformed(ActionEvent e) { } }
Fixed notifications in the treeframe (contains() != containsKey()!) git-svn-id: 50f83ef66c13f323b544ac924010c921a9f4a0f7@343 00569f92-eb28-0410-84fd-f71c24880f43
src/uk/org/ownage/dmdirc/ui/framemanager/tree/TreeFrameManager.java
Fixed notifications in the treeframe (contains() != containsKey()!)
Java
mit
e8d86f2fc2f7cf181a9f86bddf4af1867b8b0145
0
danbuckland/okrello,danbuckland/okrello
package com.blocksolid.okrello; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.blocksolid.okrello.api.ServiceGenerator; import com.blocksolid.okrello.api.TrelloApi; import com.blocksolid.okrello.model.TrelloCard; import com.blocksolid.okrello.model.TrelloCheckItem; import com.blocksolid.okrello.model.TrelloChecklist; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Dan Buckland on 06/12/2015. */ public class KeyResultsActivity extends AppCompatActivity { public static TrelloApi trelloApi; public static ArrayList<TrelloCheckItem> keyResults; public static TrelloCard trelloCard; public static ListView listView; public static ProgressBar keyresProgressBar; public String cardId; public String objective; public String checklistId; KeyResultAdapter keyResultAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_key_results); getSupportActionBar().setDisplayHomeAsUpEnabled(true); trelloApi = ServiceGenerator.createService(TrelloApi.class); // Set Activity title to the selected list name objective = this.getIntent().getExtras().getString("objective"); checklistId = this.getIntent().getExtras().getString("checklistId"); setTitle(objective); keyresProgressBar = (ProgressBar) findViewById(R.id.keyres_progress); keyresProgressBar.setVisibility(View.INVISIBLE); listView = (ListView) findViewById(R.id.keyres_list_key_results); cardId = this.getIntent().getExtras().getString("cardId"); keyResultAdapter = new KeyResultAdapter(this, getLayoutInflater()); listView.setAdapter(keyResultAdapter); trelloCard = new TrelloCard(); getKeyResults(); } private void getKeyResults() { // Show progress indicator while working keyresProgressBar.setVisibility(View.VISIBLE); // Define the request String fields = "name"; final Call<ArrayList<TrelloChecklist>> call = trelloApi.getChecklists(cardId, TrelloApi.KEY, fields); // Make the request call.enqueue(new Callback<ArrayList<TrelloChecklist>>() { @Override public void onResponse(Call<ArrayList<TrelloChecklist>> cardCall, Response<ArrayList<TrelloChecklist>> response) { trelloCard.setChecklists(response.body()); // Populate an ArrayList of checkItems called keyResults keyResults = getKeyResultsCheckitems(trelloCard); // Update data in custom view adapter keyResultAdapter.updateData(keyResults); // Hide progress indicator when done keyresProgressBar.setVisibility(View.INVISIBLE); } @Override public void onFailure(Call<ArrayList<TrelloChecklist>> cardCall, Throwable t) { // Log error here since request failed Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); Log.d("Retrofit", t.getMessage()); keyresProgressBar.setVisibility(View.INVISIBLE); } }); } public ArrayList<TrelloCheckItem> getKeyResultsCheckitems(TrelloCard trelloCard) { // Initialise keyResults ArrayList as null to be returned if there are no keyResults ArrayList<TrelloCheckItem> keyResults = null; int position = trelloCard.getKeyResultsChecklistPosition(); if (position >= 0) { // If a suitable Key Results checklist is found // Get checkItems to use as Key Results from that checklist keyResults = trelloCard.getChecklists().get(position).getTrelloCheckItems(); } return keyResults; } }
app/src/main/java/com/blocksolid/okrello/KeyResultsActivity.java
package com.blocksolid.okrello; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.Toast; import com.blocksolid.okrello.api.ServiceGenerator; import com.blocksolid.okrello.api.TrelloApi; import com.blocksolid.okrello.model.TrelloCard; import com.blocksolid.okrello.model.TrelloCheckItem; import com.blocksolid.okrello.model.TrelloChecklist; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Dan Buckland on 06/12/2015. */ public class KeyResultsActivity extends AppCompatActivity { public static TrelloApi trelloApi; public static ArrayList<TrelloChecklist> trelloChecklists; public static ArrayList<TrelloCheckItem> keyResults; public static TrelloCard trelloCard; public static ListView listView; public static ProgressBar keyresProgressBar; public String cardId; public String objective; public String checklistId; KeyResultAdapter keyResultAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_key_results); getSupportActionBar().setDisplayHomeAsUpEnabled(true); trelloApi = ServiceGenerator.createService(TrelloApi.class); // Set Activity title to the selected list name objective = this.getIntent().getExtras().getString("objective"); checklistId = this.getIntent().getExtras().getString("checklistId"); setTitle(objective); keyresProgressBar = (ProgressBar) findViewById(R.id.keyres_progress); keyresProgressBar.setVisibility(View.INVISIBLE); listView = (ListView) findViewById(R.id.keyres_list_key_results); cardId = this.getIntent().getExtras().getString("cardId"); keyResultAdapter = new KeyResultAdapter(this, getLayoutInflater()); listView.setAdapter(keyResultAdapter); getKeyResults(); } private void getKeyResults() { // Show progress indicator while working keyresProgressBar.setVisibility(View.VISIBLE); // Define the request String fields = "name"; final Call<ArrayList<TrelloChecklist>> call = trelloApi.getChecklists(cardId, TrelloApi.KEY, fields); // Make the request call.enqueue(new Callback<ArrayList<TrelloChecklist>>() { @Override public void onResponse(Call<ArrayList<TrelloChecklist>> cardCall, Response<ArrayList<TrelloChecklist>> response) { trelloChecklists = response.body(); // Update data in custom view adapter // TODO decide which checklist is the correct one to use // TODO extract this method out to somewhere else - not sure where // Populate an ArrayList of checkItems called keyResults keyResults = getKeyResultsCheckitems(trelloChecklists); // Update data in custom view adapter keyResultAdapter.updateData(keyResults); // Hide progress indicator when done keyresProgressBar.setVisibility(View.INVISIBLE); } @Override public void onFailure(Call<ArrayList<TrelloChecklist>> cardCall, Throwable t) { // Log error here since request failed Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show(); Log.d("Retrofit", t.getMessage()); keyresProgressBar.setVisibility(View.INVISIBLE); } }); } public ArrayList<TrelloCheckItem> getKeyResultsCheckitems(ArrayList<TrelloChecklist> trelloChecklists) { ArrayList<TrelloCheckItem> keyResults = null; int position = getKeyResultsChecklistPosition(trelloChecklists); if (position >= 0) { keyResults = trelloChecklists.get(position).getTrelloCheckItems(); } return keyResults; } public int getKeyResultsChecklistPosition(ArrayList<TrelloChecklist> trelloChecklists) { if (trelloChecklists.size() == 1) { // If there's only one checklist, use that checklist as Key Results return 0; } else if (trelloChecklists.size() > 1) { // When card has more than one checklist belonging to a card // only checkItems belonging to the checklist called "Key Results" are displayed. for (int i = 0; i < trelloChecklists.size(); i++) { String checklistName = trelloChecklists.get(i).getName(); if (checklistName.equals("Key Results")) { return i; } } } // When there is no checklist called "Key Results" belonging to a card with // multiple checklists, then no Key Results are displayed. return -1; } }
Use correct getKeyResultsChecklistPosition method
app/src/main/java/com/blocksolid/okrello/KeyResultsActivity.java
Use correct getKeyResultsChecklistPosition method
Java
mit
57c30d1c407d76e5c3f12cf9ded9f9651a93f7b0
0
hockeyhurd/HCoreLib
package com.hockeyhurd.api.math.pathfinding; import com.hockeyhurd.api.math.Vector3; import net.minecraft.world.World; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import static com.hockeyhurd.api.math.pathfinding.PathUtils.distanceTo; /** * General purpose A* Algorithm implementation. * * @author hockeyhurd * @version 1/25/2016. */ public class AStarAlogirthm { protected IPathTile startTile, endTile; protected IPathTile[] pathTiles; protected double distanceLeft; protected boolean useDiagonals; protected Comparator<PathNode> tileSorter = new Comparator<PathNode>() { @Override public int compare(PathNode tile, PathNode other) { final Vector3<Integer> endVec = endTile.worldVec(); double tileHCost = tile.tile.distanceTo(endVec); double otherHCost = other.tile.distanceTo(endVec); double tileFCost = tile.gCost + tileHCost; double otherFCost = other.gCost + otherHCost; return otherFCost < tileFCost ? 1 : otherFCost > tileFCost ? -1 : 0; } }; /** * @param startTile IPathTile start. * @param endTile IPathTile end. */ public AStarAlogirthm(IPathTile startTile, IPathTile endTile) { this.startTile = startTile; this.endTile = endTile; // pathTiles = new LinkedList<IPathTile>(); distanceLeft = distanceTo(startTile, endTile); this.useDiagonals = false; } /** * Finds and returns a path if available. * * @param world World to reference. * @return List of path tiles to follow if found, else may return NULL! */ public IPathTile[] findPath(World world) { List<PathNode> openList = new LinkedList<PathNode>(); List<PathNode> closedList = new LinkedList<PathNode>(); PathNode current = new PathNode(startTile, null, startTile.getCost(), 0.0d); PathNode node; // final Vector3<Integer> startVec = startTile.worldVec(); final Vector3<Integer> endVec = endTile.worldVec(); openList.add(current); while (!openList.isEmpty()) { Collections.sort(openList, tileSorter); current = openList.get(0); if (current.vec.equals(endVec)) { List<IPathTile> path = new LinkedList<IPathTile>(); // while (current.parent != null) { while (current.hasParentNode()) { path.add(current.tile); current = current.parent; } // PathUtils.toArray(path, pathTiles); pathTiles = path.toArray(new IPathTile[path.size()]); // openList.clear(); // closedList.clear(); return pathTiles; } openList.remove(current); closedList.add(current); IPathTile[] adjacents = PathUtils.getAdjacentTiles(world, current.tile, useDiagonals); for (int i = 0; i < adjacents.length; i++) { IPathTile at = adjacents[i]; if (at.isSolid()) continue; Vector3<Integer> atVec = at.worldVec(); // double gCost = current.gCost + current.tile.distanceTo(atVec); double gCost = current.gCost + PathUtils.distanceTo(current.tile, at); // double hCost = atVec.getNetDifference(endVec); double hCost = PathUtils.distanceTo(at, endTile); node = new PathNode(at, current, gCost, hCost); if (contains(closedList, atVec) && gCost >= node.gCost) continue; if (!contains(openList, atVec) || gCost < node.gCost) openList.add(node); } } // closedList.clear(); return null; } /** * Gets the last calculated path. * * @return IPathTile[]. */ public IPathTile[] getLastPath() { return pathTiles != null ? pathTiles : new IPathTile[0]; } /** * Checks if vector is in PathNode list. * * @param list List to check. * @param search Vector3 to search for. * @return boolean result. */ protected boolean contains(List<PathNode> list, Vector3<Integer> search) { if (list == null || list.isEmpty() || search == null) return false; for (PathNode node : list) { if (search.equals(node.vec)) return true; } return false; } }
com/hockeyhurd/api/math/pathfinding/AStarAlogirthm.java
package com.hockeyhurd.api.math.pathfinding; import com.hockeyhurd.api.math.Vector3; import net.minecraft.world.World; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import static com.hockeyhurd.api.math.pathfinding.PathUtils.distanceTo; /** * General purpose A* Algorithm implementation. * * @author hockeyhurd * @version 1/25/2016. */ public class AStarAlogirthm { protected IPathTile startTile, endTile; protected IPathTile[] pathTiles; protected double distanceLeft; protected boolean useDiagonals; protected Comparator<PathNode> tileSorter = new Comparator<PathNode>() { @Override public int compare(PathNode tile, PathNode other) { final Vector3<Integer> endVec = endTile.worldVec(); double tileHCost = tile.tile.distanceTo(endVec); double otherHCost = other.tile.distanceTo(endVec); double tileFCost = tile.gCost + tileHCost; double otherFCost = other.gCost + otherHCost; return otherFCost < tileFCost ? 1 : otherFCost > tileFCost ? -1 : 0; } }; /** * @param startTile IPathTile start. * @param endTile IPathTile end. */ public AStarAlogirthm(IPathTile startTile, IPathTile endTile) { this.startTile = startTile; this.endTile = endTile; // pathTiles = new LinkedList<IPathTile>(); distanceLeft = distanceTo(startTile, endTile); this.useDiagonals = false; } /** * Finds and returns a path if available. * * @param world World to reference. * @return List of path tiles to follow if found, else may return NULL! */ public IPathTile[] findPath(World world) { List<PathNode> openList = new LinkedList<PathNode>(); List<PathNode> closedList = new LinkedList<PathNode>(); PathNode current = new PathNode(startTile, null, startTile.getCost(), 0.0d); PathNode node; // final Vector3<Integer> startVec = startTile.worldVec(); final Vector3<Integer> endVec = endTile.worldVec(); openList.add(current); while (!openList.isEmpty()) { Collections.sort(openList, tileSorter); current = openList.get(0); if (current.vec.equals(endVec)) { List<IPathTile> path = new LinkedList<IPathTile>(); // while (current.parent != null) { while (current.hasParentNode()) { path.add(current.tile); current = current.parent; } PathUtils.toArray(path, pathTiles); // openList.clear(); // closedList.clear(); return pathTiles; } openList.remove(current); closedList.add(current); IPathTile[] adjacents = PathUtils.getAdjacentTiles(world, current.tile, useDiagonals); for (int i = 0; i < adjacents.length; i++) { IPathTile at = adjacents[i]; if (at.isSolid()) continue; Vector3<Integer> atVec = at.worldVec(); // double gCost = current.gCost + current.tile.distanceTo(atVec); double gCost = current.gCost + PathUtils.distanceTo(current.tile, at); // double hCost = atVec.getNetDifference(endVec); double hCost = PathUtils.distanceTo(at, endTile); node = new PathNode(at, current, gCost, hCost); if (contains(closedList, atVec) && gCost >= node.gCost) continue; if (!contains(openList, atVec) || gCost < node.gCost) openList.add(node); } } closedList.clear(); return null; } /** * Gets the last calculated path. * * @return IPathTile[]. */ public IPathTile[] getLastPath() { return pathTiles != null ? pathTiles : new IPathTile[0]; } /** * Checks if vector is in PathNode list. * * @param list List to check. * @param search Vector3 to search for. * @return boolean result. */ protected boolean contains(List<PathNode> list, Vector3<Integer> search) { if (list == null || list.isEmpty() || search == null) return false; for (PathNode node : list) { if (search.equals(node.vec)) return true; } return false; } }
- Quick fix for A* path finding.
com/hockeyhurd/api/math/pathfinding/AStarAlogirthm.java
- Quick fix for A* path finding.
Java
mit
d8b67b9835baf1543665dc38b25747d38057f03d
0
kirapoetica974/projet_HADL
package M1.Systeme_Simple_CS.Composant_Serveur; import M2.Objet_Architectural.Configuration.PackageComposant.Composant; public class Serveur extends Composant { }
projetHadl/src/M1/Systeme_Simple_CS/Composant_Serveur/Serveur.java
package M1.Systeme_Simple_CS.Composant_Serveur; public class Serveur { }
ajout serveur
projetHadl/src/M1/Systeme_Simple_CS/Composant_Serveur/Serveur.java
ajout serveur
Java
epl-1.0
5e95029a50dc3b4c8a1c6075e5701d10f7c9df74
0
ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio
/******************************************************************************* * Copyright (c) 2014 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.swt.rtplot.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.logging.Level; import org.csstudio.swt.rtplot.Activator; import org.csstudio.swt.rtplot.Axis; import org.csstudio.swt.rtplot.AxisRange; import org.csstudio.swt.rtplot.Messages; import org.csstudio.swt.rtplot.Trace; import org.csstudio.swt.rtplot.data.PlotDataItem; import org.csstudio.swt.rtplot.data.PlotDataProvider; import org.csstudio.swt.rtplot.data.PlotDataSearch; import org.csstudio.swt.rtplot.data.ValueRange; import org.csstudio.swt.rtplot.internal.util.Log10; import org.csstudio.swt.rtplot.undo.AddAnnotationAction; import org.csstudio.swt.rtplot.undo.ChangeAxisRanges; import org.eclipse.swt.graphics.Point; /** Helper for processing traces of a plot * in a thread pool to avoid blocking UI thread. * @param <XTYPE> Data type of horizontal {@link Axis} * @author Kay Kasemir */ @SuppressWarnings("nls") public class PlotProcessor<XTYPE extends Comparable<XTYPE>> { final private static ExecutorService thread_pool = Executors.newWorkStealingPool(); final private Plot<XTYPE> plot; /** @param plot Plot on which this processor operates */ public PlotProcessor(final Plot<XTYPE> plot) { this.plot = plot; } /** Submit background job to determine value range for y axis for values within the * specified x axis. * @param data {@link PlotDataProvider} with values * @param x_range {@link AxisRange} covering visible part of plot * @return {@link Future} to {@link ValueRange} */ public Future<ValueRange> determineValueRange(final PlotDataProvider<XTYPE> data, final AxisRange<XTYPE> x_range) { return thread_pool.submit(new Callable<ValueRange>() { @Override public ValueRange call() throws Exception { double low = Double.MAX_VALUE; double high = -Double.MAX_VALUE; final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); data.getLock().lock(); try { if (data.size() > 0) { // Consider first sample at-or-before start int start = search.findSampleLessOrEqual(data, x_range.getLow()); if (start < 0) start = 0; // Last sample is the one just inside end of range. int stop = search.findSampleLessOrEqual(data, x_range.getHigh()); if (stop < 0) stop = 0; // If data is completely outside the x_range, // we end up using just data[0] // Check [start .. stop], including stop for (int i=start; i<=stop; ++i) { final PlotDataItem<XTYPE> item = data.get(i); final double value = item.getValue(); if (! Double.isFinite(value)) continue; if (value < low) low = value; if (value > high) high = value; } } } finally { data.getLock().unlock(); } return new ValueRange(low, high); } }); } /** Submit background job to determine value range * @param axis {@link YAxisImpl} for which to determine range * @param x_axis {@link AxisRange} over which range is to be determined * @return {@link Future} to {@link ValueRange} */ public Future<ValueRange> determineValueRange(final YAxisImpl<XTYPE> axis, final AxisPart<XTYPE> x_axis) { return thread_pool.submit(new Callable<ValueRange>() { @Override public ValueRange call() throws Exception { // In parallel, determine range of all traces in this axis final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (Trace<XTYPE> trace : axis.getTraces()) ranges.add(determineValueRange(trace.getData(), x_axis.getValueRange())); // Merge the trace ranges into overall axis range double low = Double.MAX_VALUE; double high = -Double.MAX_VALUE; for (Future<ValueRange> result : ranges) { final ValueRange range = result.get(); if (range.getLow() < low) low = range.getLow(); if (range.getHigh() > high) high = range.getHigh(); } return new ValueRange(low, high); } }); } /** Round value range up/down to add a little room above & below the exact range. * This results in "locking" to a nice looking range for a while * until a new sample outside of the rounded range is added. * * @param low Low and * @param high high end of value range * @return Adjusted range */ public ValueRange roundValueRange(final double low, final double high) { final double size = Math.abs(high-low); if (size > 0) { // Add 2 digits to the 'tight' order of magnitude final double order_of_magnitude = Math.floor(Log10.log10(size))-2; final double round = Math.pow(10, order_of_magnitude); return new ValueRange(Math.floor(low / round) * round, Math.ceil(high / round) * round); } else return new ValueRange(low, high); } /** Stagger the range of axes */ public void stagger() { thread_pool.execute(() -> { final double GAP = 0.1; // Arrange all axes so they don't overlap by assigning 1/Nth of // the vertical range to each one // Determine range of each axes' traces in parallel final List<YAxisImpl<XTYPE>> y_axes = new ArrayList<>(); final List<AxisRange<Double>> original_ranges = new ArrayList<>(); final List<AxisRange<Double>> new_ranges = new ArrayList<>(); final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) { y_axes.add(axis); // As fallback, assume that new range matches old range new_ranges.add(axis.getValueRange()); original_ranges.add(axis.getValueRange()); ranges.add(determineValueRange(axis, plot.getXAxis())); } final int N = y_axes.size(); for (int i=0; i<N; ++i) { final YAxisImpl<XTYPE> axis = y_axes.get(i); // Does axis handle itself in another way? if (axis.isAutoscale()) continue; // Fetch range of values on this axis final ValueRange axis_range; try { axis_range = ranges.get(i).get(); } catch (Exception ex) { Activator.getLogger().log(Level.WARNING, "Axis stagger error", ex); continue; } // Skip axis which for some reason cannot determine its range double low = axis_range.getLow(); double high = axis_range.getHigh(); if (low > high) continue; if (low == high) { // Center trace with constant value (empty range) final double half = Math.abs(low/2); low -= half; high += half; } if (axis.isLogarithmic()) { // Transition into log space low = Log10.log10(low); high = Log10.log10(high); } double span = high - low; // Make some extra space low -= GAP*span; high += GAP*span; span = high-low; // With N axes, assign 1/Nth of the vertical plot space to this axis // by shifting the span down according to the axis index, // using a total of N*range. low -= (N-i-1)*span; high += i*span; final ValueRange rounded = roundValueRange(low, high); low = rounded.getLow(); high = rounded.getHigh(); if (axis.isLogarithmic()) { // Revert from log space low = Log10.pow10(low); high = Log10.pow10(high); } // Sanity check for empty traces if (low < high && !Double.isInfinite(low) && !Double.isInfinite(high)) new_ranges.set(i, new AxisRange<Double>(low, high)); } // 'Stagger' tends to be on-demand, // or executed infrequently as archived data arrives after a zoom operation // -> Use undo, which also notifies listeners plot.getUndoableActionManager().execute(new ChangeAxisRanges<>(plot, Messages.Zoom_Stagger, y_axes, original_ranges, new_ranges)); }); } /** Compute cursor values for the various traces * * <p>Updates the 'selected' sample for each trace, * and sends valid {@link CursorMarker}s to the {@link Plot} * * @param cursor_x Pixel location of cursor * @param location Corresponding position on X axis * @param callback Will be called with markers for the cursor location */ public void updateCursorMarkers(final int cursor_x, final XTYPE location, final Consumer<List<CursorMarker>> callback) { // Run in thread thread_pool.execute(() -> { final List<CursorMarker> markers = new ArrayList<>(); final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) for (TraceImpl<XTYPE> trace : axis.getTraces()) { final PlotDataProvider<XTYPE> data = trace.getData(); final PlotDataItem<XTYPE> sample; data.getLock().lock(); try { final int index = search.findSampleLessOrEqual(data, location); sample = index >= 0 ? data.get(index) : null; } finally { data.getLock().unlock(); } trace.selectSample(sample); if (sample == null) continue; final double value = sample.getValue(); if (Double.isFinite(value) && axis.getValueRange().contains(value)) { String label = axis.getTicks().formatDetailed(value); final String units = trace.getUnits(); if (! units.isEmpty()) label += " " + units; String info = sample.getInfo(); if (info != null) { if (info.contains("(")) { // Must be an enum with labels saved in info String[] splt = info.split("\t"); if (splt.length > 1) { String enumVal = splt[1]; label += " " + enumVal; } } } markers.add(new CursorMarker(cursor_x, axis.getScreenCoord(value), trace.getColor(), label)); } } Collections.sort(markers); callback.accept(markers); }); } /** @param plot Plot where annotation is added * @param trace Trace to which a annotation should be added * @param text Text for the annotation */ public void createAnnotation(final Trace<XTYPE> trace, final String text) { final AxisPart<XTYPE> x_axis = plot.getXAxis(); // Run in thread thread_pool.execute(() -> { final AxisRange<Integer> range = x_axis.getScreenRange(); XTYPE location = x_axis.getValue((range.getLow() + range.getHigh())/2); final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); final PlotDataProvider<XTYPE> data = trace.getData(); double value= Double.NaN; data.getLock().lock(); try { final int index = search.findSampleGreaterOrEqual(data, location); if (index >= 0) { location = data.get(index).getPosition(); value = data.get(index).getValue(); } else location = null; } finally { data.getLock().unlock(); } if (location != null) plot.getUndoableActionManager().execute( new AddAnnotationAction<XTYPE>(plot, new AnnotationImpl<XTYPE>(false, trace, location, value, new Point(20, -20), text))); }); } public void updateAnnotation(final AnnotationImpl<XTYPE> annotation, final XTYPE location) { // Run in thread thread_pool.execute(() -> { final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); final PlotDataProvider<XTYPE> data = annotation.getTrace().getData(); XTYPE position; double value; data.getLock().lock(); try { final int index = search.findSampleLessOrEqual(data, location); if (index < 0) return; position = data.get(index).getPosition(); value = data.get(index).getValue(); } finally { data.getLock().unlock(); } plot.updateAnnotation(annotation, position, value, annotation.getOffset()); }); } /** * Perform autoscale for all axes that are marked as such. * Autoscale only for the data that is visible on the plot. */ public void autoscale() { // Determine range of each axes' traces in parallel final List<YAxisImpl<XTYPE>> y_axes = new ArrayList<>(); final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) if (axis.isAutoscale()) { y_axes.add(axis); ranges.add(determineValueRange(axis, plot.getXAxis())); } final int N = y_axes.size(); for (int i=0; i<N; ++i) { final YAxisImpl<XTYPE> axis = y_axes.get(i); try { final ValueRange new_range = ranges.get(i).get(); double low = new_range.getLow(), high = new_range.getHigh(); if (low > high) continue; if (low == high) { // Center trace with constant value (empty range) final double half = Math.abs(low/2); low -= half; high += half; } if (axis.isLogarithmic()) { // Perform adjustment in log space. // But first, refuse to deal with <= 0 if (low <= 0.0) low = 1; if (high <= low) high = 100; low = Log10.log10(low); high = Log10.log10(high); } final ValueRange rounded = roundValueRange(low, high); low = rounded.getLow(); high = rounded.getHigh(); if (axis.isLogarithmic()) { low = Log10.pow10(low); high = Log10.pow10(high); } else { // Stretch range a little bit // (but not for log scale, where low just above 0 // could be stretched to <= 0) final double headroom = (high - low) * 0.05; low -= headroom; high += headroom; } // Autoscale happens 'all the time'. // Do not use undo, but notify listeners. if (low < high) if (axis.setValueRange(low, high)) plot.fireYAxisChange(axis); } catch (Exception ex) { Activator.getLogger().log(Level.WARNING, "Axis autorange error for " + axis, ex); } } } }
applications/appunorganized/appunorganized-plugins/org.csstudio.swt.rtplot/src/org/csstudio/swt/rtplot/internal/PlotProcessor.java
/******************************************************************************* * Copyright (c) 2014 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.swt.rtplot.internal; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.function.Consumer; import java.util.logging.Level; import org.csstudio.swt.rtplot.Activator; import org.csstudio.swt.rtplot.Axis; import org.csstudio.swt.rtplot.AxisRange; import org.csstudio.swt.rtplot.Messages; import org.csstudio.swt.rtplot.Trace; import org.csstudio.swt.rtplot.data.PlotDataItem; import org.csstudio.swt.rtplot.data.PlotDataProvider; import org.csstudio.swt.rtplot.data.PlotDataSearch; import org.csstudio.swt.rtplot.data.ValueRange; import org.csstudio.swt.rtplot.internal.util.Log10; import org.csstudio.swt.rtplot.undo.AddAnnotationAction; import org.csstudio.swt.rtplot.undo.ChangeAxisRanges; import org.eclipse.swt.graphics.Point; /** Helper for processing traces of a plot * in a thread pool to avoid blocking UI thread. * @param <XTYPE> Data type of horizontal {@link Axis} * @author Kay Kasemir */ @SuppressWarnings("nls") public class PlotProcessor<XTYPE extends Comparable<XTYPE>> { final private static ExecutorService thread_pool = Executors.newWorkStealingPool(); final private Plot<XTYPE> plot; /** @param plot Plot on which this processor operates */ public PlotProcessor(final Plot<XTYPE> plot) { this.plot = plot; } /** Submit background job to determine value range for y axis for values within the * specified x axis. * @param data {@link PlotDataProvider} with values * @param x_range {@link AxisRange} covering visible part of plot * @return {@link Future} to {@link ValueRange} */ public Future<ValueRange> determineValueRange(final PlotDataProvider<XTYPE> data, final AxisRange<XTYPE> x_range) { return thread_pool.submit(new Callable<ValueRange>() { @Override public ValueRange call() throws Exception { double low = Double.MAX_VALUE; double high = -Double.MAX_VALUE; final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); data.getLock().lock(); try { if (data.size() > 0) { // Consider first sample at-or-before start int start = search.findSampleLessOrEqual(data, x_range.getLow()); if (start < 0) start = 0; // Last sample is the one just inside end of range. int stop = search.findSampleLessOrEqual(data, x_range.getHigh()); if (stop < 0) stop = 0; // If data is completely outside the x_range, // we end up using just data[0] // Check [start .. stop], including stop for (int i=start; i<=stop; ++i) { final PlotDataItem<XTYPE> item = data.get(i); final double value = item.getValue(); if (! Double.isFinite(value)) continue; if (value < low) low = value; if (value > high) high = value; } } } finally { data.getLock().unlock(); } return new ValueRange(low, high); } }); } /** Submit background job to determine value range * @param axis {@link YAxisImpl} for which to determine range * @param x_axis {@link AxisRange} over which range is to be determined * @return {@link Future} to {@link ValueRange} */ public Future<ValueRange> determineValueRange(final YAxisImpl<XTYPE> axis, final AxisPart<XTYPE> x_axis) { return thread_pool.submit(new Callable<ValueRange>() { @Override public ValueRange call() throws Exception { // In parallel, determine range of all traces in this axis final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (Trace<XTYPE> trace : axis.getTraces()) ranges.add(determineValueRange(trace.getData(), x_axis.getValueRange())); // Merge the trace ranges into overall axis range double low = Double.MAX_VALUE; double high = -Double.MAX_VALUE; for (Future<ValueRange> result : ranges) { final ValueRange range = result.get(); if (range.getLow() < low) low = range.getLow(); if (range.getHigh() > high) high = range.getHigh(); } return new ValueRange(low, high); } }); } /** Round value range up/down to add a little room above & below the exact range. * This results in "locking" to a nice looking range for a while * until a new sample outside of the rounded range is added. * * @param low Low and * @param high high end of value range * @return Adjusted range */ public ValueRange roundValueRange(final double low, final double high) { final double size = Math.abs(high-low); if (size > 0) { // Add 2 digits to the 'tight' order of magnitude final double order_of_magnitude = Math.floor(Log10.log10(size))-2; final double round = Math.pow(10, order_of_magnitude); return new ValueRange(Math.floor(low / round) * round, Math.ceil(high / round) * round); } else return new ValueRange(low, high); } /** Stagger the range of axes */ public void stagger() { thread_pool.execute(() -> { final double GAP = 0.1; // Arrange all axes so they don't overlap by assigning 1/Nth of // the vertical range to each one // Determine range of each axes' traces in parallel final List<YAxisImpl<XTYPE>> y_axes = new ArrayList<>(); final List<AxisRange<Double>> original_ranges = new ArrayList<>(); final List<AxisRange<Double>> new_ranges = new ArrayList<>(); final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) { y_axes.add(axis); // As fallback, assume that new range matches old range new_ranges.add(axis.getValueRange()); original_ranges.add(axis.getValueRange()); ranges.add(determineValueRange(axis, plot.getXAxis())); } final int N = y_axes.size(); for (int i=0; i<N; ++i) { final YAxisImpl<XTYPE> axis = y_axes.get(i); // Does axis handle itself in another way? if (axis.isAutoscale()) continue; // Fetch range of values on this axis final ValueRange axis_range; try { axis_range = ranges.get(i).get(); } catch (Exception ex) { Activator.getLogger().log(Level.WARNING, "Axis stagger error", ex); continue; } // Skip axis which for some reason cannot determine its range double low = axis_range.getLow(); double high = axis_range.getHigh(); if (low > high) continue; if (low == high) { // Center trace with constant value (empty range) final double half = Math.abs(low/2); low -= half; high += half; } if (axis.isLogarithmic()) { // Transition into log space low = Log10.log10(low); high = Log10.log10(high); } double span = high - low; // Make some extra space low -= GAP*span; high += GAP*span; span = high-low; // With N axes, assign 1/Nth of the vertical plot space to this axis // by shifting the span down according to the axis index, // using a total of N*range. low -= (N-i-1)*span; high += i*span; final ValueRange rounded = roundValueRange(low, high); low = rounded.getLow(); high = rounded.getHigh(); if (axis.isLogarithmic()) { // Revert from log space low = Log10.pow10(low); high = Log10.pow10(high); } // Sanity check for empty traces if (low < high && !Double.isInfinite(low) && !Double.isInfinite(high)) new_ranges.set(i, new AxisRange<Double>(low, high)); } // 'Stagger' tends to be on-demand, // or executed infrequently as archived data arrives after a zoom operation // -> Use undo, which also notifies listeners plot.getUndoableActionManager().execute(new ChangeAxisRanges<>(plot, Messages.Zoom_Stagger, y_axes, original_ranges, new_ranges)); }); } /** Compute cursor values for the various traces * * <p>Updates the 'selected' sample for each trace, * and sends valid {@link CursorMarker}s to the {@link Plot} * * @param cursor_x Pixel location of cursor * @param location Corresponding position on X axis * @param callback Will be called with markers for the cursor location */ public void updateCursorMarkers(final int cursor_x, final XTYPE location, final Consumer<List<CursorMarker>> callback) { // Run in thread thread_pool.execute(() -> { final List<CursorMarker> markers = new ArrayList<>(); final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) for (TraceImpl<XTYPE> trace : axis.getTraces()) { final PlotDataProvider<XTYPE> data = trace.getData(); final PlotDataItem<XTYPE> sample; data.getLock().lock(); try { final int index = search.findSampleLessOrEqual(data, location); sample = index >= 0 ? data.get(index) : null; } finally { data.getLock().unlock(); } trace.selectSample(sample); if (sample == null) continue; final double value = sample.getValue(); if (Double.isFinite(value) && axis.getValueRange().contains(value)) { String label = axis.getTicks().formatDetailed(value); final String units = trace.getUnits(); if (! units.isEmpty()) label += " " + units; markers.add(new CursorMarker(cursor_x, axis.getScreenCoord(value), trace.getColor(), label)); } } Collections.sort(markers); callback.accept(markers); }); } /** @param plot Plot where annotation is added * @param trace Trace to which a annotation should be added * @param text Text for the annotation */ public void createAnnotation(final Trace<XTYPE> trace, final String text) { final AxisPart<XTYPE> x_axis = plot.getXAxis(); // Run in thread thread_pool.execute(() -> { final AxisRange<Integer> range = x_axis.getScreenRange(); XTYPE location = x_axis.getValue((range.getLow() + range.getHigh())/2); final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); final PlotDataProvider<XTYPE> data = trace.getData(); double value= Double.NaN; data.getLock().lock(); try { final int index = search.findSampleGreaterOrEqual(data, location); if (index >= 0) { location = data.get(index).getPosition(); value = data.get(index).getValue(); } else location = null; } finally { data.getLock().unlock(); } if (location != null) plot.getUndoableActionManager().execute( new AddAnnotationAction<XTYPE>(plot, new AnnotationImpl<XTYPE>(false, trace, location, value, new Point(20, -20), text))); }); } public void updateAnnotation(final AnnotationImpl<XTYPE> annotation, final XTYPE location) { // Run in thread thread_pool.execute(() -> { final PlotDataSearch<XTYPE> search = new PlotDataSearch<>(); final PlotDataProvider<XTYPE> data = annotation.getTrace().getData(); XTYPE position; double value; data.getLock().lock(); try { final int index = search.findSampleLessOrEqual(data, location); if (index < 0) return; position = data.get(index).getPosition(); value = data.get(index).getValue(); } finally { data.getLock().unlock(); } plot.updateAnnotation(annotation, position, value, annotation.getOffset()); }); } /** * Perform autoscale for all axes that are marked as such. * Autoscale only for the data that is visible on the plot. */ public void autoscale() { // Determine range of each axes' traces in parallel final List<YAxisImpl<XTYPE>> y_axes = new ArrayList<>(); final List<Future<ValueRange>> ranges = new ArrayList<Future<ValueRange>>(); for (YAxisImpl<XTYPE> axis : plot.getYAxes()) if (axis.isAutoscale()) { y_axes.add(axis); ranges.add(determineValueRange(axis, plot.getXAxis())); } final int N = y_axes.size(); for (int i=0; i<N; ++i) { final YAxisImpl<XTYPE> axis = y_axes.get(i); try { final ValueRange new_range = ranges.get(i).get(); double low = new_range.getLow(), high = new_range.getHigh(); if (low > high) continue; if (low == high) { // Center trace with constant value (empty range) final double half = Math.abs(low/2); low -= half; high += half; } if (axis.isLogarithmic()) { // Perform adjustment in log space. // But first, refuse to deal with <= 0 if (low <= 0.0) low = 1; if (high <= low) high = 100; low = Log10.log10(low); high = Log10.log10(high); } final ValueRange rounded = roundValueRange(low, high); low = rounded.getLow(); high = rounded.getHigh(); if (axis.isLogarithmic()) { low = Log10.pow10(low); high = Log10.pow10(high); } else { // Stretch range a little bit // (but not for log scale, where low just above 0 // could be stretched to <= 0) final double headroom = (high - low) * 0.05; low -= headroom; high += headroom; } // Autoscale happens 'all the time'. // Do not use undo, but notify listeners. if (low < high) if (axis.setValueRange(low, high)) plot.fireYAxisChange(axis); } catch (Exception ex) { Activator.getLogger().log(Level.WARNING, "Axis autorange error for " + axis, ex); } } } }
Adding enum labels to the crosshair value.
applications/appunorganized/appunorganized-plugins/org.csstudio.swt.rtplot/src/org/csstudio/swt/rtplot/internal/PlotProcessor.java
Adding enum labels to the crosshair value.
Java
agpl-3.0
2f324ec570314304e8efcea1da25bf774832b8b1
0
rdkgit/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,aihua/opennms,aihua/opennms,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,tdefilip/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,tdefilip/opennms,aihua/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.vaadin.datacollection; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.opennms.core.utils.ConfigFileConstants; import org.opennms.core.xml.JaxbUtils; import org.opennms.features.vaadin.api.Logger; import org.opennms.netmgt.config.DataCollectionConfigDao; import org.opennms.netmgt.config.datacollection.DatacollectionGroup; import com.vaadin.data.util.ObjectProperty; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.TabSheet; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; import com.vaadin.ui.TabSheet.Tab; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.Runo; import de.steinwedel.vaadin.MessageBox; import de.steinwedel.vaadin.MessageBox.ButtonType; import de.steinwedel.vaadin.MessageBox.EventListener; /** * The Class DataCollectionGroupPanel. * * @author <a href="mailto:[email protected]">Alejandro Galue</a> */ // TODO When renaming a group, all the SNMP collections must be updated. @SuppressWarnings("serial") public abstract class DataCollectionGroupPanel extends Panel implements TabSheet.SelectedTabChangeListener { /** The group name. */ private final TextField groupName; /** The resource types. */ private final ResourceTypePanel resourceTypes; /** The groups. */ private final GroupPanel groups; /** The system definitions. */ private final SystemDefPanel systemDefs; /** * Instantiates a new data collection group panel. * * @param dataCollectionConfigDao the OpenNMS Data Collection Configuration DAO * @param group the data collection group object * @param logger the logger object */ public DataCollectionGroupPanel(final DataCollectionConfigDao dataCollectionConfigDao, final DatacollectionGroup group, final Logger logger) { setCaption("Data Collection"); addStyleName(Runo.PANEL_LIGHT); // Data Collection Group - Main Fields groupName = new TextField("Data Collection Group Name"); groupName.setPropertyDataSource(new ObjectProperty<String>(group.getName())); groupName.setNullSettingAllowed(false); groupName.setImmediate(true); resourceTypes = new ResourceTypePanel(dataCollectionConfigDao, group, logger); groups = new GroupPanel(dataCollectionConfigDao, group, logger); systemDefs = new SystemDefPanel(dataCollectionConfigDao, group, logger); // Button Toolbar final HorizontalLayout toolbar = new HorizontalLayout(); toolbar.addComponent(new Button("Save Data Collection File", new Button.ClickListener() { public void buttonClick(ClickEvent event) { processDataCollection(dataCollectionConfigDao, logger); } })); toolbar.addComponent(new Button("Cancel", new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { cancel(); logger.info("Data collection processing has been canceled"); } })); // Tab Panel final TabSheet tabs = new TabSheet(); tabs.setStyleName(Runo.TABSHEET_SMALL); tabs.setSizeFull(); tabs.addTab(resourceTypes, "Resource Types"); tabs.addTab(groups, "MIB Groups"); tabs.addTab(systemDefs, "System Definitions"); // Main Layout final VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setSpacing(true); mainLayout.setMargin(true); mainLayout.addComponent(toolbar); mainLayout.addComponent(groupName); mainLayout.addComponent(tabs); mainLayout.setComponentAlignment(toolbar, Alignment.MIDDLE_RIGHT); setContent(mainLayout); } /* (non-Javadoc) * @see com.vaadin.ui.TabSheet.SelectedTabChangeListener#selectedTabChange(com.vaadin.ui.TabSheet.SelectedTabChangeEvent) */ public void selectedTabChange(SelectedTabChangeEvent event) { TabSheet tabsheet = event.getTabSheet(); Tab tab = tabsheet.getTab(tabsheet.getSelectedTab()); if (tab != null) { getWindow().showNotification("Selected tab: " + tab.getCaption()); } } /** * Gets the OpenNMS data collection group. * * @return the OpenNMS data collection group */ public DatacollectionGroup getOnmsDataCollection() { final DatacollectionGroup dto = new DatacollectionGroup(); dto.setName((String) groupName.getValue()); dto.getGroupCollection().addAll(groups.getGroups()); dto.getResourceTypeCollection().addAll(resourceTypes.getResourceTypes()); dto.getSystemDefCollection().addAll(systemDefs.getSystemDefinitions()); return dto; } /** * Cancel. */ public abstract void cancel(); /** * Success. */ public abstract void success(); /** * Failure. */ public abstract void failure(); /** * Process data collection. * * @param dataCollectionConfigDao the OpenNMS data collection configuration DAO * @param logger the logger */ private void processDataCollection(final DataCollectionConfigDao dataCollectionConfigDao, final Logger logger) { final DatacollectionGroup dcGroup = getOnmsDataCollection(); final File configDir = new File(ConfigFileConstants.getHome(), "etc/datacollection/"); final File file = new File(configDir, dcGroup.getName().replaceAll(" ", "_") + ".xml"); if (file.exists()) { MessageBox mb = new MessageBox(getApplication().getMainWindow(), "Are you sure?", MessageBox.Icon.QUESTION, "Do you really want to override the existig file?<br/>All current information will be lost.", new MessageBox.ButtonConfig(MessageBox.ButtonType.YES, "Yes"), new MessageBox.ButtonConfig(MessageBox.ButtonType.NO, "No")); mb.addStyleName(Runo.WINDOW_DIALOG); mb.show(new EventListener() { public void buttonClicked(ButtonType buttonType) { if (buttonType == MessageBox.ButtonType.YES) { saveFile(file, dcGroup, logger); } } }); } else { if (dataCollectionConfigDao.getAvailableDataCollectionGroups().contains(dcGroup.getName())) { getApplication().getMainWindow().showNotification("There is a group with the same name, please pick another one."); } else { saveFile(file, dcGroup, logger); } } } /** * Saves file. * * @param file the file * @param dcGroup the datacollection-group * @param logger the logger */ private void saveFile(final File file, final DatacollectionGroup dcGroup, final Logger logger) { try { FileWriter writer = new FileWriter(file); JaxbUtils.marshal(dcGroup, writer); logger.info("Saving XML data into " + file.getAbsolutePath()); logger.warn("Remember to update datacollection-config.xml to include the group " + dcGroup.getName() + " and restart OpenNMS."); // Force reload datacollection-config.xml to be able to configure SNMP collections. try { final File configFile = ConfigFileConstants.getFile(ConfigFileConstants.DATA_COLLECTION_CONF_FILE_NAME); configFile.setLastModified(System.currentTimeMillis()); } catch (IOException e) { logger.warn("Can't reach datacollection-config.xml: " + e.getMessage()); } success(); } catch (Exception e) { logger.error(e.getMessage()); failure(); } } }
features/vaadin-snmp-events-and-metrics/src/main/java/org/opennms/features/vaadin/datacollection/DataCollectionGroupPanel.java
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.features.vaadin.datacollection; import java.io.File; import java.io.FileWriter; import java.io.IOException; import org.opennms.core.utils.ConfigFileConstants; import org.opennms.core.xml.JaxbUtils; import org.opennms.features.vaadin.api.Logger; import org.opennms.netmgt.config.DataCollectionConfigDao; import org.opennms.netmgt.config.datacollection.DatacollectionGroup; import com.vaadin.data.util.ObjectProperty; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Panel; import com.vaadin.ui.TabSheet; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.TabSheet.SelectedTabChangeEvent; import com.vaadin.ui.TabSheet.Tab; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.Runo; import de.steinwedel.vaadin.MessageBox; import de.steinwedel.vaadin.MessageBox.ButtonType; import de.steinwedel.vaadin.MessageBox.EventListener; /** * The Class DataCollectionGroupPanel. * * @author <a href="mailto:[email protected]">Alejandro Galue</a> */ // TODO When renaming a group, all the SNMP collections must be updated. @SuppressWarnings("serial") public abstract class DataCollectionGroupPanel extends Panel implements TabSheet.SelectedTabChangeListener { /** The group name. */ private final TextField groupName; /** The resource types. */ private final ResourceTypePanel resourceTypes; /** The groups. */ private final GroupPanel groups; /** The system definitions. */ private final SystemDefPanel systemDefs; /** * Instantiates a new data collection group panel. * * @param dataCollectionConfigDao the OpenNMS Data Collection Configuration DAO * @param group the data collection group object * @param logger the logger object */ public DataCollectionGroupPanel(final DataCollectionConfigDao dataCollectionConfigDao, final DatacollectionGroup group, final Logger logger) { setCaption("Data Collection"); addStyleName(Runo.PANEL_LIGHT); // Data Collection Group - Main Fields groupName = new TextField("Data Collection Group Name"); groupName.setPropertyDataSource(new ObjectProperty<String>(group.getName())); groupName.setNullSettingAllowed(false); groupName.setImmediate(true); resourceTypes = new ResourceTypePanel(dataCollectionConfigDao, group, logger); groups = new GroupPanel(dataCollectionConfigDao, group, logger); systemDefs = new SystemDefPanel(dataCollectionConfigDao, group, logger); // Button Toolbar final HorizontalLayout toolbar = new HorizontalLayout(); toolbar.addComponent(new Button("Save Data Collection File", new Button.ClickListener() { public void buttonClick(ClickEvent event) { DatacollectionGroup dcGroup = getOnmsDataCollection(); if (dataCollectionConfigDao.getAvailableDataCollectionGroups().contains(dcGroup.getName())) { getApplication().getMainWindow().showNotification("There is a group with the same name, please pick another one."); } else { processDataCollection(getOnmsDataCollection(), logger); logger.info("The data collection have been saved."); } } })); toolbar.addComponent(new Button("Cancel", new Button.ClickListener() { public void buttonClick(Button.ClickEvent event) { cancel(); logger.info("Data collection processing has been canceled"); } })); // Tab Panel final TabSheet tabs = new TabSheet(); tabs.setStyleName(Runo.TABSHEET_SMALL); tabs.setSizeFull(); tabs.addTab(resourceTypes, "Resource Types"); tabs.addTab(groups, "MIB Groups"); tabs.addTab(systemDefs, "System Definitions"); // Main Layout final VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setSpacing(true); mainLayout.setMargin(true); mainLayout.addComponent(toolbar); mainLayout.addComponent(groupName); mainLayout.addComponent(tabs); mainLayout.setComponentAlignment(toolbar, Alignment.MIDDLE_RIGHT); setContent(mainLayout); } /* (non-Javadoc) * @see com.vaadin.ui.TabSheet.SelectedTabChangeListener#selectedTabChange(com.vaadin.ui.TabSheet.SelectedTabChangeEvent) */ public void selectedTabChange(SelectedTabChangeEvent event) { TabSheet tabsheet = event.getTabSheet(); Tab tab = tabsheet.getTab(tabsheet.getSelectedTab()); if (tab != null) { getWindow().showNotification("Selected tab: " + tab.getCaption()); } } /** * Gets the OpenNMS data collection group. * * @return the OpenNMS data collection group */ public DatacollectionGroup getOnmsDataCollection() { final DatacollectionGroup dto = new DatacollectionGroup(); dto.setName((String) groupName.getValue()); dto.getGroupCollection().addAll(groups.getGroups()); dto.getResourceTypeCollection().addAll(resourceTypes.getResourceTypes()); dto.getSystemDefCollection().addAll(systemDefs.getSystemDefinitions()); return dto; } /** * Cancel. */ public abstract void cancel(); /** * Success. */ public abstract void success(); /** * Failure. */ public abstract void failure(); /** * Process data collection. * * @param dcGroup the OpenNMS Data Collection Group * @param logger the logger */ private void processDataCollection(final DatacollectionGroup dcGroup, final Logger logger) { final File configDir = new File(ConfigFileConstants.getHome(), "etc/datacollection/"); final File file = new File(configDir, dcGroup.getName().replaceAll(" ", "_") + ".xml"); if (file.exists()) { MessageBox mb = new MessageBox(getApplication().getMainWindow(), "Are you sure?", MessageBox.Icon.QUESTION, "Do you really want to override the existig file?<br/>All current information will be lost.", new MessageBox.ButtonConfig(MessageBox.ButtonType.YES, "Yes"), new MessageBox.ButtonConfig(MessageBox.ButtonType.NO, "No")); mb.addStyleName(Runo.WINDOW_DIALOG); mb.show(new EventListener() { public void buttonClicked(ButtonType buttonType) { if (buttonType == MessageBox.ButtonType.YES) { saveFile(file, dcGroup, logger); } } }); } else { saveFile(file, dcGroup, logger); // Force reload datacollection-config.xml to be able to configure SNMP collections. try { final File configFile = ConfigFileConstants.getFile(ConfigFileConstants.DATA_COLLECTION_CONF_FILE_NAME); configFile.setLastModified(System.currentTimeMillis()); } catch (IOException e) { logger.warn("Can't reach datacollection-config.xml: " + e.getMessage()); } } } /** * Saves file. * * @param file the file * @param dcGroup the datacollection-group * @param logger the logger */ private void saveFile(final File file, final DatacollectionGroup dcGroup, final Logger logger) { try { FileWriter writer = new FileWriter(file); JaxbUtils.marshal(dcGroup, writer); logger.info("Saving XML data into " + file.getAbsolutePath()); logger.warn("Remember to update datacollection-config.xml to include the group " + dcGroup.getName() + " and restart OpenNMS."); success(); } catch (Exception e) { logger.error(e.getMessage()); failure(); } } }
Fixing the workflow when saving a DataCollectionGroup file.
features/vaadin-snmp-events-and-metrics/src/main/java/org/opennms/features/vaadin/datacollection/DataCollectionGroupPanel.java
Fixing the workflow when saving a DataCollectionGroup file.
Java
apache-2.0
d30fec178abcfcdb93943d2b0841032d80433535
0
mhardalov/sports-web-search,mhardalov/sports-web-search
package org.sports.websearch.model; import java.util.ArrayList; import java.util.List; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.SpellCheckResponse; import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation; public class SpellSuggestion { private List<String> suggestions; public SpellSuggestion() { this.setSuggestions(new ArrayList<String>()); } public SpellSuggestion(QueryResponse response) { this.setSuggestions(new ArrayList<String>()); SpellCheckResponse spellCheckResponse = response .getSpellCheckResponse(); if (!spellCheckResponse.isCorrectlySpelled() && response.getSpellCheckResponse() .getCollatedResults() != null) { for (Collation collation : response.getSpellCheckResponse() .getCollatedResults()) { this.suggestions.add(collation.getCollationQueryString()); } } } public String getSuggestionQuery() { return this.suggestions.size() > 0 ? this.suggestions.get(0) : ""; } public List<String> getSuggestions() { return suggestions; } public void setSuggestions(List<String> suggestions) { this.suggestions = suggestions; } }
src/main/java/org/sports/websearch/model/SpellSuggestion.java
package org.sports.websearch.model; import java.util.ArrayList; import java.util.List; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.SpellCheckResponse; import org.apache.solr.client.solrj.response.SpellCheckResponse.Collation; public class SpellSuggestion { private List<String> suggestions; public SpellSuggestion() { this.setSuggestions(new ArrayList<String>()); } public SpellSuggestion(QueryResponse response) { this.setSuggestions(new ArrayList<String>()); SpellCheckResponse spellCheckResponse = response .getSpellCheckResponse(); if (!spellCheckResponse.isCorrectlySpelled()) { for (Collation collation : response.getSpellCheckResponse() .getCollatedResults()) { this.suggestions.add(collation.getCollationQueryString()); } } } public String getSuggestionQuery() { return this.suggestions.size() > 0 ? this.suggestions.get(0) : ""; } public List<String> getSuggestions() { return suggestions; } public void setSuggestions(List<String> suggestions) { this.suggestions = suggestions; } }
Validation for suggestions. Fixed null pointer exception
src/main/java/org/sports/websearch/model/SpellSuggestion.java
Validation for suggestions. Fixed null pointer exception
Java
apache-2.0
5afd90790ae656d4c3b40cb201113e80373bdff4
0
FIRST-Tech-Challenge/appinventor-sources,doburaimo/appinventor-sources,fmntf/appinventor-sources,RachaelT/appinventor-sources,satgod/appinventor,mit-dig/punya,mark-friedman/web-appinventor,fturbak/appinventor-sources,afmckinney/appinventor-sources,themadrobot/appinventor-sources,awoodworth/appinventor-sources,nwtel/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,jithinbp/appinventor-sources,mit-cml/appinventor-sources,jsheldonmit/appinventor-sources,sujianping/appinventor-sources,jithinbp/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,GodUseVPN/appinventor-sources,tiffanyle/appinventor-sources,jsheldonmit/appinventor-sources,josmas/app-inventor,tvomf/appinventor-mapps,anseo/friedgerAI24BLE,mit-cml/appinventor-sources,emeryotopalik/appinventor-sources,ram8647/appinventor-sources,JalexChang/appinventor-sources,Edeleon4/punya,William-Byrne/appinventor-sources,themadrobot/appinventor-sources,GodUseVPN/appinventor-sources,E-Hon/appinventor-sources,nickboucart/appinventor-sources,josmas/app-inventor,tatuzaumm/app-inventor2-custom,nwtel/appinventor-sources,AlanRosenthal/appinventor-sources,nwtel/appinventor-sources,jithinbp/appinventor-sources,graceRyu/appinventor-sources,Klomi/appinventor-sources,bitsecure/appinventor1-sources,jcweaver/appinventorTutorial,ajcolter/appinventor-sources,sujianping/appinventor-sources,bitsecure/appinventor1-sources,afmckinney/appinventor-sources,youprofit/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,thequixotic/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,warren922/appinventor-sources,Mateopato/appinventor-sources,bxie/appinventor-sources,KeithGalli/appinventor-sources,GodUseVPN/appinventor-sources,mintingle/appinventor-sources,emeryotopalik/appinventor-sources,awoodworth/appinventor-sources,onyeka/AppInventor-WebApp,awoodworth/appinventor-sources,toropeza/appinventor-sources,JalexChang/appinventor-sources,lizlooney/appinventor-sources,wadleo/appinventor-sources,ram8647/appinventor-sources,themadrobot/appinventor-sources,emeryotopalik/appinventor-sources,dengxinyue0420/appinventor-sources,ZachLamb/appinventor-sources,anseo/friedgerAI24BLE,AlanRosenthal/appinventor-sources,fmntf/appinventor-sources,mit-dig/punya,wanddy/ai4all2,spefley/appinventor-sources,wadleo/appinventor-sources,wicedfast/appinventor-sources,marksherman/appinventor-sources,AlanRosenthal/appinventor-sources,yflou520/appinventor-sources,DRavnaas/appinventor-clone,jisqyv/appinventor-sources,Edeleon4/punya,ewpatton/appinventor-sources,wanddy/ai4all2,ewpatton/appinventor-sources,Momoumar/appinventor-sources,aouskaroui/appinventor-sources,warren922/appinventor-sources,doburaimo/appinventor-sources,mark-friedman/web-appinventor,wanddy/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,halatmit/appinventor-sources,mit-dig/punya,Momoumar/appinventor-sources,lizlooney/appinventor-sources,Mateopato/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,aouskaroui/appinventor-sources,CoderDojoLX/appinventor-sources,JalexChang/appinventor-sources,CoderDojoLX/appinventor-sources,wanddy/appinventor-sources,halatmit/appinventor-sources,CoderDojoLX/appinventor-sources,liyucun/appinventor-sources,wanddy/ai4all2,thequixotic/appinventor-sources,nickboucart/appinventor-sources,Klomi/appinventor-sources,hasi96/appinventor-sources,satgod/appinventor,joshaham/latest_app_inventor,lizlooney/appinventor-sources,mintingle/appinventor-sources,dengxinyue0420/appinventor-sources,marksherman/appinventor-sources,ZachLamb/appinventor-sources,warren922/appinventor-sources,Momoumar/appinventor-sources,graceRyu/appinventor-sources,ram8647/appinventor-sources,halatmit/appinventor-sources,jithinbp/appinventor-sources,graceRyu/appinventor-sources,kkashi01/appinventor-sources,wanddy/ai4all2,joshaham/latest_app_inventor,puravidaapps/appinventor-sources,kkashi01/appinventor-sources,RachaelT/appinventor-sources,CoderDojoLX/appinventor-sources,liyucun/appinventor-sources,mintingle/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,hasi96/appinventor-sources,Edeleon4/punya,dengxinyue0420/appinventor-sources,warren922/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,Mateopato/appinventor-sources,E-Hon/appinventor-sources,lizlooney/appinventor-sources,jcweaver/appinventorTutorial,frfranca/appinventor-sources,thilankam/appinventor-sources,DRavnaas/appinventor-clone,nmcalabroso/appinventor-sources,josmas/app-inventor,kkashi01/appinventor-sources,thequixotic/appinventor-sources,krishc90/APP-INVENTOR,dengxinyue0420/appinventor-sources,wicedfast/appinventor-sources,mit-cml/appinventor-sources,KeithGalli/appinventor-sources,farxinu/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,sujianping/appinventor-sources,wicedfast/appinventor-sources,tvomf/appinventor-mapps,onyeka/AppInventor-WebApp,jisqyv/appinventor-sources,bitsecure/appinventor1-sources,Klomi/appinventor-sources,afmckinney/appinventor-sources,tiffanyle/appinventor-sources,William-Byrne/appinventor-sources,jcweaver/appinventorTutorial,kannan-usf/AppInventorJavaBridge,wanddy/ai4all2,josmas/app-inventor,weihuali0509/web-appinventor,joshaham/latest_app_inventor,wadleo/appinventor-sources,William-Byrne/appinventor-sources,afmckinney/appinventor-sources,barreeeiroo/appinventor-sources,anseo/friedgerAI24BLE,tatuzaumm/app-inventor2-custom,LaboratoryForPlayfulComputation/appinventor-sources,weihuali0509/appinventor-sources,bxie/appinventor-sources,yflou520/appinventor-sources,Edeleon4/punya,marksherman/appinventor-sources,fturbak/appinventor-sources,GodUseVPN/appinventor-sources,spefley/appinventor-sources,DRavnaas/appinventor-clone,barreeeiroo/appinventor-sources,yflou520/appinventor-sources,tatuzaumm/app-inventor2-custom,halatmit/appinventor-sources,fmntf/appinventor-sources,jcweaver/appinventorTutorial,kkashi01/appinventor-sources,nmcalabroso/appinventor-sources,kidebit/AudioBlurp,mit-cml/appinventor-sources,jisqyv/appinventor-sources,aouskaroui/appinventor-sources,jsheldonmit/appinventor-sources,mintingle/appinventor-sources,Edeleon4/punya,kannan-usf/AppInventorJavaBridge,weihuali0509/web-appinventor,puravidaapps/appinventor-sources,ewpatton/appinventor-sources,weihuali0509/web-appinventor,KeithGalli/appinventor-sources,Momoumar/appinventor-sources,tiffanyle/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,kkashi01/appinventor-sources,weihuali0509/web-appinventor,barreeeiroo/appinventor-sources,gitars/appinventor-sources,liyucun/appinventor-sources,wanddy/appinventor-sources,joshaham/latest_app_inventor,hasi96/appinventor-sources,nwtel/appinventor-sources,puravidaapps/appinventor-sources,toropeza/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,frfranca/appinventor-sources,GodUseVPN/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,wadleo/appinventor-sources,youprofit/appinventor-sources,kidebit/AudioBlurp,gitars/appinventor-sources,kidebit/AudioBlurp,weihuali0509/appinventor-sources,lizlooney/appinventor-sources,weihuali0509/appinventor-sources,spefley/appinventor-sources,ajcolter/appinventor-sources,mit-dig/punya,warren922/appinventor-sources,doburaimo/appinventor-sources,satgod/appinventor,AlanRosenthal/appinventor-sources,spefley/appinventor-sources,onyeka/AppInventor-WebApp,thilankam/appinventor-sources,onyeka/AppInventor-WebApp,bitsecure/appinventor1-sources,egiurleo/appinventor-sources,tatuzaumm/app-inventor2-custom,yflou520/appinventor-sources,toropeza/appinventor-sources,bxie/appinventor-sources,farxinu/appinventor-sources,liyucun/appinventor-sources,RachaelT/appinventor-sources,AlanRosenthal/appinventor-sources,mintingle/appinventor-sources,barreeeiroo/appinventor-sources,farxinu/appinventor-sources,frfranca/appinventor-sources,wanddy/appinventor-sources,anseo/friedgerAI24BLE,krishc90/APP-INVENTOR,krishc90/APP-INVENTOR,fturbak/appinventor-sources,thequixotic/appinventor-sources,onyeka/AppInventor-WebApp,liyucun/appinventor-sources,aouskaroui/appinventor-sources,mit-dig/punya,ram8647/appinventor-sources,mit-dig/punya,halatmit/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,JalexChang/appinventor-sources,ajcolter/appinventor-sources,jsheldonmit/appinventor-sources,mit-cml/appinventor-sources,puravidaapps/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,themadrobot/appinventor-sources,E-Hon/appinventor-sources,tvomf/appinventor-mapps,frfranca/appinventor-sources,themadrobot/appinventor-sources,Klomi/appinventor-sources,egiurleo/appinventor-sources,kkashi01/appinventor-sources,kannan-usf/AppInventorJavaBridge,thequixotic/appinventor-sources,tiffanyle/appinventor-sources,hasi96/appinventor-sources,bxie/appinventor-sources,jisqyv/appinventor-sources,doburaimo/appinventor-sources,wicedfast/appinventor-sources,CoderDojoLX/appinventor-sources,DRavnaas/appinventor-clone,farxinu/appinventor-sources,ewpatton/appinventor-sources,mit-cml/appinventor-sources,toropeza/appinventor-sources,barreeeiroo/appinventor-sources,nickboucart/appinventor-sources,ZachLamb/appinventor-sources,awoodworth/appinventor-sources,mark-friedman/web-appinventor,halatmit/appinventor-sources,marksherman/appinventor-sources,KeithGalli/appinventor-sources,thilankam/appinventor-sources,aouskaroui/appinventor-sources,nwtel/appinventor-sources,jcweaver/appinventorTutorial,tvomf/appinventor-mapps,weihuali0509/appinventor-sources,youprofit/appinventor-sources,awoodworth/appinventor-sources,egiurleo/appinventor-sources,KeithGalli/appinventor-sources,marksherman/appinventor-sources,joshaham/latest_app_inventor,mark-friedman/web-appinventor,youprofit/appinventor-sources,toropeza/appinventor-sources,emeryotopalik/appinventor-sources,ajcolter/appinventor-sources,spefley/appinventor-sources,ajcolter/appinventor-sources,ZachLamb/appinventor-sources,fmntf/appinventor-sources,sujianping/appinventor-sources,emeryotopalik/appinventor-sources,ewpatton/appinventor-sources,DRavnaas/appinventor-clone,jsheldonmit/appinventor-sources,nickboucart/appinventor-sources,LaboratoryForPlayfulComputation/appinventor-sources,farxinu/appinventor-sources,Klomi/appinventor-sources,Edeleon4/punya,kidebit/https-github.com-wicedfast-appinventor-sources,wadleo/appinventor-sources,josmas/app-inventor,RachaelT/appinventor-sources,gitars/appinventor-sources,youprofit/appinventor-sources,nickboucart/appinventor-sources,fmntf/appinventor-sources,afmckinney/appinventor-sources,Mateopato/appinventor-sources,E-Hon/appinventor-sources,satgod/appinventor,tvomf/appinventor-mapps,Momoumar/appinventor-sources,wicedfast/appinventor-sources,mintingle/appinventor-sources,nmcalabroso/appinventor-sources,puravidaapps/appinventor-sources,gitars/appinventor-sources,egiurleo/appinventor-sources,kannan-usf/AppInventorJavaBridge,tatuzaumm/app-inventor2-custom,ewpatton/appinventor-sources,hasi96/appinventor-sources,cs6510/CS6510-LiveEdit-Onyeka,yflou520/appinventor-sources,JalexChang/appinventor-sources,dengxinyue0420/appinventor-sources,thilankam/appinventor-sources,fturbak/appinventor-sources,kannan-usf/AppInventorJavaBridge,bitsecure/appinventor1-sources,graceRyu/appinventor-sources,E-Hon/appinventor-sources,jisqyv/appinventor-sources,wanddy/appinventor-sources,bxie/appinventor-sources,thilankam/appinventor-sources,Mateopato/appinventor-sources,kidebit/https-github.com-wicedfast-appinventor-sources,ZachLamb/appinventor-sources,nmcalabroso/appinventor-sources,tiffanyle/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,mit-dig/punya,egiurleo/appinventor-sources,mark-friedman/web-appinventor,gitars/appinventor-sources,marksherman/appinventor-sources,krishc90/APP-INVENTOR,jisqyv/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,William-Byrne/appinventor-sources,nmcalabroso/appinventor-sources,William-Byrne/appinventor-sources,weihuali0509/web-appinventor,sujianping/appinventor-sources,graceRyu/appinventor-sources,ram8647/appinventor-sources,kpjs4s/AppInventorJavaBridgeCodeGen,weihuali0509/appinventor-sources,krishc90/APP-INVENTOR,RachaelT/appinventor-sources,frfranca/appinventor-sources,FIRST-Tech-Challenge/appinventor-sources,kidebit/AudioBlurp,fturbak/appinventor-sources,josmas/app-inventor,jithinbp/appinventor-sources,satgod/appinventor,doburaimo/appinventor-sources
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package com.google.appinventor.client.editor.youngandroid.properties; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.components.MockVisibleComponent; import com.google.appinventor.client.widgets.properties.AdditionalChoicePropertyEditor; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Property editor for length properties (i.e. width and height). * */ public class YoungAndroidLengthPropertyEditor extends AdditionalChoicePropertyEditor { public static final String CONST_AUTOMATIC = "" + MockVisibleComponent.LENGTH_PREFERRED; public static final String CONST_FILL_PARENT = "" + MockVisibleComponent.LENGTH_FILL_PARENT; private static int uniqueIdSeed = 0; private final RadioButton automaticRadioButton; private final RadioButton fillParentRadioButton; private final RadioButton customLengthRadioButton; private final TextBox customLengthField; /** * Creates a new length property editor. */ public YoungAndroidLengthPropertyEditor() { // The radio button group cannot be shared across all instances, so we append a unique id. int uniqueId = ++uniqueIdSeed; String radioButtonGroup = "LengthType-" + uniqueId; automaticRadioButton = new RadioButton(radioButtonGroup, MESSAGES.automaticCaption()); fillParentRadioButton = new RadioButton(radioButtonGroup, MESSAGES.fillParentCaption()); customLengthRadioButton = new RadioButton(radioButtonGroup); customLengthField = new TextBox(); customLengthField.setVisibleLength(4); customLengthField.setMaxLength(4); Panel customRow = new HorizontalPanel(); customRow.add(customLengthRadioButton); customRow.add(customLengthField); Label pixels = new Label(MESSAGES.pixelsCaption()); pixels.setStylePrimaryName("ode-PixelsLabel"); customRow.add(pixels); Panel panel = new VerticalPanel(); panel.add(automaticRadioButton); panel.add(fillParentRadioButton); panel.add(customRow); automaticRadioButton.addValueChangeHandler(new ValueChangeHandler() { @Override public void onValueChange(ValueChangeEvent event) { // Clear the custom length field. customLengthField.setText(""); } }); fillParentRadioButton.addValueChangeHandler(new ValueChangeHandler() { @Override public void onValueChange(ValueChangeEvent event) { // Clear the custom length field. customLengthField.setText(""); } }); customLengthField.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { // If the user clicks on the custom length field, but the radio button for a custom length // is not checked, check it. if (!customLengthRadioButton.isChecked()) { customLengthRadioButton.setChecked(true); } } }); initAdditionalChoicePanel(panel); } @Override protected void updateValue() { super.updateValue(); String propertyValue = property.getValue(); if (propertyValue.equals(CONST_AUTOMATIC)) { automaticRadioButton.setChecked(true); } else if (propertyValue.equals(CONST_FILL_PARENT)) { fillParentRadioButton.setChecked(true); } else { customLengthRadioButton.setChecked(true); customLengthField.setText(propertyValue); } } @Override protected String getPropertyValueSummary() { String lengthHint = property.getValue(); if (lengthHint.equals(CONST_AUTOMATIC)) { return MESSAGES.automaticCaption(); } else if (lengthHint.equals(CONST_FILL_PARENT)) { return MESSAGES.fillParentCaption(); } else { return MESSAGES.pixelsSummary(lengthHint); } } @Override protected boolean okAction() { if (automaticRadioButton.isChecked()) { property.setValue(CONST_AUTOMATIC); } else if (fillParentRadioButton.isChecked()) { property.setValue(CONST_FILL_PARENT); } else { // Custom length String text = customLengthField.getText(); // Make sure it's a non-negative number. It is important // that this check stay within the custom length case because // CONST_AUTOMATIC and CONST_FILL_PARENT are deliberately negative. boolean success = false; try { if (Integer.parseInt(text) >= 0) { success = true; } } catch (NumberFormatException e) { // fall through with success == false } if (!success) { Window.alert(MESSAGES.nonnumericInputError()); return false; } property.setValue(text); } return true; } }
appinventor/appengine/src/com/google/appinventor/client/editor/youngandroid/properties/YoungAndroidLengthPropertyEditor.java
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt package com.google.appinventor.client.editor.youngandroid.properties; import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.components.MockVisibleComponent; import com.google.appinventor.client.widgets.properties.AdditionalChoicePropertyEditor; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; /** * Property editor for length properties (i.e. width and height). * */ public class YoungAndroidLengthPropertyEditor extends AdditionalChoicePropertyEditor { public static final String CONST_AUTOMATIC = "" + MockVisibleComponent.LENGTH_PREFERRED; public static final String CONST_FILL_PARENT = "" + MockVisibleComponent.LENGTH_FILL_PARENT; private static int uniqueIdSeed = 0; private final RadioButton automaticRadioButton; private final RadioButton fillParentRadioButton; private final RadioButton customLengthRadioButton; private final TextBox customLengthField; /** * Creates a new length property editor. */ public YoungAndroidLengthPropertyEditor() { // The radio button group cannot be shared across all instances, so we append a unique id. int uniqueId = ++uniqueIdSeed; String radioButtonGroup = "LengthType-" + uniqueId; automaticRadioButton = new RadioButton(radioButtonGroup, MESSAGES.automaticCaption()); fillParentRadioButton = new RadioButton(radioButtonGroup, MESSAGES.fillParentCaption()); customLengthRadioButton = new RadioButton(radioButtonGroup); customLengthField = new TextBox(); customLengthField.setVisibleLength(3); customLengthField.setMaxLength(3); Panel customRow = new HorizontalPanel(); customRow.add(customLengthRadioButton); customRow.add(customLengthField); Label pixels = new Label(MESSAGES.pixelsCaption()); pixels.setStylePrimaryName("ode-PixelsLabel"); customRow.add(pixels); Panel panel = new VerticalPanel(); panel.add(automaticRadioButton); panel.add(fillParentRadioButton); panel.add(customRow); automaticRadioButton.addValueChangeHandler(new ValueChangeHandler() { @Override public void onValueChange(ValueChangeEvent event) { // Clear the custom length field. customLengthField.setText(""); } }); fillParentRadioButton.addValueChangeHandler(new ValueChangeHandler() { @Override public void onValueChange(ValueChangeEvent event) { // Clear the custom length field. customLengthField.setText(""); } }); customLengthField.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { // If the user clicks on the custom length field, but the radio button for a custom length // is not checked, check it. if (!customLengthRadioButton.isChecked()) { customLengthRadioButton.setChecked(true); } } }); initAdditionalChoicePanel(panel); } @Override protected void updateValue() { super.updateValue(); String propertyValue = property.getValue(); if (propertyValue.equals(CONST_AUTOMATIC)) { automaticRadioButton.setChecked(true); } else if (propertyValue.equals(CONST_FILL_PARENT)) { fillParentRadioButton.setChecked(true); } else { customLengthRadioButton.setChecked(true); customLengthField.setText(propertyValue); } } @Override protected String getPropertyValueSummary() { String lengthHint = property.getValue(); if (lengthHint.equals(CONST_AUTOMATIC)) { return MESSAGES.automaticCaption(); } else if (lengthHint.equals(CONST_FILL_PARENT)) { return MESSAGES.fillParentCaption(); } else { return MESSAGES.pixelsSummary(lengthHint); } } @Override protected boolean okAction() { if (automaticRadioButton.isChecked()) { property.setValue(CONST_AUTOMATIC); } else if (fillParentRadioButton.isChecked()) { property.setValue(CONST_FILL_PARENT); } else { // Custom length String text = customLengthField.getText(); // Make sure it's a non-negative number. It is important // that this check stay within the custom length case because // CONST_AUTOMATIC and CONST_FILL_PARENT are deliberately negative. boolean success = false; try { if (Integer.parseInt(text) >= 0) { success = true; } } catch (NumberFormatException e) { // fall through with success == false } if (!success) { Window.alert(MESSAGES.nonnumericInputError()); return false; } property.setValue(text); } return true; } }
Increase space for speciying width and height to 4 digits, rather than 3 Change-Id: I70e7091f11e730d7fbcdc84158108018a15f7f80
appinventor/appengine/src/com/google/appinventor/client/editor/youngandroid/properties/YoungAndroidLengthPropertyEditor.java
Increase space for speciying width and height to 4 digits, rather than 3
Java
apache-2.0
5ccd4547cba41aaea9e552d45b08700429aba2a3
0
subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/base,subutai-io/base,subutai-io/base
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.commands; import org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.CassandraModule; import org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.management.CassandraCommandEnum; import org.safehaus.kiskis.mgmt.shared.protocol.CommandImpl; import org.safehaus.kiskis.mgmt.shared.protocol.CommandFactory; import org.safehaus.kiskis.mgmt.shared.protocol.enums.OutputRedirection; import org.safehaus.kiskis.mgmt.shared.protocol.Request; import org.safehaus.kiskis.mgmt.shared.protocol.enums.RequestType; /** * * @author dilshat */ public class CassandraCommands { // private static final String conf = "/opt/cassandra-2.0.4/conf/cassandra.yaml"; private static final String conf = "$CASSANDRA_HOME/conf/cassandra.yaml"; // INSTALLATION COMMANDS =================================================== public static CommandImpl getTemplate() { return (CommandImpl) CommandFactory.createRequest( RequestType.EXECUTE_REQUEST, // type null, // !! agent uuid CassandraModule.MODULE_NAME, // source null, // !! task uuid 1, // !! request sequence number "/", // cwd null, // program OutputRedirection.RETURN, // std output redirection OutputRedirection.RETURN, // std error redirection null, // stdout capture file path null, // stderr capture file path "root", // runas null, // arg null, // env vars 60); // timeout (sec) } // public static Command getInstallCommand() { // Command cmd = getTemplate(); // Request req = cmd.getRequest(); // req.setProgram("/usr/bin/apt-get"); // req.setArgs(Arrays.asList( // "--force-yes", // "--assume-yes", // "install", // "ksks-cassandra" // )); // req.setTimeout(180); // return cmd; // } // public static Command getUninstallCommand() { // Command cmd = getTemplate(); // Request req = cmd.getRequest(); // req.setProgram("/usr/bin/apt-get"); // req.setArgs(Arrays.asList( // "--force-yes", // "--assume-yes", // "purge", // "ksks-cassandra" // )); // req.setTimeout(180); // return cmd; // } public static CommandImpl getSetListenAddressCommand(String listenAddress) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/listen_address:/=' " + conf + ")`'s!.*!listen_address: %listenAddress!'"; req.setProgram(program.replace("%listenAddress", listenAddress)); return cmd; } public static CommandImpl getSetRpcAddressCommand(String rpcAddress) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/rpc_address:/=' " + conf + ")`'s!.*!rpc_address: %rpcAddress!'"; req.setProgram(program.replace("%rpcAddress", rpcAddress)); return cmd; } public static CommandImpl getSetSeedsCommand(String seeds) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/- seeds:/=' " + conf + ")`'s!.*! - seeds: %seedsIps!'"; req.setProgram(program.replace("%seedsIps", '"' + seeds + '"')); return cmd; } public static CommandImpl getSetClusterNameCommand(String clusterName) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/cluster_name:/=' " + conf + ")`'s!.*!cluster_name: %clusterName!'"; req.setProgram(program.replace("%clusterName", clusterName)); return cmd; } public static CommandImpl getSetDataDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/data_file_directories:/=' " + conf + ") + 1`'s!.*! - %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getSetCommitLogDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/commitlog_directory:/=' " + conf + ")`'s!.*!commitlog_directory: %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getSetSavedCachesDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/saved_caches_directory:/=' " + conf + ")`'s!.*!saved_caches_directory: %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getDeleteDataDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/data/*"); return cmd; } public static CommandImpl getDeleteCommitLogDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/commitlog/*"); return cmd; } public static CommandImpl getDeleteSavedCachesDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/saved_caches/*"); return cmd; } public static CommandImpl getSourceEtcProfileUpdateCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram(". /etc/profile"); return cmd; } public static CommandImpl getServiceCassandraStartCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra start"); return cmd; } public static CommandImpl getServiceCassandraStopCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra stop"); return cmd; } public static CommandImpl getServiceCassandraStatusCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra status"); return cmd; } public static CommandImpl getAptGetUpdate() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("apt-get update"); return cmd; } public CommandImpl getCommand(CassandraCommandEnum cce) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram(cce.getProgram()); return cmd; } }
management/server/ui-modules/cassandra/src/main/java/org/safehaus/kiskis/mgmt/server/ui/modules/cassandra/commands/CassandraCommands.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.commands; import org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.CassandraModule; import org.safehaus.kiskis.mgmt.server.ui.modules.cassandra.management.CassandraCommandEnum; import org.safehaus.kiskis.mgmt.shared.protocol.CommandImpl; import org.safehaus.kiskis.mgmt.shared.protocol.CommandFactory; import org.safehaus.kiskis.mgmt.shared.protocol.enums.OutputRedirection; import org.safehaus.kiskis.mgmt.shared.protocol.Request; import org.safehaus.kiskis.mgmt.shared.protocol.enums.RequestType; /** * * @author dilshat */ public class CassandraCommands { private static final String conf = "/opt/cassandra-2.0.3/conf/cassandra.yaml"; // INSTALLATION COMMANDS =================================================== public static CommandImpl getTemplate() { return (CommandImpl) CommandFactory.createRequest( RequestType.EXECUTE_REQUEST, // type null, // !! agent uuid CassandraModule.MODULE_NAME, // source null, // !! task uuid 1, // !! request sequence number "/", // cwd null, // program OutputRedirection.RETURN, // std output redirection OutputRedirection.RETURN, // std error redirection null, // stdout capture file path null, // stderr capture file path "root", // runas null, // arg null, // env vars 60); // timeout (sec) } // public static Command getInstallCommand() { // Command cmd = getTemplate(); // Request req = cmd.getRequest(); // req.setProgram("/usr/bin/apt-get"); // req.setArgs(Arrays.asList( // "--force-yes", // "--assume-yes", // "install", // "ksks-cassandra" // )); // req.setTimeout(180); // return cmd; // } // public static Command getUninstallCommand() { // Command cmd = getTemplate(); // Request req = cmd.getRequest(); // req.setProgram("/usr/bin/apt-get"); // req.setArgs(Arrays.asList( // "--force-yes", // "--assume-yes", // "purge", // "ksks-cassandra" // )); // req.setTimeout(180); // return cmd; // } public static CommandImpl getSetListenAddressCommand(String listenAddress) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/listen_address:/=' " + conf + ")`'s!.*!listen_address: %listenAddress!'"; req.setProgram(program.replace("%listenAddress", listenAddress)); return cmd; } public static CommandImpl getSetRpcAddressCommand(String rpcAddress) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/rpc_address:/=' " + conf + ")`'s!.*!rpc_address: %rpcAddress!'"; req.setProgram(program.replace("%rpcAddress", rpcAddress)); return cmd; } public static CommandImpl getSetSeedsCommand(String seeds) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/- seeds:/=' " + conf + ")`'s!.*! - seeds: %seedsIps!'"; req.setProgram(program.replace("%seedsIps", '"' + seeds + '"')); return cmd; } public static CommandImpl getSetClusterNameCommand(String clusterName) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/cluster_name:/=' " + conf + ")`'s!.*!cluster_name: %clusterName!'"; req.setProgram(program.replace("%clusterName", clusterName)); return cmd; } public static CommandImpl getSetDataDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/data_file_directories:/=' " + conf + ") + 1`'s!.*! - %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getSetCommitLogDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/commitlog_directory:/=' " + conf + ")`'s!.*!commitlog_directory: %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getSetSavedCachesDirectoryCommand(String dir) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); String program = "sed -i " + conf + " -e `expr $(sed -n '/saved_caches_directory:/=' " + conf + ")`'s!.*!saved_caches_directory: %dir!'"; req.setProgram(program.replace("%dir", dir)); return cmd; } public static CommandImpl getDeleteDataDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/data/*"); return cmd; } public static CommandImpl getDeleteCommitLogDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/commitlog/*"); return cmd; } public static CommandImpl getDeleteSavedCachesDirectoryCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("rm -rf /var/lib/cassandra/saved_caches/*"); return cmd; } public static CommandImpl getSourceEtcProfileUpdateCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram(". /etc/profile"); return cmd; } public static CommandImpl getServiceCassandraStartCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra start"); return cmd; } public static CommandImpl getServiceCassandraStopCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra stop"); return cmd; } public static CommandImpl getServiceCassandraStatusCommand() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("service cassandra status"); return cmd; } public static CommandImpl getAptGetUpdate() { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram("apt-get update"); return cmd; } public CommandImpl getCommand(CassandraCommandEnum cce) { CommandImpl cmd = getTemplate(); Request req = cmd.getRequest(); req.setProgram(cce.getProgram()); return cmd; } }
Fix Cassandra Home variable. Former-commit-id: c78a672a4998cab02e149b1226615f63b71d6535
management/server/ui-modules/cassandra/src/main/java/org/safehaus/kiskis/mgmt/server/ui/modules/cassandra/commands/CassandraCommands.java
Fix Cassandra Home variable.
Java
apache-2.0
ae86b66039555af76214238b1f49aa80cb373e51
0
sarovios/graphdb-benchmarks,amcp/graphdb-benchmarks,orientechnologies/graphdb-benchmarks,changshan/graphdb-benchmarks,socialsensor/graphdb-benchmarks
package eu.socialsensor.benchmarks; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Random; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.Logger; import eu.socialsensor.graphdatabases.GraphDatabase; import eu.socialsensor.graphdatabases.Neo4jGraphDatabase; import eu.socialsensor.graphdatabases.OrientGraphDatabase; import eu.socialsensor.graphdatabases.SparkseeGraphDatabase; import eu.socialsensor.graphdatabases.TitanGraphDatabase; import eu.socialsensor.main.GraphDatabaseBenchmark; import eu.socialsensor.utils.PermuteMethod; import eu.socialsensor.utils.Utils; /** * FindShortestPathBenchmark implementation * @author sotbeis * @email [email protected] */ public class FindShortestPathBenchmark implements Benchmark { private static int SCENARIOS = 24; public static Set<Integer> generatedNodes; private final String resultFile = "QW-FSResults.txt"; private Logger logger = Logger.getLogger(FindShortestPathBenchmark.class); private double[] orientTimes = new double[SCENARIOS]; private double[] titanTimes = new double[SCENARIOS]; private double[] neo4jTimes = new double[SCENARIOS]; private double[] sparkseeTimes = new double[SCENARIOS]; private int titanScenarioCount = 0; private int orientScenarioCount = 0; private int neo4jScenarioCount = 0; private int sparkseeScenarioCount = 0; @Override public void startBenchmark() { logger.setLevel(Level.INFO); logger.info("Executing Find Shortest Path Benchmark . . . ."); Random rand = new Random(); generatedNodes = new HashSet<Integer>(); int max = 300; int min = 2; int numberOfGeneratedNodes = 100; while(generatedNodes.size() < numberOfGeneratedNodes) { int randomNum = rand.nextInt((max - min) +1) + min; generatedNodes.add(randomNum); } Utils utils = new Utils(); Class<FindShortestPathBenchmark> c = FindShortestPathBenchmark.class; Method[] methods = utils.filter(c.getDeclaredMethods(), "FindShortestPathBenchmark"); PermuteMethod permutations = new PermuteMethod(methods); int cntPermutations = 1; while(permutations.hasNext()) { logger.info("Scenario " + cntPermutations++); for(Method permutation : permutations.next()) { try { permutation.invoke(this, null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } } } System.out.println(""); logger.info("Find Shortest Path Benchmark finished"); double meanOrientTime = utils.calculateMean(orientTimes); double meanTitanTime = utils.calculateMean(titanTimes); double meanNeo4jTime = utils.calculateMean(neo4jTimes); double meanSparkseeTime = utils.calculateMean(sparkseeTimes); double varOrientTime = utils.calculateVariance(meanOrientTime, orientTimes); double varTitanTime = utils.calculateVariance(meanTitanTime, titanTimes); double varNeo4jTime = utils.calculateVariance(meanNeo4jTime, neo4jTimes); double varSparkseeTime = utils.calculateVariance(meanSparkseeTime, sparkseeTimes); double stdOrientTime = utils.calculateStdDeviation(varOrientTime); double stdTitanTime = utils.calculateStdDeviation(varTitanTime); double stdNeo4jTime = utils.calculateStdDeviation(varNeo4jTime); double stdSparkseeTime = utils.calculateStdDeviation(varSparkseeTime); String resultsFolder = GraphDatabaseBenchmark.inputPropertiesFile.getProperty("RESULTS_PATH"); String output = resultsFolder+resultFile; System.out.println(""); logger.info("Write results to "+output); try { BufferedWriter out = new BufferedWriter(new FileWriter(output)); out.write("##############################################################"); out.write("\n"); out.write("############ Find Shortest Path Benchmark Results ############"); out.write("\n"); out.write("##############################################################"); out.write("\n"); out.write("\n"); out.write("OrientDB execution time"); out.write("\n"); out.write("Mean Value: "+meanOrientTime); out.write("\n"); out.write("STD Value: "+stdOrientTime); out.write("\n"); out.write("\n"); out.write("Titan execution time"); out.write("\n"); out.write("Mean Value: "+meanTitanTime); out.write("\n"); out.write("STD Value: "+stdTitanTime); out.write("\n"); out.write("\n"); out.write("Neo4j execution time"); out.write("\n"); out.write("Mean Value: "+meanNeo4jTime); out.write("\n"); out.write("STD Value: "+stdNeo4jTime); out.write("\n"); out.write("\n"); out.write("Sparksee execution time"); out.write("\n"); out.write("Mean Value: " + meanSparkseeTime); out.write("\n"); out.write("STD Value: " + stdSparkseeTime); out.write("\n"); out.write("########################################################"); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unused") private void orientFindShortestPathBenchmark() { GraphDatabase orientGraphDatabase = new OrientGraphDatabase(); orientGraphDatabase.open(GraphDatabaseBenchmark.ORIENTDB_PATH); long start = System.currentTimeMillis(); orientGraphDatabase.shorestPathQuery(); long orientTime = System.currentTimeMillis() - start; orientGraphDatabase.shutdown(); orientTimes[orientScenarioCount] = orientTime / 1000.0; orientScenarioCount++; } @SuppressWarnings("unused") private void titanFindShortestPathBenchmark() { GraphDatabase titanGraphDatabase = new TitanGraphDatabase(); titanGraphDatabase.open(GraphDatabaseBenchmark.TITANDB_PATH); long start = System.currentTimeMillis(); titanGraphDatabase.shorestPathQuery(); long titanTime = System.currentTimeMillis() - start; titanGraphDatabase.shutdown(); titanTimes[titanScenarioCount] = titanTime / 1000.0; titanScenarioCount++; } @SuppressWarnings("unused") private void neo4jFindShortestPathBenchmark() { GraphDatabase neo4jGraphDatabase = new Neo4jGraphDatabase(); neo4jGraphDatabase.open(GraphDatabaseBenchmark.NEO4JDB_PATH); long start = System.currentTimeMillis(); neo4jGraphDatabase.shorestPathQuery(); long neo4jTime = System.currentTimeMillis() - start; neo4jGraphDatabase.shutdown(); neo4jTimes[neo4jScenarioCount] = neo4jTime / 1000.0; neo4jScenarioCount++; } @SuppressWarnings("unused") private void sparkseeFindShortestPathBenchmark() { GraphDatabase sparkseeGraphDatabase = new SparkseeGraphDatabase(); sparkseeGraphDatabase.open(GraphDatabaseBenchmark.SPARKSEEDB_PATH); long start = System.currentTimeMillis(); sparkseeGraphDatabase.shorestPathQuery(); long sparkseeTime = System.currentTimeMillis() - start; sparkseeGraphDatabase.shutdown(); sparkseeTimes[sparkseeScenarioCount] = sparkseeTime / 1000.0; sparkseeScenarioCount++; } }
src/eu/socialsensor/benchmarks/FindShortestPathBenchmark.java
package eu.socialsensor.benchmarks; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Random; import java.util.Set; import org.apache.log4j.Level; import org.apache.log4j.Logger; import eu.socialsensor.graphdatabases.GraphDatabase; import eu.socialsensor.graphdatabases.Neo4jGraphDatabase; import eu.socialsensor.graphdatabases.OrientGraphDatabase; import eu.socialsensor.graphdatabases.TitanGraphDatabase; import eu.socialsensor.main.GraphDatabaseBenchmark; import eu.socialsensor.utils.Utils; /** * FindShortestPathBenchmark implementation * @author sotbeis * @email [email protected] */ public class FindShortestPathBenchmark implements Benchmark { public static Set<Integer> generatedNodes; private final String resultFile = "QW-FSResults.txt"; private Logger logger = Logger.getLogger(FindShortestPathBenchmark.class); @Override public void startBenchmark() { logger.setLevel(Level.INFO); logger.info("Executing Find Shortest Path Benchmark . . . ."); Random rand = new Random(); generatedNodes = new HashSet<Integer>(); int max = 300; int min = 2; int numberOfGeneratedNodes = 100; while(generatedNodes.size() < numberOfGeneratedNodes) { int randomNum = rand.nextInt((max - min) +1) + min; generatedNodes.add(randomNum); } double[] orientTimes = new double[6]; double[] titanTimes = new double[6]; double[] neo4jTimes = new double[6]; logger.info("Scenario 1"); orientTimes[0] = orientFindShortestPathBenchmark(); titanTimes[0] = titanFindShortestPathBenchmark(); neo4jTimes[0] = neo4jFindShortestPathBenchmark(); logger.info("Scenario 2"); orientTimes[1] = orientFindShortestPathBenchmark(); neo4jTimes[1] = neo4jFindShortestPathBenchmark(); titanTimes[1] = titanFindShortestPathBenchmark(); logger.info("Scenario 3"); neo4jTimes[2] = neo4jFindShortestPathBenchmark(); orientTimes[2] = orientFindShortestPathBenchmark(); titanTimes[2] = titanFindShortestPathBenchmark(); logger.info("Scenario 4"); neo4jTimes[3] = neo4jFindShortestPathBenchmark(); titanTimes[3] = titanFindShortestPathBenchmark(); orientTimes[3] = orientFindShortestPathBenchmark(); logger.info("Scenario 5"); titanTimes[4] = titanFindShortestPathBenchmark(); neo4jTimes[4] = neo4jFindShortestPathBenchmark(); orientTimes[4] = orientFindShortestPathBenchmark(); logger.info("Scenario 6"); titanTimes[5] = titanFindShortestPathBenchmark(); orientTimes[5] = orientFindShortestPathBenchmark(); neo4jTimes[5] = neo4jFindShortestPathBenchmark(); Utils utils = new Utils(); double meanOrientTime = utils.calculateMean(orientTimes); double meanTitanTime = utils.calculateMean(titanTimes); double meanNeo4jTime = utils.calculateMean(neo4jTimes); double varOrientTime = utils.calculateVariance(meanOrientTime, orientTimes); double varTitanTime = utils.calculateVariance(meanTitanTime, titanTimes); double varNeo4jTime = utils.calculateVariance(meanNeo4jTime, neo4jTimes); double stdOrientTime = utils.calculateStdDeviation(varOrientTime); double stdTitanTime = utils.calculateStdDeviation(varTitanTime); double stdNeo4jTime = utils.calculateStdDeviation(varNeo4jTime); String resultsFolder = GraphDatabaseBenchmark.inputPropertiesFile.getProperty("RESULTS_PATH"); String output = resultsFolder+resultFile; logger.info("Write results to "+output); try { BufferedWriter out = new BufferedWriter(new FileWriter(output)); out.write("##############################################################"); out.write("\n"); out.write("############ Find Shortest Path Benchmark Results ############"); out.write("\n"); out.write("##############################################################"); out.write("\n"); out.write("\n"); out.write("OrientDB execution time"); out.write("\n"); out.write("Mean Value: "+meanOrientTime); out.write("\n"); out.write("STD Value: "+stdOrientTime); out.write("\n"); out.write("\n"); out.write("Titan execution time"); out.write("\n"); out.write("Mean Value: "+meanTitanTime); out.write("\n"); out.write("STD Value: "+stdTitanTime); out.write("\n"); out.write("\n"); out.write("Neo4j execution time"); out.write("\n"); out.write("Mean Value: "+meanNeo4jTime); out.write("\n"); out.write("STD Value: "+stdNeo4jTime); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } private double orientFindShortestPathBenchmark() { GraphDatabase orientGraphDatabase = new OrientGraphDatabase(); orientGraphDatabase.open(GraphDatabaseBenchmark.ORIENTDB_PATH); long start = System.currentTimeMillis(); orientGraphDatabase.shorestPathQuery(); long orientTime = System.currentTimeMillis() - start; orientGraphDatabase.shutdown(); return orientTime/1000.0; } private double titanFindShortestPathBenchmark() { GraphDatabase titanGraphDatabase = new TitanGraphDatabase(); titanGraphDatabase.open(GraphDatabaseBenchmark.TITANDB_PATH); long start = System.currentTimeMillis(); titanGraphDatabase.shorestPathQuery(); long titanTime = System.currentTimeMillis() - start; titanGraphDatabase.shutdown(); return titanTime/1000.0; } private double neo4jFindShortestPathBenchmark() { GraphDatabase neo4jGraphDatabase = new Neo4jGraphDatabase(); neo4jGraphDatabase.open(GraphDatabaseBenchmark.NEO4JDB_PATH); long start = System.currentTimeMillis(); neo4jGraphDatabase.shorestPathQuery(); long neo4jTime = System.currentTimeMillis() - start; neo4jGraphDatabase.shutdown(); return neo4jTime/1000.0; } }
sparksee shortest path benchmark added
src/eu/socialsensor/benchmarks/FindShortestPathBenchmark.java
sparksee shortest path benchmark added
Java
apache-2.0
b5b07af6055925351e0386f2f030b1c12ee5db06
0
mapr/hadoop-common,mapr/hadoop-common,apache/hadoop,mapr/hadoop-common,mapr/hadoop-common,mapr/hadoop-common,JingchengDu/hadoop,apache/hadoop,JingchengDu/hadoop,wwjiang007/hadoop,JingchengDu/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,mapr/hadoop-common,apache/hadoop,apache/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,apache/hadoop,wwjiang007/hadoop,mapr/hadoop-common,wwjiang007/hadoop,apache/hadoop,apache/hadoop,wwjiang007/hadoop
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode.ha; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URI; import java.util.concurrent.TimeUnit; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.hdfs.ClientGSIContext; import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.io.retry.AtMostOnce; import org.apache.hadoop.io.retry.Idempotent; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.io.retry.RetryPolicy.RetryAction; import org.apache.hadoop.ipc.AlignmentContext; import org.apache.hadoop.ipc.Client.ConnectionId; import org.apache.hadoop.ipc.ObserverRetryOnActiveException; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.ipc.RpcInvocationHandler; import org.apache.hadoop.ipc.StandbyException; import org.apache.hadoop.util.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.VisibleForTesting; /** * A {@link org.apache.hadoop.io.retry.FailoverProxyProvider} implementation * that supports reading from observer namenode(s). * * This constructs a wrapper proxy that sends the request to observer * namenode(s), if observer read is enabled. In case there are multiple * observer namenodes, it will try them one by one in case the RPC failed. It * will fail back to the active namenode after it has exhausted all the * observer namenodes. * * Read and write requests will still be sent to active NN if reading from * observer is turned off. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class ObserverReadProxyProvider<T> extends AbstractNNFailoverProxyProvider<T> { @VisibleForTesting static final Logger LOG = LoggerFactory.getLogger( ObserverReadProxyProvider.class); /** Configuration key for {@link #autoMsyncPeriodMs}. */ static final String AUTO_MSYNC_PERIOD_KEY_PREFIX = HdfsClientConfigKeys.Failover.PREFIX + "observer.auto-msync-period"; /** Auto-msync disabled by default. */ static final long AUTO_MSYNC_PERIOD_DEFAULT = -1; /** Client-side context for syncing with the NameNode server side. */ private final AlignmentContext alignmentContext; /** Configuration key for {@link #observerProbeRetryPeriodMs}. */ static final String OBSERVER_PROBE_RETRY_PERIOD_KEY = HdfsClientConfigKeys.Failover.PREFIX + "observer.probe.retry.period"; /** Observer probe retry period default to 10 min. */ static final long OBSERVER_PROBE_RETRY_PERIOD_DEFAULT = 60 * 10 * 1000; /** The inner proxy provider used for active/standby failover. */ private final AbstractNNFailoverProxyProvider<T> failoverProxy; /** List of all NameNode proxies. */ private final List<NNProxyInfo<T>> nameNodeProxies; /** The policy used to determine if an exception is fatal or retriable. */ private final RetryPolicy observerRetryPolicy; /** The combined proxy which redirects to other proxies as necessary. */ private final ProxyInfo<T> combinedProxy; /** * Whether reading from observer is enabled. If this is false, all read * requests will still go to active NN. */ private boolean observerReadEnabled; /** * This adjusts how frequently this proxy provider should auto-msync to the * Active NameNode, automatically performing an msync() call to the active * to fetch the current transaction ID before submitting read requests to * observer nodes. See HDFS-14211 for more description of this feature. * If this is below 0, never auto-msync. If this is 0, perform an msync on * every read operation. If this is above 0, perform an msync after this many * ms have elapsed since the last msync. */ private final long autoMsyncPeriodMs; /** * The time, in millisecond epoch, that the last msync operation was * performed. This includes any implicit msync (any operation which is * serviced by the Active NameNode). */ private volatile long lastMsyncTimeMs = -1; /** * A client using an ObserverReadProxyProvider should first sync with the * active NameNode on startup. This ensures that the client reads data which * is consistent with the state of the world as of the time of its * instantiation. This variable will be true after this initial sync has * been performed. */ private volatile boolean msynced = false; /** * The index into the nameNodeProxies list currently being used. Should only * be accessed in synchronized methods. */ private int currentIndex = -1; /** * The proxy being used currently. Should only be accessed in synchronized * methods. */ private NNProxyInfo<T> currentProxy; /** The last proxy that has been used. Only used for testing. */ private volatile ProxyInfo<T> lastProxy = null; /** * In case there is no Observer node, for every read call, client will try * to loop through all Standby nodes and fail eventually. Since there is no * guarantee on when Observer node will be enabled. This can be very * inefficient. * The following value specify the period on how often to retry all Standby. */ private long observerProbeRetryPeriodMs; /** * The previous time where zero observer were found. If there was observer, * or it is initialization, this is set to 0. */ private long lastObserverProbeTime; /** * By default ObserverReadProxyProvider uses * {@link ConfiguredFailoverProxyProvider} for failover. */ public ObserverReadProxyProvider( Configuration conf, URI uri, Class<T> xface, HAProxyFactory<T> factory) { this(conf, uri, xface, factory, new ConfiguredFailoverProxyProvider<>(conf, uri, xface, factory)); } @SuppressWarnings("unchecked") public ObserverReadProxyProvider( Configuration conf, URI uri, Class<T> xface, HAProxyFactory<T> factory, AbstractNNFailoverProxyProvider<T> failoverProxy) { super(conf, uri, xface, factory); this.failoverProxy = failoverProxy; this.alignmentContext = new ClientGSIContext(); factory.setAlignmentContext(alignmentContext); this.lastObserverProbeTime = 0; // Don't bother configuring the number of retries and such on the retry // policy since it is mainly only used for determining whether or not an // exception is retriable or fatal observerRetryPolicy = RetryPolicies.failoverOnNetworkException( RetryPolicies.TRY_ONCE_THEN_FAIL, 1); // Get all NameNode proxies nameNodeProxies = getProxyAddresses(uri, HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY); // Create a wrapped proxy containing all the proxies. Since this combined // proxy is just redirecting to other proxies, all invocations can share it. StringBuilder combinedInfo = new StringBuilder("["); for (int i = 0; i < nameNodeProxies.size(); i++) { if (i > 0) { combinedInfo.append(","); } combinedInfo.append(nameNodeProxies.get(i).proxyInfo); } combinedInfo.append(']'); T wrappedProxy = (T) Proxy.newProxyInstance( ObserverReadInvocationHandler.class.getClassLoader(), new Class<?>[] {xface}, new ObserverReadInvocationHandler()); combinedProxy = new ProxyInfo<>(wrappedProxy, combinedInfo.toString()); autoMsyncPeriodMs = conf.getTimeDuration( // The host of the URI is the nameservice ID AUTO_MSYNC_PERIOD_KEY_PREFIX + "." + uri.getHost(), AUTO_MSYNC_PERIOD_DEFAULT, TimeUnit.MILLISECONDS); observerProbeRetryPeriodMs = conf.getTimeDuration( OBSERVER_PROBE_RETRY_PERIOD_KEY, OBSERVER_PROBE_RETRY_PERIOD_DEFAULT, TimeUnit.MILLISECONDS); if (wrappedProxy instanceof ClientProtocol) { this.observerReadEnabled = true; } else { LOG.info("Disabling observer reads for {} because the requested proxy " + "class does not implement {}", uri, ClientProtocol.class.getName()); this.observerReadEnabled = false; } } public AlignmentContext getAlignmentContext() { return alignmentContext; } @Override public ProxyInfo<T> getProxy() { return combinedProxy; } @Override public void performFailover(T currentProxy) { failoverProxy.performFailover(currentProxy); } /** * Check if a method is read-only. * * @return whether the 'method' is a read-only operation. */ private static boolean isRead(Method method) { if (!method.isAnnotationPresent(ReadOnly.class)) { return false; } return !method.getAnnotationsByType(ReadOnly.class)[0].activeOnly(); } @VisibleForTesting void setObserverReadEnabled(boolean flag) { this.observerReadEnabled = flag; } @VisibleForTesting ProxyInfo<T> getLastProxy() { return lastProxy; } /** * Return the currently used proxy. If there is none, first calls * {@link #changeProxy(NNProxyInfo)} to initialize one. */ private NNProxyInfo<T> getCurrentProxy() { return changeProxy(null); } /** * Move to the next proxy in the proxy list. If the NNProxyInfo supplied by * the caller does not match the current proxy, the call is ignored; this is * to handle concurrent calls (to avoid changing the proxy multiple times). * The service state of the newly selected proxy will be updated before * returning. * * @param initial The expected current proxy * @return The new proxy that should be used. */ private synchronized NNProxyInfo<T> changeProxy(NNProxyInfo<T> initial) { if (currentProxy != initial) { // Must have been a concurrent modification; ignore the move request return currentProxy; } currentIndex = (currentIndex + 1) % nameNodeProxies.size(); currentProxy = createProxyIfNeeded(nameNodeProxies.get(currentIndex)); currentProxy.setCachedState(getHAServiceState(currentProxy)); LOG.debug("Changed current proxy from {} to {}", initial == null ? "none" : initial.proxyInfo, currentProxy.proxyInfo); return currentProxy; } /** * Fetch the service state from a proxy. If it is unable to be fetched, * assume it is in standby state, but log the exception. */ private HAServiceState getHAServiceState(NNProxyInfo<T> proxyInfo) { IOException ioe; try { return getProxyAsClientProtocol(proxyInfo.proxy).getHAServiceState(); } catch (RemoteException re) { // Though a Standby will allow a getHAServiceState call, it won't allow // delegation token lookup, so if DT is used it throws StandbyException if (re.unwrapRemoteException() instanceof StandbyException) { LOG.debug("NameNode {} threw StandbyException when fetching HAState", proxyInfo.getAddress()); return HAServiceState.STANDBY; } ioe = re; } catch (IOException e) { ioe = e; } if (LOG.isDebugEnabled()) { LOG.debug("Failed to connect to {} while fetching HAServiceState", proxyInfo.getAddress(), ioe); } return null; } /** * Return the input proxy, cast as a {@link ClientProtocol}. This catches any * {@link ClassCastException} and wraps it in a more helpful message. This * should ONLY be called if the caller is certain that the proxy is, in fact, * a {@link ClientProtocol}. */ private ClientProtocol getProxyAsClientProtocol(T proxy) { assert proxy instanceof ClientProtocol : "BUG: Attempted to use proxy " + "of class " + proxy.getClass() + " as if it was a ClientProtocol."; return (ClientProtocol) proxy; } /** * This will call {@link ClientProtocol#msync()} on the active NameNode * (via the {@link #failoverProxy}) to initialize the state of this client. * Calling it multiple times is a no-op; only the first will perform an * msync. * * @see #msynced */ private synchronized void initializeMsync() throws IOException { if (msynced) { return; // No need for an msync } getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); msynced = true; lastMsyncTimeMs = Time.monotonicNow(); } /** * Check if client need to find an Observer proxy. * If current proxy is Active then we should stick to it and postpone probing * for Observers for a period of time. When this time expires the client will * try to find an Observer again. * * * @return true if we did not reach the threshold * to start looking for Observer, or false otherwise. */ private boolean shouldFindObserver() { // lastObserverProbeTime > 0 means we tried, but did not find any // Observers yet // If lastObserverProbeTime <= 0, previous check found observer, so // we should not skip observer read. if (lastObserverProbeTime > 0) { return Time.monotonicNow() - lastObserverProbeTime >= observerProbeRetryPeriodMs; } return true; } /** * This will call {@link ClientProtocol#msync()} on the active NameNode * (via the {@link #failoverProxy}) to update the state of this client, only * if at least {@link #autoMsyncPeriodMs} ms has elapsed since the last time * an msync was performed. * * @see #autoMsyncPeriodMs */ private void autoMsyncIfNecessary() throws IOException { if (autoMsyncPeriodMs == 0) { // Always msync getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); } else if (autoMsyncPeriodMs > 0) { if (Time.monotonicNow() - lastMsyncTimeMs > autoMsyncPeriodMs) { synchronized (this) { // Use a synchronized block so that only one thread will msync // if many operations are submitted around the same time. // Re-check the entry criterion since the status may have changed // while waiting for the lock. if (Time.monotonicNow() - lastMsyncTimeMs > autoMsyncPeriodMs) { getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); lastMsyncTimeMs = Time.monotonicNow(); } } } } } /** * An InvocationHandler to handle incoming requests. This class's invoke * method contains the primary logic for redirecting to observers. * * If observer reads are enabled, attempt to send read operations to the * current proxy. If it is not an observer, or the observer fails, adjust * the current proxy and retry on the next one. If all proxies are tried * without success, the request is forwarded to the active. * * Write requests are always forwarded to the active. */ private class ObserverReadInvocationHandler implements RpcInvocationHandler { @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { lastProxy = null; Object retVal; if (observerReadEnabled && shouldFindObserver() && isRead(method)) { if (!msynced) { // An msync() must first be performed to ensure that this client is // up-to-date with the active's state. This will only be done once. initializeMsync(); } else { autoMsyncIfNecessary(); } int failedObserverCount = 0; int activeCount = 0; int standbyCount = 0; int unreachableCount = 0; for (int i = 0; i < nameNodeProxies.size(); i++) { NNProxyInfo<T> current = getCurrentProxy(); HAServiceState currState = current.getCachedState(); if (currState != HAServiceState.OBSERVER) { if (currState == HAServiceState.ACTIVE) { activeCount++; } else if (currState == HAServiceState.STANDBY) { standbyCount++; } else if (currState == null) { unreachableCount++; } LOG.debug("Skipping proxy {} for {} because it is in state {}", current.proxyInfo, method.getName(), currState == null ? "unreachable" : currState); changeProxy(current); continue; } LOG.debug("Attempting to service {} using proxy {}", method.getName(), current.proxyInfo); try { retVal = method.invoke(current.proxy, args); lastProxy = current; LOG.debug("Invocation of {} using {} was successful", method.getName(), current.proxyInfo); return retVal; } catch (InvocationTargetException ite) { if (!(ite.getCause() instanceof Exception)) { throw ite.getCause(); } Exception e = (Exception) ite.getCause(); if (e instanceof InterruptedIOException || e instanceof InterruptedException) { // If interrupted, do not retry. LOG.warn("Invocation returned interrupted exception on [{}];", current.proxyInfo, e); throw e; } if (e instanceof RemoteException) { RemoteException re = (RemoteException) e; Exception unwrapped = re.unwrapRemoteException( ObserverRetryOnActiveException.class); if (unwrapped instanceof ObserverRetryOnActiveException) { LOG.debug("Encountered ObserverRetryOnActiveException from {}." + " Retry active namenode directly.", current.proxyInfo); break; } } RetryAction retryInfo = observerRetryPolicy.shouldRetry(e, 0, 0, method.isAnnotationPresent(Idempotent.class) || method.isAnnotationPresent(AtMostOnce.class)); if (retryInfo.action == RetryAction.RetryDecision.FAIL) { throw e; } else { failedObserverCount++; LOG.warn( "Invocation returned exception on [{}]; {} failure(s) so far", current.proxyInfo, failedObserverCount, e); changeProxy(current); } } } // Only log message if there are actual observer failures. // Getting here with failedObserverCount = 0 could // be that there is simply no Observer node running at all. if (failedObserverCount > 0) { // If we get here, it means all observers have failed. LOG.warn("{} observers have failed for read request {}; " + "also found {} standby, {} active, and {} unreachable. " + "Falling back to active.", failedObserverCount, method.getName(), standbyCount, activeCount, unreachableCount); lastObserverProbeTime = 0; } else { if (LOG.isDebugEnabled()) { LOG.debug("Read falling back to active without observer read " + "fail, is there no observer node running?"); } lastObserverProbeTime = Time.monotonicNow(); } } // Either all observers have failed, observer reads are disabled, // or this is a write request. In any case, forward the request to // the active NameNode. LOG.debug("Using failoverProxy to service {}", method.getName()); ProxyInfo<T> activeProxy = failoverProxy.getProxy(); try { retVal = method.invoke(activeProxy.proxy, args); } catch (InvocationTargetException e) { // This exception will be handled by higher layers throw e.getCause(); } // If this was reached, the request reached the active, so the // state is up-to-date with active and no further msync is needed. msynced = true; lastMsyncTimeMs = Time.monotonicNow(); lastProxy = activeProxy; return retVal; } @Override public void close() throws IOException {} @Override public ConnectionId getConnectionId() { return RPC.getConnectionIdForProxy(observerReadEnabled ? getCurrentProxy().proxy : failoverProxy.getProxy().proxy); } } @Override public synchronized void close() throws IOException { for (ProxyInfo<T> pi : nameNodeProxies) { if (pi.proxy != null) { if (pi.proxy instanceof Closeable) { ((Closeable)pi.proxy).close(); } else { RPC.stopProxy(pi.proxy); } // Set to null to avoid the failoverProxy having to re-do the close // if it is sharing a proxy instance pi.proxy = null; } } failoverProxy.close(); } @Override public boolean useLogicalURI() { return failoverProxy.useLogicalURI(); } }
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ObserverReadProxyProvider.java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.namenode.ha; import java.io.Closeable; import java.io.IOException; import java.io.InterruptedIOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.URI; import java.util.concurrent.TimeUnit; import java.util.List; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.ha.HAServiceProtocol.HAServiceState; import org.apache.hadoop.hdfs.ClientGSIContext; import org.apache.hadoop.hdfs.client.HdfsClientConfigKeys; import org.apache.hadoop.hdfs.protocol.ClientProtocol; import org.apache.hadoop.io.retry.AtMostOnce; import org.apache.hadoop.io.retry.Idempotent; import org.apache.hadoop.io.retry.RetryPolicies; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.io.retry.RetryPolicy.RetryAction; import org.apache.hadoop.ipc.AlignmentContext; import org.apache.hadoop.ipc.Client.ConnectionId; import org.apache.hadoop.ipc.ObserverRetryOnActiveException; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.ipc.RemoteException; import org.apache.hadoop.ipc.RpcInvocationHandler; import org.apache.hadoop.ipc.StandbyException; import org.apache.hadoop.util.Time; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.classification.VisibleForTesting; /** * A {@link org.apache.hadoop.io.retry.FailoverProxyProvider} implementation * that supports reading from observer namenode(s). * * This constructs a wrapper proxy that sends the request to observer * namenode(s), if observer read is enabled. In case there are multiple * observer namenodes, it will try them one by one in case the RPC failed. It * will fail back to the active namenode after it has exhausted all the * observer namenodes. * * Read and write requests will still be sent to active NN if reading from * observer is turned off. */ @InterfaceAudience.Private @InterfaceStability.Evolving public class ObserverReadProxyProvider<T> extends AbstractNNFailoverProxyProvider<T> { @VisibleForTesting static final Logger LOG = LoggerFactory.getLogger( ObserverReadProxyProvider.class); /** Configuration key for {@link #autoMsyncPeriodMs}. */ static final String AUTO_MSYNC_PERIOD_KEY_PREFIX = HdfsClientConfigKeys.Failover.PREFIX + "observer.auto-msync-period"; /** Auto-msync disabled by default. */ static final long AUTO_MSYNC_PERIOD_DEFAULT = -1; /** Client-side context for syncing with the NameNode server side. */ private final AlignmentContext alignmentContext; /** Configuration key for {@link #observerProbeRetryPeriodMs}. */ static final String OBSERVER_PROBE_RETRY_PERIOD_KEY = HdfsClientConfigKeys.Failover.PREFIX + "observer.probe.retry.period"; /** Observer probe retry period default to 10 min. */ static final long OBSERVER_PROBE_RETRY_PERIOD_DEFAULT = 60 * 10 * 1000; /** The inner proxy provider used for active/standby failover. */ private final AbstractNNFailoverProxyProvider<T> failoverProxy; /** List of all NameNode proxies. */ private final List<NNProxyInfo<T>> nameNodeProxies; /** The policy used to determine if an exception is fatal or retriable. */ private final RetryPolicy observerRetryPolicy; /** The combined proxy which redirects to other proxies as necessary. */ private final ProxyInfo<T> combinedProxy; /** * Whether reading from observer is enabled. If this is false, all read * requests will still go to active NN. */ private boolean observerReadEnabled; /** * This adjusts how frequently this proxy provider should auto-msync to the * Active NameNode, automatically performing an msync() call to the active * to fetch the current transaction ID before submitting read requests to * observer nodes. See HDFS-14211 for more description of this feature. * If this is below 0, never auto-msync. If this is 0, perform an msync on * every read operation. If this is above 0, perform an msync after this many * ms have elapsed since the last msync. */ private final long autoMsyncPeriodMs; /** * The time, in millisecond epoch, that the last msync operation was * performed. This includes any implicit msync (any operation which is * serviced by the Active NameNode). */ private volatile long lastMsyncTimeMs = -1; /** * A client using an ObserverReadProxyProvider should first sync with the * active NameNode on startup. This ensures that the client reads data which * is consistent with the state of the world as of the time of its * instantiation. This variable will be true after this initial sync has * been performed. */ private volatile boolean msynced = false; /** * The index into the nameNodeProxies list currently being used. Should only * be accessed in synchronized methods. */ private int currentIndex = -1; /** * The proxy being used currently. Should only be accessed in synchronized * methods. */ private NNProxyInfo<T> currentProxy; /** The last proxy that has been used. Only used for testing. */ private volatile ProxyInfo<T> lastProxy = null; /** * In case there is no Observer node, for every read call, client will try * to loop through all Standby nodes and fail eventually. Since there is no * guarantee on when Observer node will be enabled. This can be very * inefficient. * The following value specify the period on how often to retry all Standby. */ private long observerProbeRetryPeriodMs; /** * The previous time where zero observer were found. If there was observer, * or it is initialization, this is set to 0. */ private long lastObserverProbeTime; /** * By default ObserverReadProxyProvider uses * {@link ConfiguredFailoverProxyProvider} for failover. */ public ObserverReadProxyProvider( Configuration conf, URI uri, Class<T> xface, HAProxyFactory<T> factory) { this(conf, uri, xface, factory, new ConfiguredFailoverProxyProvider<>(conf, uri, xface, factory)); } @SuppressWarnings("unchecked") public ObserverReadProxyProvider( Configuration conf, URI uri, Class<T> xface, HAProxyFactory<T> factory, AbstractNNFailoverProxyProvider<T> failoverProxy) { super(conf, uri, xface, factory); this.failoverProxy = failoverProxy; this.alignmentContext = new ClientGSIContext(); factory.setAlignmentContext(alignmentContext); this.lastObserverProbeTime = 0; // Don't bother configuring the number of retries and such on the retry // policy since it is mainly only used for determining whether or not an // exception is retriable or fatal observerRetryPolicy = RetryPolicies.failoverOnNetworkException( RetryPolicies.TRY_ONCE_THEN_FAIL, 1); // Get all NameNode proxies nameNodeProxies = getProxyAddresses(uri, HdfsClientConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY); // Create a wrapped proxy containing all the proxies. Since this combined // proxy is just redirecting to other proxies, all invocations can share it. StringBuilder combinedInfo = new StringBuilder("["); for (int i = 0; i < nameNodeProxies.size(); i++) { if (i > 0) { combinedInfo.append(","); } combinedInfo.append(nameNodeProxies.get(i).proxyInfo); } combinedInfo.append(']'); T wrappedProxy = (T) Proxy.newProxyInstance( ObserverReadInvocationHandler.class.getClassLoader(), new Class<?>[] {xface}, new ObserverReadInvocationHandler()); combinedProxy = new ProxyInfo<>(wrappedProxy, combinedInfo.toString()); autoMsyncPeriodMs = conf.getTimeDuration( // The host of the URI is the nameservice ID AUTO_MSYNC_PERIOD_KEY_PREFIX + "." + uri.getHost(), AUTO_MSYNC_PERIOD_DEFAULT, TimeUnit.MILLISECONDS); observerProbeRetryPeriodMs = conf.getTimeDuration( OBSERVER_PROBE_RETRY_PERIOD_KEY, OBSERVER_PROBE_RETRY_PERIOD_DEFAULT, TimeUnit.MILLISECONDS); // TODO : make this configurable or remove this variable if (wrappedProxy instanceof ClientProtocol) { this.observerReadEnabled = true; } else { LOG.info("Disabling observer reads for {} because the requested proxy " + "class does not implement {}", uri, ClientProtocol.class.getName()); this.observerReadEnabled = false; } } public AlignmentContext getAlignmentContext() { return alignmentContext; } @Override public ProxyInfo<T> getProxy() { return combinedProxy; } @Override public void performFailover(T currentProxy) { failoverProxy.performFailover(currentProxy); } /** * Check if a method is read-only. * * @return whether the 'method' is a read-only operation. */ private static boolean isRead(Method method) { if (!method.isAnnotationPresent(ReadOnly.class)) { return false; } return !method.getAnnotationsByType(ReadOnly.class)[0].activeOnly(); } @VisibleForTesting void setObserverReadEnabled(boolean flag) { this.observerReadEnabled = flag; } @VisibleForTesting ProxyInfo<T> getLastProxy() { return lastProxy; } /** * Return the currently used proxy. If there is none, first calls * {@link #changeProxy(NNProxyInfo)} to initialize one. */ private NNProxyInfo<T> getCurrentProxy() { return changeProxy(null); } /** * Move to the next proxy in the proxy list. If the NNProxyInfo supplied by * the caller does not match the current proxy, the call is ignored; this is * to handle concurrent calls (to avoid changing the proxy multiple times). * The service state of the newly selected proxy will be updated before * returning. * * @param initial The expected current proxy * @return The new proxy that should be used. */ private synchronized NNProxyInfo<T> changeProxy(NNProxyInfo<T> initial) { if (currentProxy != initial) { // Must have been a concurrent modification; ignore the move request return currentProxy; } currentIndex = (currentIndex + 1) % nameNodeProxies.size(); currentProxy = createProxyIfNeeded(nameNodeProxies.get(currentIndex)); currentProxy.setCachedState(getHAServiceState(currentProxy)); LOG.debug("Changed current proxy from {} to {}", initial == null ? "none" : initial.proxyInfo, currentProxy.proxyInfo); return currentProxy; } /** * Fetch the service state from a proxy. If it is unable to be fetched, * assume it is in standby state, but log the exception. */ private HAServiceState getHAServiceState(NNProxyInfo<T> proxyInfo) { IOException ioe; try { return getProxyAsClientProtocol(proxyInfo.proxy).getHAServiceState(); } catch (RemoteException re) { // Though a Standby will allow a getHAServiceState call, it won't allow // delegation token lookup, so if DT is used it throws StandbyException if (re.unwrapRemoteException() instanceof StandbyException) { LOG.debug("NameNode {} threw StandbyException when fetching HAState", proxyInfo.getAddress()); return HAServiceState.STANDBY; } ioe = re; } catch (IOException e) { ioe = e; } if (LOG.isDebugEnabled()) { LOG.debug("Failed to connect to {} while fetching HAServiceState", proxyInfo.getAddress(), ioe); } return null; } /** * Return the input proxy, cast as a {@link ClientProtocol}. This catches any * {@link ClassCastException} and wraps it in a more helpful message. This * should ONLY be called if the caller is certain that the proxy is, in fact, * a {@link ClientProtocol}. */ private ClientProtocol getProxyAsClientProtocol(T proxy) { assert proxy instanceof ClientProtocol : "BUG: Attempted to use proxy " + "of class " + proxy.getClass() + " as if it was a ClientProtocol."; return (ClientProtocol) proxy; } /** * This will call {@link ClientProtocol#msync()} on the active NameNode * (via the {@link #failoverProxy}) to initialize the state of this client. * Calling it multiple times is a no-op; only the first will perform an * msync. * * @see #msynced */ private synchronized void initializeMsync() throws IOException { if (msynced) { return; // No need for an msync } getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); msynced = true; lastMsyncTimeMs = Time.monotonicNow(); } /** * Check if client need to find an Observer proxy. * If current proxy is Active then we should stick to it and postpone probing * for Observers for a period of time. When this time expires the client will * try to find an Observer again. * * * @return true if we did not reach the threshold * to start looking for Observer, or false otherwise. */ private boolean shouldFindObserver() { // lastObserverProbeTime > 0 means we tried, but did not find any // Observers yet // If lastObserverProbeTime <= 0, previous check found observer, so // we should not skip observer read. if (lastObserverProbeTime > 0) { return Time.monotonicNow() - lastObserverProbeTime >= observerProbeRetryPeriodMs; } return true; } /** * This will call {@link ClientProtocol#msync()} on the active NameNode * (via the {@link #failoverProxy}) to update the state of this client, only * if at least {@link #autoMsyncPeriodMs} ms has elapsed since the last time * an msync was performed. * * @see #autoMsyncPeriodMs */ private void autoMsyncIfNecessary() throws IOException { if (autoMsyncPeriodMs == 0) { // Always msync getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); } else if (autoMsyncPeriodMs > 0) { if (Time.monotonicNow() - lastMsyncTimeMs > autoMsyncPeriodMs) { synchronized (this) { // Use a synchronized block so that only one thread will msync // if many operations are submitted around the same time. // Re-check the entry criterion since the status may have changed // while waiting for the lock. if (Time.monotonicNow() - lastMsyncTimeMs > autoMsyncPeriodMs) { getProxyAsClientProtocol(failoverProxy.getProxy().proxy).msync(); lastMsyncTimeMs = Time.monotonicNow(); } } } } } /** * An InvocationHandler to handle incoming requests. This class's invoke * method contains the primary logic for redirecting to observers. * * If observer reads are enabled, attempt to send read operations to the * current proxy. If it is not an observer, or the observer fails, adjust * the current proxy and retry on the next one. If all proxies are tried * without success, the request is forwarded to the active. * * Write requests are always forwarded to the active. */ private class ObserverReadInvocationHandler implements RpcInvocationHandler { @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { lastProxy = null; Object retVal; if (observerReadEnabled && shouldFindObserver() && isRead(method)) { if (!msynced) { // An msync() must first be performed to ensure that this client is // up-to-date with the active's state. This will only be done once. initializeMsync(); } else { autoMsyncIfNecessary(); } int failedObserverCount = 0; int activeCount = 0; int standbyCount = 0; int unreachableCount = 0; for (int i = 0; i < nameNodeProxies.size(); i++) { NNProxyInfo<T> current = getCurrentProxy(); HAServiceState currState = current.getCachedState(); if (currState != HAServiceState.OBSERVER) { if (currState == HAServiceState.ACTIVE) { activeCount++; } else if (currState == HAServiceState.STANDBY) { standbyCount++; } else if (currState == null) { unreachableCount++; } LOG.debug("Skipping proxy {} for {} because it is in state {}", current.proxyInfo, method.getName(), currState == null ? "unreachable" : currState); changeProxy(current); continue; } LOG.debug("Attempting to service {} using proxy {}", method.getName(), current.proxyInfo); try { retVal = method.invoke(current.proxy, args); lastProxy = current; LOG.debug("Invocation of {} using {} was successful", method.getName(), current.proxyInfo); return retVal; } catch (InvocationTargetException ite) { if (!(ite.getCause() instanceof Exception)) { throw ite.getCause(); } Exception e = (Exception) ite.getCause(); if (e instanceof InterruptedIOException || e instanceof InterruptedException) { // If interrupted, do not retry. LOG.warn("Invocation returned interrupted exception on [{}];", current.proxyInfo, e); throw e; } if (e instanceof RemoteException) { RemoteException re = (RemoteException) e; Exception unwrapped = re.unwrapRemoteException( ObserverRetryOnActiveException.class); if (unwrapped instanceof ObserverRetryOnActiveException) { LOG.debug("Encountered ObserverRetryOnActiveException from {}." + " Retry active namenode directly.", current.proxyInfo); break; } } RetryAction retryInfo = observerRetryPolicy.shouldRetry(e, 0, 0, method.isAnnotationPresent(Idempotent.class) || method.isAnnotationPresent(AtMostOnce.class)); if (retryInfo.action == RetryAction.RetryDecision.FAIL) { throw e; } else { failedObserverCount++; LOG.warn( "Invocation returned exception on [{}]; {} failure(s) so far", current.proxyInfo, failedObserverCount, e); changeProxy(current); } } } // Only log message if there are actual observer failures. // Getting here with failedObserverCount = 0 could // be that there is simply no Observer node running at all. if (failedObserverCount > 0) { // If we get here, it means all observers have failed. LOG.warn("{} observers have failed for read request {}; " + "also found {} standby, {} active, and {} unreachable. " + "Falling back to active.", failedObserverCount, method.getName(), standbyCount, activeCount, unreachableCount); lastObserverProbeTime = 0; } else { if (LOG.isDebugEnabled()) { LOG.debug("Read falling back to active without observer read " + "fail, is there no observer node running?"); } lastObserverProbeTime = Time.monotonicNow(); } } // Either all observers have failed, observer reads are disabled, // or this is a write request. In any case, forward the request to // the active NameNode. LOG.debug("Using failoverProxy to service {}", method.getName()); ProxyInfo<T> activeProxy = failoverProxy.getProxy(); try { retVal = method.invoke(activeProxy.proxy, args); } catch (InvocationTargetException e) { // This exception will be handled by higher layers throw e.getCause(); } // If this was reached, the request reached the active, so the // state is up-to-date with active and no further msync is needed. msynced = true; lastMsyncTimeMs = Time.monotonicNow(); lastProxy = activeProxy; return retVal; } @Override public void close() throws IOException {} @Override public ConnectionId getConnectionId() { return RPC.getConnectionIdForProxy(observerReadEnabled ? getCurrentProxy().proxy : failoverProxy.getProxy().proxy); } } @Override public synchronized void close() throws IOException { for (ProxyInfo<T> pi : nameNodeProxies) { if (pi.proxy != null) { if (pi.proxy instanceof Closeable) { ((Closeable)pi.proxy).close(); } else { RPC.stopProxy(pi.proxy); } // Set to null to avoid the failoverProxy having to re-do the close // if it is sharing a proxy instance pi.proxy = null; } } failoverProxy.close(); } @Override public boolean useLogicalURI() { return failoverProxy.useLogicalURI(); } }
HDFS-16435. Remove no need TODO comment for ObserverReadProxyProvider (#3912). Contributed by tomscut. Reviewed-by: Chao Sun <[email protected]> Signed-off-by: Ayush Saxena <[email protected]>
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/namenode/ha/ObserverReadProxyProvider.java
HDFS-16435. Remove no need TODO comment for ObserverReadProxyProvider (#3912). Contributed by tomscut.
Java
apache-2.0
bccaf074973278ed62573577cad9c3d5fdb8e320
0
anuraaga/grpc-java,ejona86/grpc-java,huangsihuan/grpc-java,simonhorlick/grpc-java,huangsihuan/grpc-java,stanley-cheung/grpc-java,elandau/grpc-java,wrwg/grpc-java,dapengzhang0/grpc-java,stanley-cheung/grpc-java,dapengzhang0/grpc-java,rmichela/grpc-java,wrwg/grpc-java,ejona86/grpc-java,joshuabezaleel/grpc-java,pieterjanpintens/grpc-java,nmittler/grpc-java,elandau/grpc-java,carl-mastrangelo/grpc-java,carl-mastrangelo/grpc-java,nmittler/grpc-java,pieterjanpintens/grpc-java,wrwg/grpc-java,eonezhang/grpc-java,eonezhang/grpc-java,anuraaga/grpc-java,pieterjanpintens/grpc-java,simonhorlick/grpc-java,eonezhang/grpc-java,eamonnmcmanus/grpc-java,simonhorlick/grpc-java,pieterjanpintens/grpc-java,elandau/grpc-java,eamonnmcmanus/grpc-java,louiscryan/grpc-java,louiscryan/grpc-java,ejona86/grpc-java,ejona86/grpc-java,rmichela/grpc-java,zpencer/grpc-java,huangsihuan/grpc-java,rmichela/grpc-java,zhangkun83/grpc-java,madongfly/grpc-java,LuminateWireless/grpc-java,grpc/grpc-java,carl-mastrangelo/grpc-java,grpc/grpc-java,dapengzhang0/grpc-java,zhangkun83/grpc-java,carl-mastrangelo/grpc-java,anuraaga/grpc-java,dapengzhang0/grpc-java,grpc/grpc-java,nmittler/grpc-java,madongfly/grpc-java,joshuabezaleel/grpc-java,madongfly/grpc-java,elandau/grpc-java,eamonnmcmanus/grpc-java,LuminateWireless/grpc-java,LuminateWireless/grpc-java,louiscryan/grpc-java,simonhorlick/grpc-java,grpc/grpc-java,zpencer/grpc-java,joshuabezaleel/grpc-java,zpencer/grpc-java,stanley-cheung/grpc-java,zpencer/grpc-java,zhangkun83/grpc-java,zhangkun83/grpc-java,rmichela/grpc-java,stanley-cheung/grpc-java
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.auth; import com.google.auth.Credentials; import com.google.common.base.Preconditions; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ClientInterceptors.CheckedForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.StatusException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; /** * Client interceptor that authenticates all calls by binding header data provided by a credential. * Typically this will populate the Authorization header but other headers may also be filled out. * * <p> Uses the new and simplified Google auth library: * https://github.com/google/google-auth-library-java */ public final class ClientAuthInterceptor implements ClientInterceptor { private final Credentials credentials; private Metadata cached; private Map<String, List<String>> lastMetadata; // TODO(louiscryan): refresh token asynchronously with this executor. private Executor executor; public ClientAuthInterceptor(Credentials credentials, Executor executor) { this.credentials = Preconditions.checkNotNull(credentials); this.executor = Preconditions.checkNotNull(executor); } @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) { // TODO(ejona86): If the call fails for Auth reasons, this does not properly propagate info that // would be in WWW-Authenticate, because it does not yet have access to the header. return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException { Metadata cachedSaved; URI uri = serviceUri(next, method); synchronized (ClientAuthInterceptor.this) { // TODO(louiscryan): This is icky but the current auth library stores the same // metadata map until the next refresh cycle. This will be fixed once // https://github.com/google/google-auth-library-java/issues/3 // is resolved. // getRequestMetadata() may return a different map based on the provided URI, i.e., for // JWT. However, today it does not cache JWT and so we won't bother tring to cache its // return value based on the URI. Map<String, List<String>> latestMetadata = getRequestMetadata(uri); if (lastMetadata == null || lastMetadata != latestMetadata) { lastMetadata = latestMetadata; cached = toHeaders(lastMetadata); } cachedSaved = cached; } headers.merge(cachedSaved); delegate().start(responseListener, headers); } }; } /** * Generate a JWT-specific service URI. The URI is simply an identifier with enough information * for a service to know that the JWT was intended for it. The URI will commonly be verified with * a simple string equality check. */ private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException { String authority = channel.authority(); if (authority == null) { throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException(); } // Always use HTTPS, by definition. final String scheme = "https"; final int defaultPort = 443; String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName()); URI uri; try { uri = new URI(scheme, authority, path, null, null); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth") .withCause(e).asException(); } // The default port must not be present. Alternative ports should be present. if (uri.getPort() == defaultPort) { uri = removePort(uri); } return uri; } private URI removePort(URI uri) throws StatusException { try { return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), -1 /* port */, uri.getPath(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED.withDescription( "Unable to construct service URI after removing port") .withCause(e).asException(); } } private Map<String, List<String>> getRequestMetadata(URI uri) throws StatusException { try { return credentials.getRequestMetadata(uri); } catch (IOException e) { throw Status.UNAUTHENTICATED.withCause(e).asException(); } } private static final Metadata toHeaders(Map<String, List<String>> metadata) { Metadata headers = new Metadata(); if (metadata != null) { for (String key : metadata.keySet()) { Metadata.Key<String> headerKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER); for (String value : metadata.get(key)) { headers.put(headerKey, value); } } } return headers; } }
auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java
/* * Copyright 2014, Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.grpc.auth; import com.google.auth.Credentials; import com.google.common.base.Preconditions; import io.grpc.CallOptions; import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ClientInterceptors.CheckedForwardingClientCall; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.StatusException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; import java.util.concurrent.Executor; /** * Client interceptor that authenticates all calls by binding header data provided by a credential. * Typically this will populate the Authorization header but other headers may also be filled out. * * <p> Uses the new and simplified Google auth library: * https://github.com/google/google-auth-library-java */ public final class ClientAuthInterceptor implements ClientInterceptor { private final Credentials credentials; private Metadata cached; private Map<String, List<String>> lastMetadata; // TODO(louiscryan): refresh token asynchronously with this executor. private Executor executor; public ClientAuthInterceptor(Credentials credentials, Executor executor) { this.credentials = Preconditions.checkNotNull(credentials); this.executor = Preconditions.checkNotNull(executor); } @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall( final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) { // TODO(ejona86): If the call fails for Auth reasons, this does not properly propagate info that // would be in WWW-Authenticate, because it does not yet have access to the header. return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) { @Override protected void checkedStart(Listener<RespT> responseListener, Metadata headers) throws StatusException { Metadata cachedSaved; URI uri = serviceUri(next, method); synchronized (ClientAuthInterceptor.this) { // TODO(louiscryan): This is icky but the current auth library stores the same // metadata map until the next refresh cycle. This will be fixed once // https://github.com/google/google-auth-library-java/issues/3 // is resolved. // getRequestMetadata() may return a different map based on the provided URI, i.e., for // JWT. However, today it does not cache JWT and so we won't bother tring to cache its // return value based on the URI. Map<String, List<String>> latestMetadata = getRequestMetadata(uri); if (lastMetadata == null || lastMetadata != latestMetadata) { lastMetadata = latestMetadata; cached = toHeaders(lastMetadata); } cachedSaved = cached; } headers.merge(cachedSaved); delegate().start(responseListener, headers); } }; } /** * Generate a JWT-specific service URI. The URI is simply an identifier with enough information * for a service to know that the JWT was intended for it. The URI will commonly be verified with * a simple string equality check. */ private URI serviceUri(Channel channel, MethodDescriptor<?, ?> method) throws StatusException { String authority = channel.authority(); if (authority == null) { throw Status.UNAUTHENTICATED.withDescription("Channel has no authority").asException(); } // Always use HTTPS, by definition. final String scheme = "https"; // The default port must not be present. Alternative ports should be present. final String suffixToStrip = ":443"; if (authority.endsWith(suffixToStrip)) { authority = authority.substring(0, authority.length() - suffixToStrip.length()); } String path = "/" + MethodDescriptor.extractFullServiceName(method.getFullMethodName()); try { return new URI(scheme, authority, path, null, null); } catch (URISyntaxException e) { throw Status.UNAUTHENTICATED.withDescription("Unable to construct service URI for auth") .withCause(e).asException(); } } private Map<String, List<String>> getRequestMetadata(URI uri) throws StatusException { try { return credentials.getRequestMetadata(uri); } catch (IOException e) { throw Status.UNAUTHENTICATED.withCause(e).asException(); } } private static final Metadata toHeaders(Map<String, List<String>> metadata) { Metadata headers = new Metadata(); if (metadata != null) { for (String key : metadata.keySet()) { Metadata.Key<String> headerKey = Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER); for (String value : metadata.get(key)) { headers.put(headerKey, value); } } } return headers; } }
Use real authority parsing in ClientAuthInterceptor
auth/src/main/java/io/grpc/auth/ClientAuthInterceptor.java
Use real authority parsing in ClientAuthInterceptor
Java
apache-2.0
83abf2fbce721ce776e0494e48a6998402ca5459
0
rswijesena/product-apim,ChamNDeSilva/product-apim,dewmini/product-apim,chamilaadhi/product-apim,pradeepmurugesan/product-apim,thilinicooray/product-apim,hevayo/product-apim,jaadds/product-apim,hevayo/product-apim,hevayo/product-apim,jaadds/product-apim,thilinicooray/product-apim,wso2/product-apim,nu1silva/product-apim,thilinicooray/product-apim,tharikaGitHub/product-apim,wso2/product-apim,nu1silva/product-apim,hevayo/product-apim,chamilaadhi/product-apim,nu1silva/product-apim,nu1silva/product-apim,dewmini/product-apim,thilinicooray/product-apim,ChamNDeSilva/product-apim,dewmini/product-apim,irhamiqbal/product-apim,tharikaGitHub/product-apim,dewmini/product-apim,chamilaadhi/product-apim,tharikaGitHub/product-apim,dewmini/product-apim,nu1silva/product-apim,abimarank/product-apim,chamilaadhi/product-apim,jaadds/product-apim,tharindu1st/product-apim,wso2/product-apim,tharikaGitHub/product-apim,sambaheerathan/product-apim,abimarank/product-apim,lakmali/product-apim,chamilaadhi/product-apim,wso2/product-apim,irhamiqbal/product-apim,pradeepmurugesan/product-apim,sambaheerathan/product-apim,lakmali/product-apim,irhamiqbal/product-apim,rswijesena/product-apim,irhamiqbal/product-apim,wso2/product-apim,jaadds/product-apim,pradeepmurugesan/product-apim,tharikaGitHub/product-apim,pradeepmurugesan/product-apim
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.am.integration.tests.other; import com.google.common.io.Files; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.json.JSONArray; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.bean.APILifeCycleState; import org.wso2.am.integration.test.utils.bean.APILifeCycleStateRequest; import org.wso2.am.integration.test.utils.bean.APIResourceBean; import org.wso2.am.integration.test.utils.bean.APIThrottlingTier; import org.wso2.am.integration.test.utils.bean.APPKeyRequestGenerator; import org.wso2.am.integration.test.utils.bean.SubscriptionRequest; import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; import org.wso2.am.integration.test.utils.http.HTTPSClientUtils; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This test case is used to test the API Manager Import Export tool */ @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) public class APIImportExportTestCase extends APIMIntegrationBaseTest { private final Log log = LogFactory.getLog(APIImportExportTestCase.class); private final String API_NAME = "APIImportExportTestCaseAPIName"; private final String NEW_API_NAME = "NewAPIImportExportTestCaseAPIName"; private final String PRESERVE_PUBLISHER_API_NAME = "preserveNewAPIImportExportAPIName"; private final String NOT_PRESERVE_PUBLISHER_API_NAME = "notPreserveNewAPIImportExportAPIName"; private final String PRESERVE_PUBLISHER_API_CONTEXT = "preserveAPIImportExportContext"; private final String NOT_PRESERVE_PUBLISHER_API_CONTEXT = "notPreserveAPIImportExportContext"; private final String API_CONTEXT = "APIImportExportTestCaseContext"; private final String NEW_API_CONTEXT = "NewAPIImportExportTestCaseContext"; private final String ALLOWED_ROLE = "allowedRole"; private final String VISIBILITY_ROLE = "visibilityRole"; private final String NOT_ALLOWED_ROLE = "denyRole"; private final String ADMIN_ROLE = "admin"; private final String[] PERMISSIONS = { "/permission/admin/login", "/permission/admin/manage/api/subscribe" }; private final char[] ALLOWED_USER_PASS = "pass@123".toCharArray(); private final char[] DENIED_USER_PASS = "pass@123".toCharArray(); private final char[] PUBLISHER_USER_PASS = "pass@123".toCharArray(); private final String SCOPE_NAME = "ImportExportScope"; private final String TAG1 = "import"; private final String TAG2 = "export"; private final String TAG3 = "test"; private final String DESCRIPTION = "This is test API create by API manager integration test"; private final String API_VERSION = "1.0.0"; private final String APP_NAME = "APIImportExportTestCaseApp"; private final String NEW_APP_NAME = "newAPIImportExportTestCaseApp"; private String allowedUser = "allowedUser"; private String deniedUser = "deniedUser"; private String publisherUser = "importExportPublisher"; private String publisherURLHttps; private String storeURLHttp; private File zipTempDir, apiZip, newApiZip, preservePublisherApiZip, notPreservePublisherApiZip; private String importUrl; private String exportUrl; private APICreationRequestBean apiCreationRequestBean; private List<APIResourceBean> resList; private String tags; private String tierCollection; private String endpointUrl; private Map<String, String> requestHeaders = new HashMap<String, String>(); private APIPublisherRestClient apiPublisher; private APIStoreRestClient apiStore; @Factory(dataProvider = "userModeDataProvider") public APIImportExportTestCase(TestUserMode userMode) { this.userMode = userMode; } @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(userMode); publisherURLHttps = publisherUrls.getWebAppURLHttps(); storeURLHttp = getStoreURLHttp(); endpointUrl = backEndServerUrl.getWebAppURLHttp() + "am/sample/calculator/v1/api"; apiPublisher = new APIPublisherRestClient(publisherURLHttps); apiPublisher.login(user.getUserName(), user.getPassword()); //concat tags tags = TAG1 + "," + TAG2 + "," + TAG3; tierCollection = APIMIntegrationConstants.API_TIER.BRONZE + "," + APIMIntegrationConstants.API_TIER.GOLD + "," + APIMIntegrationConstants.API_TIER.SILVER + "," + APIMIntegrationConstants.API_TIER.UNLIMITED; importUrl = publisherURLHttps + APIMIntegrationConstants.AM_IMPORT_EXPORT_WEB_APP_NAME + "/import-api"; exportUrl = publisherURLHttps + APIMIntegrationConstants.AM_IMPORT_EXPORT_WEB_APP_NAME + "/export-api"; //adding new 3 roles and two users userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(), createSession(keyManagerContext)); userManagementClient.addRole(ALLOWED_ROLE, null, PERMISSIONS); userManagementClient.addRole(NOT_ALLOWED_ROLE, null, PERMISSIONS); userManagementClient.addRole(VISIBILITY_ROLE, null, PERMISSIONS); userManagementClient .addUser(allowedUser, String.valueOf(ALLOWED_USER_PASS), new String[] { ALLOWED_ROLE, VISIBILITY_ROLE }, null); userManagementClient.addUser(deniedUser, String.valueOf(DENIED_USER_PASS), new String[] { NOT_ALLOWED_ROLE, VISIBILITY_ROLE }, null); userManagementClient .addUser(publisherUser, String.valueOf(PUBLISHER_USER_PASS), new String[] { ADMIN_ROLE }, null); if (!keyManagerContext.getContextTenant().getDomain().equals("carbon.super")) { allowedUser = allowedUser + "@" + keyManagerContext.getContextTenant().getDomain(); deniedUser = deniedUser + "@" + keyManagerContext.getContextTenant().getDomain(); publisherUser = publisherUser + "@" + keyManagerContext.getContextTenant().getDomain(); } } @Test(groups = { "wso2.am" }, description = "Sample API creation") public void testAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean res1 = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); APIResourceBean res2 = new APIResourceBean("GET", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/get"); APIResourceBean res3 = new APIResourceBean("PUT", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION_USER.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.ULTIMATE, "/put"); APIResourceBean res4 = new APIResourceBean("DELETE", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION_AND_APPLICATION_USER.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.UNLIMITED, "/delete"); APIResourceBean res5 = new APIResourceBean("PATCH", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/patch"); APIResourceBean res6 = new APIResourceBean("HEAD", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/head"); APIResourceBean res7 = new APIResourceBean("OPTIONS", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/options"); resList.add(res1); resList.add(res2); resList.add(res3); resList.add(res4); resList.add(res5); resList.add(res6); resList.add(res7); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testAPICreation") public void testAPIExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + API_NAME + "&version=" + API_VERSION + "&provider=" + user.getUserName()); zipTempDir = Files.createTempDir(); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + API_NAME; apiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, apiZip); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testAPIExport") public void testAPIImport() throws Exception { //delete exported API before import HttpResponse serviceResponse = apiPublisher.deleteAPI(API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //upload the exported zip importAPI(importUrl, apiZip, user.getUserName(), user.getPassword().toCharArray()); } @Test(groups = { "wso2.am" }, description = "Checking status of the imported API", dependsOnMethods = "testAPIImport") public void testAPIState() throws Exception { //get the imported API information HttpResponse response = apiPublisher.getAPI(API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String state = apiObj.getString("status"); Assert.assertEquals(state, APILifeCycleState.CREATED.getState(), "Imported API not in Created state"); Assert.assertEquals(API_NAME, apiObj.getString("name"), "Imported API Name is incorrect"); Assert.assertEquals(API_VERSION, apiObj.getString("version"), "Imported API version is incorrect"); Assert.assertEquals(DESCRIPTION, apiObj.getString("description"), "Imported API description is incorrect"); Assert.assertTrue(tags.contains(TAG1), "Imported API not contain tag: " + TAG1); Assert.assertTrue(tags.contains(TAG2), "Imported API not contain tag: " + TAG2); Assert.assertTrue(tags.contains(TAG3), "Imported API not contain tag: " + TAG3); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.GOLD), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.GOLD); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.BRONZE), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.BRONZE); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.SILVER), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.SILVER); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.UNLIMITED), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.UNLIMITED); Assert.assertEquals("checked", apiObj.getString("transport_http"), "Imported API HTTP transport status is incorrect"); Assert.assertEquals("checked", apiObj.getString("transport_https"), "Imported API HTTPS transport status is incorrect"); Assert.assertEquals("Disabled", apiObj.getString("responseCache"), "Imported API response Cache status is incorrect"); Assert.assertEquals("public", apiObj.getString("visibility"), "Imported API visibility is incorrect"); Assert.assertEquals("false", apiObj.getString("isDefaultVersion"), "Imported API Default Version status is incorrect"); JSONArray resourcesList = new JSONArray(apiObj.getString("resources")); Assert.assertEquals(resList.size(), resourcesList.length(), "Imported API not in Created state"); String method = null, authType = null, tier = null, urlPattern = null; APIResourceBean res; for (int i = 0; i < resList.size(); i++) { res = resList.get(i); for (int j = 0; j < resourcesList.length(); j++) { JSONObject verb = resourcesList.getJSONObject(j).getJSONObject("http_verbs"); Iterator it = verb.keys(); if (it.hasNext()) { method = (String) it.next(); if (StringUtils.equals(res.getResourceMethod(), method)) { JSONObject resProp = verb.getJSONObject(method); authType = resProp.getString("auth_type"); tier = resProp.getString("throttling_tier"); urlPattern = resourcesList.getJSONObject(j).getString("url_pattern"); break; } } } Assert.assertEquals(res.getResourceMethod(), method, "Imported API Resource method is incorrect"); Assert.assertEquals(res.getResourceMethodAuthType(), authType, "Imported API Resource Auth Type is incorrect"); Assert.assertEquals(res.getResourceMethodThrottlingTier(), tier, "Imported API Resource Tier is incorrect"); Assert.assertEquals(res.getUriTemplate(), urlPattern, "Imported API Resource URL template is incorrect"); } } @Test(groups = { "wso2.am" }, description = "Implementing sample api for scope test", dependsOnMethods = "testAPIState") public void testNewAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(NEW_API_NAME, NEW_API_CONTEXT, API_VERSION, providerName, new URL(endpointUrl)); //adding resources using swagger String swagger = "{" + "\"paths\": {" + "\"/add\": {" + "\"get\": {" + "\"x-auth-type\": \"" + URLEncoder .encode(APIMIntegrationConstants.RESOURCE_AUTH_TYPE_APPLICATION_AND_APPLICATION_USER, "UTF-8") + "\"," + "\"x-throttling-tier\": \"" + APIMIntegrationConstants.API_TIER.UNLIMITED + "\"," + "\"x-scope\": \"" + SCOPE_NAME + "\"," + "\"responses\": {" + "\"200\": {}" + "}," + "\"parameters\": [{" + "\"name\": \"x\"," + "\"paramType\": \"query\"," + "\"required\": false," + "\"type\": \"string\"," + "\"description\": \"First value\"," + "\"in\": \"query\"" + "}, {" + "\"name\": \"y\"," + "\"paramType\": \"query\"," + "\"required\": false," + "\"type\": \"string\"," + "\"description\": \"Second Value\"," + "\"in\": \"query\"" + "}]" + "}" + "}" + "}," + "\"swagger\": \"2.0\"," + "\"x-wso2-security\": {" + "\"apim\": {" + "\"x-wso2-scopes\": [{" + "\"description\": \"Sample Scope\"," + "\"name\": \"" + SCOPE_NAME + "\"," + "\"roles\": \"" + ALLOWED_ROLE + "\"," + "\"key\": \"" + SCOPE_NAME + "\"" + "}]" + "}" + "}," + "\"info\": {" + "\"title\": \"" + NEW_API_NAME + "\"," + "\"" + API_VERSION + "\": \"1.0.0\"" + "}" + "}"; apiCreationRequestBean.setSwagger(swagger); apiCreationRequestBean.setVisibility("restricted"); apiCreationRequestBean.setRoles(VISIBILITY_ROLE); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NEW_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Invoke the API before export", dependsOnMethods = "testNewAPICreation") public void testNewAPIInvoke() throws Exception { apiStore = new APIStoreRestClient(storeURLHttp); apiStore.login(allowedUser, String.valueOf(ALLOWED_USER_PASS)); //add a application HttpResponse serviceResponse = apiStore .addApplication(APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test"); verifyResponse(serviceResponse); String provider = user.getUserName(); //subscribe to the api SubscriptionRequest subscriptionRequest = new SubscriptionRequest(NEW_API_NAME, provider); subscriptionRequest.setApplicationName(APP_NAME); subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD); serviceResponse = apiStore.subscribe(subscriptionRequest); verifyResponse(serviceResponse); //generate the key for the subscription APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(APP_NAME); generateAppKeyRequest.setTokenScope(SCOPE_NAME); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject response = new JSONObject(responseString); String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); Assert.assertNotNull("Access Token not found " + responseString, accessToken); //invoke api requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken); String invokeURL = getAPIInvocationURLHttp(NEW_API_CONTEXT, API_VERSION); serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders); Assert.assertEquals(HttpStatus.SC_OK, serviceResponse.getResponseCode(), "Imported API not in Created state"); } @Test(groups = { "wso2.am" }, description = "Exporting above created new API", dependsOnMethods = "testNewAPIInvoke") public void testNewAPIExport() throws Exception { //export api URL exportRequest = new URL( exportUrl + "?name=" + NEW_API_NAME + "&version=" + API_VERSION + "&provider=" + user.getUserName()); String fileName = user.getUserDomain() + "_" + NEW_API_NAME; newApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, newApiZip); } @Test(groups = { "wso2.am" }, description = "Importing new API", dependsOnMethods = "testNewAPIExport") public void testNewAPIImport() throws Exception { //remove existing application and api HttpResponse serviceResponse = apiStore.removeApplication(APP_NAME); verifyResponse(serviceResponse); serviceResponse = apiPublisher.deleteAPI(NEW_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //deploy exported API importAPI(importUrl, newApiZip, user.getUserName(), user.getPassword().toCharArray()); } @Test(groups = { "wso2.am" }, description = "Checking newly imported API status", dependsOnMethods = "testNewAPIImport") public void testNewAPIState() throws Exception { //get the API information HttpResponse response = apiPublisher.getAPI(NEW_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String state = apiObj.getString("status"); Assert.assertEquals(state, APILifeCycleState.CREATED.getState(), "Imported API not in Created state"); Assert.assertEquals(NEW_API_NAME, apiObj.getString("name"), "Imported API name is incorrect"); Assert.assertEquals(API_VERSION, apiObj.getString("version"), "Imported API version is incorrect"); Assert.assertEquals("restricted", apiObj.getString("visibility"), "Imported API Visibility is incorrect"); String endpointConfig = apiObj.getString("endpointConfig"); Assert.assertEquals(endpointUrl, new JSONObject(endpointConfig).getJSONObject("production_endpoints").getString("url"), "Imported API Endpoint url is incorrect"); } @Test(groups = { "wso2.am" }, description = "Invoke the newly imported API", dependsOnMethods = "testNewAPIState") public void testNewAPIInvokeAfterImport() throws Exception { //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NEW_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); HttpResponse serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); apiStore = new APIStoreRestClient(storeURLHttp); apiStore.login(deniedUser, String.valueOf(DENIED_USER_PASS)); //add a application serviceResponse = apiStore .addApplication(NEW_APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test"); verifyResponse(serviceResponse); String provider = user.getUserName(); //subscribe to the api SubscriptionRequest subscriptionRequest = new SubscriptionRequest(NEW_API_NAME, provider); subscriptionRequest.setApplicationName(NEW_APP_NAME); subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD); serviceResponse = apiStore.subscribe(subscriptionRequest); verifyResponse(serviceResponse); //generate the key for the subscription APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(NEW_APP_NAME); generateAppKeyRequest.setTokenScope(SCOPE_NAME); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject response = new JSONObject(responseString); String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); Assert.assertNotNull("Access Token not found " + responseString, accessToken); //invoke the API requestHeaders.clear(); requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken); String invokeURL = getAPIInvocationURLHttp(NEW_API_CONTEXT, API_VERSION); serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, serviceResponse.getResponseCode(), "Imported API not in Created state"); } @Test(groups = { "wso2.am" }, description = "Sample API creation", dependsOnMethods = "testNewAPIInvokeAfterImport") public void testPreserveProviderTrueAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(PRESERVE_PUBLISHER_API_NAME, PRESERVE_PUBLISHER_API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean resource = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); resList.add(resource); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testPreserveProviderTrueAPICreation") public void testPreserveProviderTrueApiExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + PRESERVE_PUBLISHER_API_NAME + "&version=" + API_VERSION + "&provider=" + user .getUserName()); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + PRESERVE_PUBLISHER_API_NAME; preservePublisherApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, preservePublisherApiZip); HttpResponse serviceResponse = apiPublisher .deleteAPI(PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testPreserveProviderTrueApiExport") public void testPreserveProviderTrueSameProviderApiImport() throws Exception { //import the exported zip on same publisher importAPI(importUrl + "?preserveProvider=true", preservePublisherApiZip, user.getUserName(), user.getPassword().toCharArray()); //get the imported file information HttpResponse response = apiPublisher.getAPI(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=true"); //delete the existing API to import it again HttpResponse serviceResponse = apiPublisher .deleteAPI(PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //import the exported zip on different publisher importAPI(importUrl + "?preserveProvider=true", preservePublisherApiZip, publisherUser, PUBLISHER_USER_PASS); //get the imported file information response = apiPublisher.getAPI(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); responseObj = new JSONObject(response.getData()); apiObj = responseObj.getJSONObject("api"); provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=true"); } @Test(groups = { "wso2.am" }, description = "Sample API creation", dependsOnMethods = "testPreserveProviderTrueSameProviderApiImport") public void testPreserveProviderFalseAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(NOT_PRESERVE_PUBLISHER_API_NAME, NOT_PRESERVE_PUBLISHER_API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean resource = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); resList.add(resource); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NOT_PRESERVE_PUBLISHER_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testPreserveProviderFalseAPICreation") public void testPreserveProviderFalseApiExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + NOT_PRESERVE_PUBLISHER_API_NAME + "&version=" + API_VERSION + "&provider=" + user .getUserName()); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + NOT_PRESERVE_PUBLISHER_API_NAME; notPreservePublisherApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, notPreservePublisherApiZip); HttpResponse serviceResponse = apiPublisher .deleteAPI(NOT_PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testPreserveProviderFalseApiExport") public void testPreserveProviderFalseSameProviderApiImport() throws Exception { //import the exported zip on same publisher importAPI(importUrl + "?preserveProvider=false", notPreservePublisherApiZip, user.getUserName(), user.getPassword().toCharArray()); //get the imported file information HttpResponse response = apiPublisher.getAPI(NOT_PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=false"); //import the exported zip on different publisher importAPI(importUrl + "?preserveProvider=false", notPreservePublisherApiZip, publisherUser, PUBLISHER_USER_PASS); //get the imported file information response = apiPublisher.getAPI(NOT_PRESERVE_PUBLISHER_API_NAME, publisherUser, API_VERSION); verifyResponse(response); responseObj = new JSONObject(response.getData()); apiObj = responseObj.getJSONObject("api"); provider = apiObj.getString("provider"); Assert.assertEquals(provider, publisherUser, "Provider is not as expected when 'preserveProvider'=false"); } @AfterClass(alwaysRun = true) public void destroy() throws Exception { apiStore.removeApplication(NEW_APP_NAME); apiPublisher.deleteAPI(API_NAME, API_VERSION, user.getUserName()); apiPublisher.deleteAPI(NEW_API_NAME, API_VERSION, user.getUserName()); boolean deleteStatus; deleteStatus = apiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = newApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = preservePublisherApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = notPreservePublisherApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = zipTempDir.delete(); Assert.assertTrue(deleteStatus, "temp directory delete not successful"); super.cleanUp(); } @DataProvider public static Object[][] userModeDataProvider() { return new Object[][] { new Object[] { TestUserMode.SUPER_TENANT_ADMIN }, new Object[] { TestUserMode.TENANT_ADMIN }, }; } /** * get the base64 encoded username and password * * @param user username * @param pass password * @return encoded basic auth, as string */ private String encodeCredentials(String user, char[] pass) { StringBuilder builder = new StringBuilder(user).append(':').append(pass); String cred = builder.toString(); byte[] encodedBytes = Base64.encodeBase64(cred.getBytes()); return new String(encodedBytes); } /** * Save file from a given URL * * @param exportRequest URL of the file location * @param fileName expected File to be saved * @throws URISyntaxException throws if URL is malformed * @throws IOException throws if connection issues occurred */ private void exportAPI(URL exportRequest, File fileName) throws URISyntaxException, IOException { CloseableHttpClient client = HTTPSClientUtils.getHttpsClient(); HttpGet get = new HttpGet(exportRequest.toURI()); get.addHeader(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user.getUserName(), user.getPassword().toCharArray())); CloseableHttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { FileOutputStream outStream = new FileOutputStream(fileName); try { entity.writeTo(outStream); } finally { outStream.close(); } } Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK, "Response code is not as expected"); Assert.assertTrue(fileName.exists(), "File save was not successful"); } /** * Upload a file to the given URL * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); } }
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/APIImportExportTestCase.java
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.am.integration.tests.other; import com.google.common.io.Files; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.CloseableHttpClient; import org.json.JSONArray; import org.json.JSONObject; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import org.wso2.am.integration.test.utils.base.APIMIntegrationBaseTest; import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.bean.APILifeCycleState; import org.wso2.am.integration.test.utils.bean.APILifeCycleStateRequest; import org.wso2.am.integration.test.utils.bean.APIResourceBean; import org.wso2.am.integration.test.utils.bean.APIThrottlingTier; import org.wso2.am.integration.test.utils.bean.APPKeyRequestGenerator; import org.wso2.am.integration.test.utils.bean.SubscriptionRequest; import org.wso2.am.integration.test.utils.clients.APIPublisherRestClient; import org.wso2.am.integration.test.utils.clients.APIStoreRestClient; import org.wso2.am.integration.test.utils.http.HTTPSClientUtils; import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment; import org.wso2.carbon.automation.engine.annotations.SetEnvironment; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import org.wso2.carbon.integration.common.admin.client.UserManagementClient; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URISyntaxException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * This test case is used to test the API Manager Import Export tool */ @SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL }) public class APIImportExportTestCase extends APIMIntegrationBaseTest { private final Log log = LogFactory.getLog(APIImportExportTestCase.class); private final String API_NAME = "APIImportExportTestCaseAPIName"; private final String NEW_API_NAME = "NewAPIImportExportTestCaseAPIName"; private final String PRESERVE_PUBLISHER_API_NAME = "preserveNewAPIImportExportAPIName"; private final String NOT_PRESERVE_PUBLISHER_API_NAME = "notPreserveNewAPIImportExportAPIName"; private final String PRESERVE_PUBLISHER_API_CONTEXT = "preserveAPIImportExportContext"; private final String NOT_PRESERVE_PUBLISHER_API_CONTEXT = "notPreserveAPIImportExportContext"; private final String API_CONTEXT = "APIImportExportTestCaseContext"; private final String NEW_API_CONTEXT = "NewAPIImportExportTestCaseContext"; private final String ALLOWED_ROLE = "allowedRole"; private final String VISIBILITY_ROLE = "visibilityRole"; private final String NOT_ALLOWED_ROLE = "denyRole"; private final String ADMIN_ROLE = "admin"; private final String[] PERMISSIONS = { "/permission/admin/login", "/permission/admin/manage/api/subscribe" }; private final char[] ALLOWED_USER_PASS = "pass@123".toCharArray(); private final char[] DENIED_USER_PASS = "pass@123".toCharArray(); private final char[] PUBLISHER_USER_PASS = "pass@123".toCharArray(); private final String SCOPE_NAME = "ImportExportScope"; private final String TAG1 = "import"; private final String TAG2 = "export"; private final String TAG3 = "test"; private final String DESCRIPTION = "This is test API create by API manager integration test"; private final String API_VERSION = "1.0.0"; private final String APP_NAME = "APIImportExportTestCaseApp"; private final String NEW_APP_NAME = "newAPIImportExportTestCaseApp"; private String allowedUser = "allowedUser"; private String deniedUser = "deniedUser"; private String publisherUser = "importExportPublisher"; private String publisherURLHttps; private String storeURLHttp; private File zipTempDir, apiZip, newApiZip, preservePublisherApiZip, notPreservePublisherApiZip; private String importUrl; private String exportUrl; private APICreationRequestBean apiCreationRequestBean; private List<APIResourceBean> resList; private String tags; private String tierCollection; private String endpointUrl; private Map<String, String> requestHeaders = new HashMap<String, String>(); private APIPublisherRestClient apiPublisher; private APIStoreRestClient apiStore; @Factory(dataProvider = "userModeDataProvider") public APIImportExportTestCase(TestUserMode userMode) { this.userMode = userMode; } @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(userMode); publisherURLHttps = publisherUrls.getWebAppURLHttps(); storeURLHttp = getStoreURLHttp(); endpointUrl = backEndServerUrl.getWebAppURLHttp() + "am/sample/calculator/v1/api"; apiPublisher = new APIPublisherRestClient(publisherURLHttps); apiPublisher.login(user.getUserName(), user.getPassword()); //concat tags tags = TAG1 + "," + TAG2 + "," + TAG3; tierCollection = APIMIntegrationConstants.API_TIER.BRONZE + "," + APIMIntegrationConstants.API_TIER.GOLD + "," + APIMIntegrationConstants.API_TIER.SILVER + "," + APIMIntegrationConstants.API_TIER.UNLIMITED; importUrl = publisherURLHttps + APIMIntegrationConstants.AM_IMPORT_EXPORT_WEB_APP_NAME + "/import-api"; exportUrl = publisherURLHttps + APIMIntegrationConstants.AM_IMPORT_EXPORT_WEB_APP_NAME + "/export-api"; //adding new 3 roles and two users userManagementClient = new UserManagementClient(keyManagerContext.getContextUrls().getBackEndUrl(), createSession(keyManagerContext)); userManagementClient.addRole(ALLOWED_ROLE, null, PERMISSIONS); userManagementClient.addRole(NOT_ALLOWED_ROLE, null, PERMISSIONS); userManagementClient.addRole(VISIBILITY_ROLE, null, PERMISSIONS); userManagementClient .addUser(allowedUser, String.valueOf(ALLOWED_USER_PASS), new String[] { ALLOWED_ROLE, VISIBILITY_ROLE }, null); userManagementClient.addUser(deniedUser, String.valueOf(DENIED_USER_PASS), new String[] { NOT_ALLOWED_ROLE, VISIBILITY_ROLE }, null); userManagementClient .addUser(publisherUser, String.valueOf(PUBLISHER_USER_PASS), new String[] { ADMIN_ROLE }, null); if (!keyManagerContext.getContextTenant().getDomain().equals("carbon.super")) { allowedUser = allowedUser + "@" + keyManagerContext.getContextTenant().getDomain(); deniedUser = deniedUser + "@" + keyManagerContext.getContextTenant().getDomain(); publisherUser = publisherUser + "@" + keyManagerContext.getContextTenant().getDomain(); } } @Test(groups = { "wso2.am" }, description = "Sample API creation") public void testAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(API_NAME, API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean res1 = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); APIResourceBean res2 = new APIResourceBean("GET", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/get"); APIResourceBean res3 = new APIResourceBean("PUT", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION_USER.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.ULTIMATE, "/put"); APIResourceBean res4 = new APIResourceBean("DELETE", APIMIntegrationConstants.ResourceAuthTypes.APPLICATION_AND_APPLICATION_USER.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.UNLIMITED, "/delete"); APIResourceBean res5 = new APIResourceBean("PATCH", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/patch"); APIResourceBean res6 = new APIResourceBean("HEAD", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/head"); APIResourceBean res7 = new APIResourceBean("OPTIONS", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.BASIC, "/options"); resList.add(res1); resList.add(res2); resList.add(res3); resList.add(res4); resList.add(res5); resList.add(res6); resList.add(res7); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testAPICreation") public void testAPIExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + API_NAME + "&version=" + API_VERSION + "&provider=" + user.getUserName()); zipTempDir = Files.createTempDir(); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + API_NAME; apiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, apiZip); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testAPIExport") public void testAPIImport() throws Exception { //delete exported API before import HttpResponse serviceResponse = apiPublisher.deleteAPI(API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //upload the exported zip importAPI(importUrl, apiZip, user.getUserName(), user.getPassword().toCharArray()); } @Test(groups = { "wso2.am" }, description = "Checking status of the imported API", dependsOnMethods = "testAPIImport") public void testAPIState() throws Exception { //get the imported API information HttpResponse response = apiPublisher.getAPI(API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String state = apiObj.getString("status"); Assert.assertEquals(state, APILifeCycleState.CREATED.getState(), "Imported API not in Created state"); Assert.assertEquals(API_NAME, apiObj.getString("name"), "Imported API Name is incorrect"); Assert.assertEquals(API_VERSION, apiObj.getString("version"), "Imported API version is incorrect"); Assert.assertEquals(DESCRIPTION, apiObj.getString("description"), "Imported API description is incorrect"); Assert.assertTrue(tags.contains(TAG1), "Imported API not contain tag: " + TAG1); Assert.assertTrue(tags.contains(TAG2), "Imported API not contain tag: " + TAG2); Assert.assertTrue(tags.contains(TAG3), "Imported API not contain tag: " + TAG3); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.GOLD), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.GOLD); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.BRONZE), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.BRONZE); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.SILVER), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.SILVER); Assert.assertTrue( apiObj.getString("availableTiersDisplayNames").contains(APIMIntegrationConstants.API_TIER.UNLIMITED), "Imported API not contain Tier: " + APIMIntegrationConstants.API_TIER.UNLIMITED); Assert.assertEquals("checked", apiObj.getString("transport_http"), "Imported API HTTP transport status is incorrect"); Assert.assertEquals("checked", apiObj.getString("transport_https"), "Imported API HTTPS transport status is incorrect"); Assert.assertEquals("Disabled", apiObj.getString("responseCache"), "Imported API response Cache status is incorrect"); Assert.assertEquals("Disabled", apiObj.getString("destinationStats"), "Imported API destination Stats status is incorrect"); Assert.assertEquals("public", apiObj.getString("visibility"), "Imported API visibility is incorrect"); Assert.assertEquals("false", apiObj.getString("isDefaultVersion"), "Imported API Default Version status is incorrect"); JSONArray resourcesList = new JSONArray(apiObj.getString("resources")); Assert.assertEquals(resList.size(), resourcesList.length(), "Imported API not in Created state"); String method = null, authType = null, tier = null, urlPattern = null; APIResourceBean res; for (int i = 0; i < resList.size(); i++) { res = resList.get(i); for (int j = 0; j < resourcesList.length(); j++) { JSONObject verb = resourcesList.getJSONObject(j).getJSONObject("http_verbs"); Iterator it = verb.keys(); if (it.hasNext()) { method = (String) it.next(); if (StringUtils.equals(res.getResourceMethod(), method)) { JSONObject resProp = verb.getJSONObject(method); authType = resProp.getString("auth_type"); tier = resProp.getString("throttling_tier"); urlPattern = resourcesList.getJSONObject(j).getString("url_pattern"); break; } } } Assert.assertEquals(res.getResourceMethod(), method, "Imported API Resource method is incorrect"); Assert.assertEquals(res.getResourceMethodAuthType(), authType, "Imported API Resource Auth Type is incorrect"); Assert.assertEquals(res.getResourceMethodThrottlingTier(), tier, "Imported API Resource Tier is incorrect"); Assert.assertEquals(res.getUriTemplate(), urlPattern, "Imported API Resource URL template is incorrect"); } } @Test(groups = { "wso2.am" }, description = "Implementing sample api for scope test", dependsOnMethods = "testAPIState") public void testNewAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(NEW_API_NAME, NEW_API_CONTEXT, API_VERSION, providerName, new URL(endpointUrl)); //adding resources using swagger String swagger = "{" + "\"paths\": {" + "\"/add\": {" + "\"get\": {" + "\"x-auth-type\": \"" + URLEncoder .encode(APIMIntegrationConstants.RESOURCE_AUTH_TYPE_APPLICATION_AND_APPLICATION_USER, "UTF-8") + "\"," + "\"x-throttling-tier\": \"" + APIMIntegrationConstants.API_TIER.UNLIMITED + "\"," + "\"x-scope\": \"" + SCOPE_NAME + "\"," + "\"responses\": {" + "\"200\": {}" + "}," + "\"parameters\": [{" + "\"name\": \"x\"," + "\"paramType\": \"query\"," + "\"required\": false," + "\"type\": \"string\"," + "\"description\": \"First value\"," + "\"in\": \"query\"" + "}, {" + "\"name\": \"y\"," + "\"paramType\": \"query\"," + "\"required\": false," + "\"type\": \"string\"," + "\"description\": \"Second Value\"," + "\"in\": \"query\"" + "}]" + "}" + "}" + "}," + "\"swagger\": \"2.0\"," + "\"x-wso2-security\": {" + "\"apim\": {" + "\"x-wso2-scopes\": [{" + "\"description\": \"Sample Scope\"," + "\"name\": \"" + SCOPE_NAME + "\"," + "\"roles\": \"" + ALLOWED_ROLE + "\"," + "\"key\": \"" + SCOPE_NAME + "\"" + "}]" + "}" + "}," + "\"info\": {" + "\"title\": \"" + NEW_API_NAME + "\"," + "\"" + API_VERSION + "\": \"1.0.0\"" + "}" + "}"; apiCreationRequestBean.setSwagger(swagger); apiCreationRequestBean.setVisibility("restricted"); apiCreationRequestBean.setRoles(VISIBILITY_ROLE); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NEW_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Invoke the API before export", dependsOnMethods = "testNewAPICreation") public void testNewAPIInvoke() throws Exception { apiStore = new APIStoreRestClient(storeURLHttp); apiStore.login(allowedUser, String.valueOf(ALLOWED_USER_PASS)); //add a application HttpResponse serviceResponse = apiStore .addApplication(APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test"); verifyResponse(serviceResponse); String provider = user.getUserName(); //subscribe to the api SubscriptionRequest subscriptionRequest = new SubscriptionRequest(NEW_API_NAME, provider); subscriptionRequest.setApplicationName(APP_NAME); subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD); serviceResponse = apiStore.subscribe(subscriptionRequest); verifyResponse(serviceResponse); //generate the key for the subscription APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(APP_NAME); generateAppKeyRequest.setTokenScope(SCOPE_NAME); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject response = new JSONObject(responseString); String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); Assert.assertNotNull("Access Token not found " + responseString, accessToken); //invoke api requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken); String invokeURL = getAPIInvocationURLHttp(NEW_API_CONTEXT, API_VERSION); serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders); Assert.assertEquals(HttpStatus.SC_OK, serviceResponse.getResponseCode(), "Imported API not in Created state"); } @Test(groups = { "wso2.am" }, description = "Exporting above created new API", dependsOnMethods = "testNewAPIInvoke") public void testNewAPIExport() throws Exception { //export api URL exportRequest = new URL( exportUrl + "?name=" + NEW_API_NAME + "&version=" + API_VERSION + "&provider=" + user.getUserName()); String fileName = user.getUserDomain() + "_" + NEW_API_NAME; newApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, newApiZip); } @Test(groups = { "wso2.am" }, description = "Importing new API", dependsOnMethods = "testNewAPIExport") public void testNewAPIImport() throws Exception { //remove existing application and api HttpResponse serviceResponse = apiStore.removeApplication(APP_NAME); verifyResponse(serviceResponse); serviceResponse = apiPublisher.deleteAPI(NEW_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //deploy exported API importAPI(importUrl, newApiZip, user.getUserName(), user.getPassword().toCharArray()); } @Test(groups = { "wso2.am" }, description = "Checking newly imported API status", dependsOnMethods = "testNewAPIImport") public void testNewAPIState() throws Exception { //get the API information HttpResponse response = apiPublisher.getAPI(NEW_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String state = apiObj.getString("status"); Assert.assertEquals(state, APILifeCycleState.CREATED.getState(), "Imported API not in Created state"); Assert.assertEquals(NEW_API_NAME, apiObj.getString("name"), "Imported API name is incorrect"); Assert.assertEquals(API_VERSION, apiObj.getString("version"), "Imported API version is incorrect"); Assert.assertEquals("restricted", apiObj.getString("visibility"), "Imported API Visibility is incorrect"); String endpointConfig = apiObj.getString("endpointConfig"); Assert.assertEquals(endpointUrl, new JSONObject(endpointConfig).getJSONObject("production_endpoints").getString("url"), "Imported API Endpoint url is incorrect"); } @Test(groups = { "wso2.am" }, description = "Invoke the newly imported API", dependsOnMethods = "testNewAPIState") public void testNewAPIInvokeAfterImport() throws Exception { //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NEW_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); HttpResponse serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); apiStore = new APIStoreRestClient(storeURLHttp); apiStore.login(deniedUser, String.valueOf(DENIED_USER_PASS)); //add a application serviceResponse = apiStore .addApplication(NEW_APP_NAME, APIThrottlingTier.UNLIMITED.getState(), "", "this-is-test"); verifyResponse(serviceResponse); String provider = user.getUserName(); //subscribe to the api SubscriptionRequest subscriptionRequest = new SubscriptionRequest(NEW_API_NAME, provider); subscriptionRequest.setApplicationName(NEW_APP_NAME); subscriptionRequest.setTier(APIMIntegrationConstants.API_TIER.GOLD); serviceResponse = apiStore.subscribe(subscriptionRequest); verifyResponse(serviceResponse); //generate the key for the subscription APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(NEW_APP_NAME); generateAppKeyRequest.setTokenScope(SCOPE_NAME); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject response = new JSONObject(responseString); String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); Assert.assertNotNull("Access Token not found " + responseString, accessToken); //invoke the API requestHeaders.clear(); requestHeaders.put(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Bearer " + accessToken); String invokeURL = getAPIInvocationURLHttp(NEW_API_CONTEXT, API_VERSION); serviceResponse = HTTPSClientUtils.doGet(invokeURL + "/add?x=1&y=1", requestHeaders); Assert.assertEquals(HttpStatus.SC_FORBIDDEN, serviceResponse.getResponseCode(), "Imported API not in Created state"); } @Test(groups = { "wso2.am" }, description = "Sample API creation", dependsOnMethods = "testNewAPIInvokeAfterImport") public void testPreserveProviderTrueAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(PRESERVE_PUBLISHER_API_NAME, PRESERVE_PUBLISHER_API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean resource = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); resList.add(resource); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testPreserveProviderTrueAPICreation") public void testPreserveProviderTrueApiExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + PRESERVE_PUBLISHER_API_NAME + "&version=" + API_VERSION + "&provider=" + user .getUserName()); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + PRESERVE_PUBLISHER_API_NAME; preservePublisherApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, preservePublisherApiZip); HttpResponse serviceResponse = apiPublisher .deleteAPI(PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testPreserveProviderTrueApiExport") public void testPreserveProviderTrueSameProviderApiImport() throws Exception { //import the exported zip on same publisher importAPI(importUrl + "?preserveProvider=true", preservePublisherApiZip, user.getUserName(), user.getPassword().toCharArray()); //get the imported file information HttpResponse response = apiPublisher.getAPI(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=true"); //delete the existing API to import it again HttpResponse serviceResponse = apiPublisher .deleteAPI(PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); //import the exported zip on different publisher importAPI(importUrl + "?preserveProvider=true", preservePublisherApiZip, publisherUser, PUBLISHER_USER_PASS); //get the imported file information response = apiPublisher.getAPI(PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); responseObj = new JSONObject(response.getData()); apiObj = responseObj.getJSONObject("api"); provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=true"); } @Test(groups = { "wso2.am" }, description = "Sample API creation", dependsOnMethods = "testPreserveProviderTrueSameProviderApiImport") public void testPreserveProviderFalseAPICreation() throws Exception { String providerName = user.getUserName(); apiCreationRequestBean = new APICreationRequestBean(NOT_PRESERVE_PUBLISHER_API_NAME, NOT_PRESERVE_PUBLISHER_API_CONTEXT, API_VERSION, providerName, new URL(exportUrl)); apiCreationRequestBean.setTags(tags); apiCreationRequestBean.setDescription(DESCRIPTION); apiCreationRequestBean.setTiersCollection(tierCollection); //define resources resList = new ArrayList<APIResourceBean>(); APIResourceBean resource = new APIResourceBean("POST", APIMIntegrationConstants.ResourceAuthTypes.NONE.getAuthType(), APIMIntegrationConstants.RESOURCE_TIER.PLUS, "/post"); resList.add(resource); apiCreationRequestBean.setResourceBeanList(resList); //add test api HttpResponse serviceResponse = apiPublisher.addAPI(apiCreationRequestBean); verifyResponse(serviceResponse); //publish the api APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(NOT_PRESERVE_PUBLISHER_API_NAME, user.getUserName(), APILifeCycleState.PUBLISHED); serviceResponse = apiPublisher.changeAPILifeCycleStatus(updateRequest); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Exported Sample API", dependsOnMethods = "testPreserveProviderFalseAPICreation") public void testPreserveProviderFalseApiExport() throws Exception { //construct export API url URL exportRequest = new URL( exportUrl + "?name=" + NOT_PRESERVE_PUBLISHER_API_NAME + "&version=" + API_VERSION + "&provider=" + user .getUserName()); //set the export file name with tenant prefix String fileName = user.getUserDomain() + "_" + NOT_PRESERVE_PUBLISHER_API_NAME; notPreservePublisherApiZip = new File(zipTempDir.getAbsolutePath() + File.separator + fileName + ".zip"); //save the exported API exportAPI(exportRequest, notPreservePublisherApiZip); HttpResponse serviceResponse = apiPublisher .deleteAPI(NOT_PRESERVE_PUBLISHER_API_NAME, API_VERSION, user.getUserName()); verifyResponse(serviceResponse); } @Test(groups = { "wso2.am" }, description = "Importing exported API", dependsOnMethods = "testPreserveProviderFalseApiExport") public void testPreserveProviderFalseSameProviderApiImport() throws Exception { //import the exported zip on same publisher importAPI(importUrl + "?preserveProvider=false", notPreservePublisherApiZip, user.getUserName(), user.getPassword().toCharArray()); //get the imported file information HttpResponse response = apiPublisher.getAPI(NOT_PRESERVE_PUBLISHER_API_NAME, user.getUserName(), API_VERSION); verifyResponse(response); JSONObject responseObj = new JSONObject(response.getData()); JSONObject apiObj = responseObj.getJSONObject("api"); String provider = apiObj.getString("provider"); Assert.assertEquals(provider, user.getUserName(), "Provider is not as expected when 'preserveProvider'=false"); //import the exported zip on different publisher importAPI(importUrl + "?preserveProvider=false", notPreservePublisherApiZip, publisherUser, PUBLISHER_USER_PASS); //get the imported file information response = apiPublisher.getAPI(NOT_PRESERVE_PUBLISHER_API_NAME, publisherUser, API_VERSION); verifyResponse(response); responseObj = new JSONObject(response.getData()); apiObj = responseObj.getJSONObject("api"); provider = apiObj.getString("provider"); Assert.assertEquals(provider, publisherUser, "Provider is not as expected when 'preserveProvider'=false"); } @AfterClass(alwaysRun = true) public void destroy() throws Exception { apiStore.removeApplication(NEW_APP_NAME); apiPublisher.deleteAPI(API_NAME, API_VERSION, user.getUserName()); apiPublisher.deleteAPI(NEW_API_NAME, API_VERSION, user.getUserName()); boolean deleteStatus; deleteStatus = apiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = newApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = preservePublisherApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = notPreservePublisherApiZip.delete(); Assert.assertTrue(deleteStatus, "temp file delete not successful"); deleteStatus = zipTempDir.delete(); Assert.assertTrue(deleteStatus, "temp directory delete not successful"); super.cleanUp(); } @DataProvider public static Object[][] userModeDataProvider() { return new Object[][] { new Object[] { TestUserMode.SUPER_TENANT_ADMIN }, new Object[] { TestUserMode.TENANT_ADMIN }, }; } /** * get the base64 encoded username and password * * @param user username * @param pass password * @return encoded basic auth, as string */ private String encodeCredentials(String user, char[] pass) { StringBuilder builder = new StringBuilder(user).append(':').append(pass); String cred = builder.toString(); byte[] encodedBytes = Base64.encodeBase64(cred.getBytes()); return new String(encodedBytes); } /** * Save file from a given URL * * @param exportRequest URL of the file location * @param fileName expected File to be saved * @throws URISyntaxException throws if URL is malformed * @throws IOException throws if connection issues occurred */ private void exportAPI(URL exportRequest, File fileName) throws URISyntaxException, IOException { CloseableHttpClient client = HTTPSClientUtils.getHttpsClient(); HttpGet get = new HttpGet(exportRequest.toURI()); get.addHeader(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user.getUserName(), user.getPassword().toCharArray())); CloseableHttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { FileOutputStream outStream = new FileOutputStream(fileName); try { entity.writeTo(outStream); } finally { outStream.close(); } } Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK, "Response code is not as expected"); Assert.assertTrue(fileName.exists(), "File save was not successful"); } /** * Upload a file to the given URL * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); } }
fixed import-export test case
modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/APIImportExportTestCase.java
fixed import-export test case
Java
apache-2.0
7e8a77494a7dbee951458ad83d77861611aaae97
0
canoo/dolphin-platform,canoo/dolphin-platform,canoo/dolphin-platform
package com.canoo.dolphin.integration.server.runLater; import com.canoo.dolphin.integration.runlater.RunLaterTestBean; import com.canoo.dolphin.integration.server.TestConfiguration; import com.canoo.platform.spring.test.CommunicationMonitor; import com.canoo.platform.spring.test.ControllerUnderTest; import com.canoo.platform.spring.test.SpringTestNGControllerTest; import org.springframework.boot.test.context.SpringBootTest; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_ACTION_NAME; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_ASYNC_ACTION_NAME; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_CONTROLLER_NAME; @SpringBootTest(classes = TestConfiguration.class) public class RunLaterControllerTest extends SpringTestNGControllerTest { @Test public void testRunLaterInPostConstruct() { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); //then Assert.assertNotNull(model.getPostConstructPreRunLaterCallIndex()); Assert.assertNotNull(model.getPostConstructRunLaterCallIndex()); Assert.assertNotNull(model.getPostConstructPostRunLaterCallIndex()); Assert.assertTrue(model.getPostConstructPreRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructPostRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructPreRunLaterCallIndex() < model.getPostConstructPostRunLaterCallIndex()); Assert.assertTrue(model.getPostConstructPostRunLaterCallIndex() < model.getPostConstructRunLaterCallIndex()); } @Test public void testRunLaterInAction() { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); //when: controller.invoke(RUN_LATER_ACTION_NAME); //then: Assert.assertNotNull(model.getActionPreRunLaterCallIndex()); Assert.assertNotNull(model.getActionRunLaterCallIndex()); Assert.assertNotNull(model.getActionPostRunLaterCallIndex()); Assert.assertTrue(model.getActionPreRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionPostRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionPreRunLaterCallIndex() < model.getActionPostRunLaterCallIndex()); Assert.assertTrue(model.getActionPostRunLaterCallIndex() < model.getActionRunLaterCallIndex()); } @Test public void testRunLaterAsyncInAction() throws Exception { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); final CommunicationMonitor monitor = controller.createMonitor(); model.actionRunLaterAsyncCallIndexProperty().onChanged(e -> { monitor.signal(); }); //when: controller.invoke(RUN_LATER_ASYNC_ACTION_NAME); monitor.await(10, TimeUnit.SECONDS); //then: Assert.assertNotNull(model.getActionPreRunLaterAsyncCallIndex()); Assert.assertNotNull(model.getActionRunLaterAsyncCallIndex()); Assert.assertNotNull(model.getActionPostRunLaterAsyncCallIndex()); Assert.assertTrue(model.getActionPreRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionPostRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionPreRunLaterAsyncCallIndex() < model.getActionPostRunLaterAsyncCallIndex()); Assert.assertTrue(model.getActionPostRunLaterAsyncCallIndex() < model.getActionRunLaterAsyncCallIndex()); } }
platform-integration-tests/integration-server/src/test/java/com/canoo/dolphin/integration/server/runLater/RunLaterControllerTest.java
package com.canoo.dolphin.integration.server.runLater; import com.canoo.dolphin.integration.runlater.RunLaterTestBean; import com.canoo.dolphin.integration.server.TestConfiguration; import com.canoo.platform.spring.test.CommunicationMonitor; import com.canoo.platform.spring.test.ControllerUnderTest; import com.canoo.platform.spring.test.SpringTestNGControllerTest; import org.springframework.boot.test.context.SpringBootTest; import org.testng.Assert; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_ACTION_NAME; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_ASYNC_ACTION_NAME; import static com.canoo.dolphin.integration.runlater.RunLaterTestConstants.RUN_LATER_CONTROLLER_NAME; @SpringBootTest(classes = TestConfiguration.class) public class RunLaterControllerTest extends SpringTestNGControllerTest { @Test public void testRunLaterInPostConstruct() { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); //then Assert.assertNotNull(model.getPostConstructPreRunLaterCallIndex()); Assert.assertNotNull(model.getPostConstructRunLaterCallIndex()); Assert.assertNotNull(model.getPostConstructPostRunLaterCallIndex()); Assert.assertTrue(model.getPostConstructPreRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructPostRunLaterCallIndex() > 0); Assert.assertTrue(model.getPostConstructPreRunLaterCallIndex() < model.getPostConstructPostRunLaterCallIndex()); Assert.assertTrue(model.getPostConstructPostRunLaterCallIndex() < model.getPostConstructRunLaterCallIndex()); } @Test public void testRunLaterInAction() { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); //when: controller.invoke(RUN_LATER_ACTION_NAME); //then: Assert.assertNotNull(model.getActionPreRunLaterCallIndex()); Assert.assertNotNull(model.getActionRunLaterCallIndex()); Assert.assertNotNull(model.getActionPostRunLaterCallIndex()); Assert.assertTrue(model.getActionPreRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionPostRunLaterCallIndex() > 0); Assert.assertTrue(model.getActionPreRunLaterCallIndex() < model.getActionPostRunLaterCallIndex()); Assert.assertTrue(model.getActionPostRunLaterCallIndex() < model.getActionRunLaterCallIndex()); } @Test public void testRunLaterAsyncInAction() throws Exception { //given: final ControllerUnderTest<RunLaterTestBean> controller = createController(RUN_LATER_CONTROLLER_NAME); final RunLaterTestBean model = controller.getModel(); final CommunicationMonitor condition = controller.createMonitor(); model.actionRunLaterAsyncCallIndexProperty().onChanged(e -> { condition.signal(); }); //when: controller.invoke(RUN_LATER_ASYNC_ACTION_NAME); condition.await(10, TimeUnit.SECONDS); //then: Assert.assertNotNull(model.getActionPreRunLaterAsyncCallIndex()); Assert.assertNotNull(model.getActionRunLaterAsyncCallIndex()); Assert.assertNotNull(model.getActionPostRunLaterAsyncCallIndex()); Assert.assertTrue(model.getActionPreRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionPostRunLaterAsyncCallIndex() > 0); Assert.assertTrue(model.getActionPreRunLaterAsyncCallIndex() < model.getActionPostRunLaterAsyncCallIndex()); Assert.assertTrue(model.getActionPostRunLaterAsyncCallIndex() < model.getActionRunLaterAsyncCallIndex()); } }
based on review
platform-integration-tests/integration-server/src/test/java/com/canoo/dolphin/integration/server/runLater/RunLaterControllerTest.java
based on review
Java
apache-2.0
4246efb0c0c1288b5d2a4fbca6a8694780087e0a
0
etirelli/jbpm-form-modeler,etirelli/jbpm-form-modeler,baldimir/jbpm-form-modeler,etirelli/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler,mbiarnes/jbpm-form-modeler,baldimir/jbpm-form-modeler,mbiarnes/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,baldimir/jbpm-form-modeler,porcelli-forks/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,droolsjbpm/jbpm-form-modeler,mbiarnes/jbpm-form-modeler
/** * Copyright (C) 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.formModeler.core.processing.impl; import au.com.bytecode.opencsv.CSVParser; import org.apache.commons.logging.Log; import org.jbpm.formModeler.api.model.DataHolder; import org.jbpm.formModeler.core.FieldHandlersManager; import org.jbpm.formModeler.core.processing.FieldHandler; import org.jbpm.formModeler.core.processing.FormProcessor; import org.jbpm.formModeler.core.processing.FormStatusData; import org.jbpm.formModeler.core.processing.ProcessingMessagedException; import org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler; import org.jbpm.formModeler.core.processing.formProcessing.FormChangeProcessor; import org.jbpm.formModeler.core.processing.formProcessing.FormChangeResponse; import org.jbpm.formModeler.core.processing.formProcessing.NamespaceManager; import org.jbpm.formModeler.core.processing.formStatus.FormStatus; import org.jbpm.formModeler.core.processing.formStatus.FormStatusManager; import org.jbpm.formModeler.api.model.Field; import org.jbpm.formModeler.api.model.Form; import org.jbpm.formModeler.api.model.wrappers.I18nSet; import org.apache.commons.lang.StringUtils; import org.jbpm.formModeler.core.config.FormManagerImpl; import org.jbpm.formModeler.api.client.FormRenderContext; import org.jbpm.formModeler.api.client.FormRenderContextManager; import org.jbpm.formModeler.service.cdi.CDIBeanLocator; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.Serializable; import java.util.*; @ApplicationScoped public class FormProcessorImpl implements FormProcessor, Serializable { @Inject private Log log; // TODO: fix formulas //@Inject private FormChangeProcessor formChangeProcessor; @Inject private FieldHandlersManager fieldHandlersManager; @Inject FormRenderContextManager formRenderContextManager; private CSVParser rangeParser = new CSVParser(';'); private CSVParser optionParser = new CSVParser(','); protected FormStatus getContextFormStatus(FormRenderContext context) { return FormStatusManager.lookup().getFormStatus(context.getForm().getId(), context.getUID()); } protected FormStatus getFormStatus(Form form, String namespace) { return getFormStatus(form, namespace, new HashMap()); } protected FormStatus getFormStatus(Form form, String namespace, Map currentValues) { FormStatus formStatus = FormStatusManager.lookup().getFormStatus(form.getId(), namespace); return formStatus != null ? formStatus : createFormStatus(form, namespace, currentValues); } protected boolean existsFormStatus(Long formId, String namespace) { FormStatus formStatus = FormStatusManager.lookup().getFormStatus(formId, namespace); return formStatus != null; } protected FormStatus createFormStatus(Form form, String namespace, Map currentValues) { FormStatus fStatus = FormStatusManager.lookup().createFormStatus(form.getId(), namespace); setDefaultValues(form, namespace, currentValues); return fStatus; } protected void setDefaultValues(Form form, String namespace, Map currentValues) { if (form != null) { Set formFields = form.getFormFields(); Map params = new HashMap(5); Map rangeFormulas = (Map) getAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS); if (rangeFormulas == null) { rangeFormulas = new HashMap(); setAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS, rangeFormulas); } for (Iterator iterator = formFields.iterator(); iterator.hasNext();) { Field field = (Field) iterator.next(); Object value = currentValues.get(field.getFieldName()); String inputName = getPrefix(form, namespace) + field.getFieldName(); try { FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType()); if ((value instanceof Map && !((Map)value).containsKey(FORM_MODE)) && !(value instanceof I18nSet)) ((Map)value).put(FORM_MODE, currentValues.get(FORM_MODE)); Map paramValue = handler.getParamValue(inputName, value, field.getFieldPattern()); if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); // Init ranges for simple combos String rangeFormula = field.getRangeFormula(); if (!StringUtils.isEmpty(rangeFormula) && rangeFormula.startsWith("{") && rangeFormula.endsWith("}")) { rangeFormula = rangeFormula.substring(1, rangeFormula.length() - 1); String[] options = rangeParser.parseLine(rangeFormula); if (options != null) { Map rangeValues = new TreeMap(); for (String option : options) { String[] values = optionParser.parseLine(option); if (values != null && values.length == 2) { rangeValues.put(values[0], values[1]); } } rangeFormulas.put(field.getFieldName(), rangeValues); } } /* TODO: implement again formulas for default values Object defaultValue = pField.get("defaultValueFormula"); String inputName = getPrefix(pf, namespace) + pField.getFieldName(); try { String pattern = (String) pField.get("pattern"); Object value = currentValues.get(pField.getFieldName()); FieldHandler handler = pField.getFieldType().getManager(); if (value == null) { if (defaultValue != null) { if (!defaultValue.toString().startsWith("=")) { log.error("Incorrect formula specified for field " + pField.getFieldName()); continue; } if (handler instanceof DefaultFieldHandler) value = ((DefaultFieldHandler) handler).evaluateFormula(pField, defaultValue.toString().substring(1), "", new HashMap(0), "", namespace, new Date()); } } if ((value instanceof Map && !((Map)value).containsKey(FormProcessor.FORM_MODE)) && !(value instanceof I18nSet) && !(value instanceof I18nObject)) ((Map)value).put(FormProcessor.FORM_MODE, currentValues.get(FormProcessor.FORM_MODE)); Map paramValue = handler.getParamValue(inputName, value, pattern); if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); */ } catch (Exception e) { log.error("Error obtaining default values for " + inputName, e); } } setValues(form, namespace, params, null, true); } } protected void destroyFormStatus(Form form, String namespace) { FormStatusManager.lookup().destroyFormStatus(form.getId(), namespace); } public void setValues(Form form, String namespace, Map parameterMap, Map filesMap) { setValues(form, namespace, parameterMap, filesMap, false); } public void setValues(Form form, String namespace, Map parameterMap, Map filesMap, boolean incremental) { if (form != null) { namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE); FormStatus formStatus = getFormStatus(form, namespace); // if (!incremental) formStatus.getWrongFields().clear(); if (incremental) { Map mergedParameterMap = new HashMap(); if (formStatus.getLastParameterMap() != null) mergedParameterMap.putAll(formStatus.getLastParameterMap()); if (parameterMap != null) mergedParameterMap.putAll(parameterMap); formStatus.setLastParameterMap(mergedParameterMap); } else { formStatus.setLastParameterMap(parameterMap); } String inputsPrefix = getPrefix(form, namespace); for (Field field : form.getFormFields()) { setFieldValue(field, formStatus, inputsPrefix, parameterMap, filesMap, incremental); } } } public void modify(Form form, String namespace, String fieldName, Object value) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getInputValues().put(fieldName, value); propagateChangesToParentFormStatuses(formStatus, fieldName, value); } public void setAttribute(Form form, String namespace, String attributeName, Object attributeValue) { if (form != null) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getAttributes().put(attributeName, attributeValue); } } public Object getAttribute(Form form, String namespace, String attributeName) { if (form != null){ FormStatus formStatus = getFormStatus(form, namespace); return formStatus.getAttributes().get(attributeName); } return null; } protected void setFieldValue(Field field, FormStatus formStatus, String inputsPrefix, Map parameterMap, Map filesMap, boolean incremental) { String fieldName = field.getFieldName(); String inputName = inputsPrefix + fieldName; FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType()); try { Object previousValue = formStatus.getInputValues().get(fieldName); boolean isRequired = field.getFieldRequired().booleanValue(); if (!handler.isEvaluable(inputName, parameterMap, filesMap) && !(handler.isEmpty(previousValue) && isRequired)) return; Object value = null; boolean emptyNumber = false; try { value = handler.getValue(field, inputName, parameterMap, filesMap, field.getFieldType().getFieldClass(), previousValue); } catch (NumericFieldHandler.EmptyNumberException ene) { //Treat this case in particular, as returning null in a numeric field would make related formulas not working. emptyNumber = true; } if (incremental && value == null && !emptyNumber) { if (log.isDebugEnabled()) log.debug("Refusing to overwrite input value for parameter " + fieldName); } else { formStatus.getInputValues().put(fieldName, value); try { propagateChangesToParentFormStatuses(formStatus, fieldName, value); } catch (Exception e) { log.error("Error modifying formStatus: ", e); } boolean isEmpty = handler.isEmpty(value); if (isRequired && isEmpty && !incremental) { log.debug("Missing required field " + fieldName); formStatus.getWrongFields().add(fieldName); } else { formStatus.removeWrongField(fieldName); } } } catch (ProcessingMessagedException pme) { log.debug("Processing field: ", pme); formStatus.addErrorMessages(fieldName, pme.getMessages()); } catch (Exception e) { log.debug("Error setting field value:", e); if (!incremental) { formStatus.getInputValues().put(fieldName, null); formStatus.getWrongFields().add(fieldName); } } } protected void propagateChangesToParentFormStatuses(FormStatus formStatus, String fieldName, Object value) { FormStatus parent = FormStatusManager.lookup().getParent(formStatus); if (parent != null) { String fieldNameInParent = NamespaceManager.lookup().getNamespace(formStatus.getNamespace()).getFieldNameInParent(); Object valueInParent = parent.getInputValues().get(fieldNameInParent); if (valueInParent != null) { Map parentMapObjectRepresentation = null; if (valueInParent instanceof Map) { parentMapObjectRepresentation = (Map) valueInParent; } else if (valueInParent instanceof Map[]) { //Take the correct value Map editFieldPositions = (Map) parent.getAttributes().get(FormStatusData.EDIT_FIELD_POSITIONS); if (editFieldPositions != null) { Integer pos = (Integer) editFieldPositions.get(fieldNameInParent); if (pos != null) { parentMapObjectRepresentation = ((Map[]) valueInParent)[pos.intValue()]; } } } if (parentMapObjectRepresentation != null) { //Copy my value to parent parentMapObjectRepresentation.put(fieldName, value); propagateChangesToParentFormStatuses(parent, fieldNameInParent, valueInParent); } } } } public FormStatusData read(String ctxUid) { FormStatusDataImpl data = null; try { FormRenderContext context = formRenderContextManager.getFormRenderContext(ctxUid); if (context == null ) return null; FormStatus formStatus = getContextFormStatus(context); boolean isNew = formStatus == null; if (isNew) { formStatus = createContextFormStatus(context); } data = new FormStatusDataImpl(formStatus, isNew); } catch (Exception e) { log.error("Error: ", e); } return data; } protected FormStatus createContextFormStatus(FormRenderContext context) throws Exception { Map values = new HashMap(); Map<String, Object> bindingData = context.getBindingData(); if (bindingData != null && !bindingData.isEmpty()) { Form form = context.getForm(); Set<Field> fields = form.getFormFields(); if (fields != null) { for (Field field : form.getFormFields()) { String bindingString = field.getBindingStr(); if (!StringUtils.isEmpty(bindingString)) { bindingString = bindingString.substring(1, bindingString.length() - 1); boolean canSetValue = bindingString.indexOf("/") > 0; if (canSetValue) { String holderId = bindingString.substring(0, bindingString.indexOf("/")); String holderFieldId = bindingString.substring(holderId.length() + 1); DataHolder holder = form.getDataHolderById(holderId); if (holder != null && !StringUtils.isEmpty(holderFieldId)) { Object value = bindingData.get(holder.getId()); if (value == null) continue; values.put(field.getFieldName(), holder.readValue(value, holderFieldId)); } } else { Object value = bindingData.get(bindingString); if (value != null) values.put(bindingString, value); } } } } } return getFormStatus(context.getForm(), context.getUID(), values); } public FormStatusData read(Form form, String namespace, Map currentValues) { boolean exists = existsFormStatus(form.getId(), namespace); if (currentValues == null) currentValues = new HashMap(); FormStatus formStatus = getFormStatus(form, namespace, currentValues); FormStatusDataImpl data = null; try { data = new FormStatusDataImpl(formStatus, !exists); } catch (Exception e) { log.error("Error: ", e); } return data; } public FormStatusData read(Form form, String namespace) { return read(form, namespace, new HashMap<String, Object>()); } public void flushPendingCalculations(Form form, String namespace) { if (formChangeProcessor != null) { formChangeProcessor.process(form, namespace, new FormChangeResponse());//Response is ignored, we just need the session values. } } public void persist(String ctxUid) throws Exception { ctxUid = StringUtils.defaultIfEmpty(ctxUid, FormProcessor.DEFAULT_NAMESPACE); persist(formRenderContextManager.getFormRenderContext(ctxUid)); } public void persist(FormRenderContext context) throws Exception { Form form = context.getForm(); Map mapToPersist = getFilteredMapRepresentationToPersist(form, context.getUID()); for (Iterator it = mapToPersist.keySet().iterator(); it.hasNext();) { String fieldName = (String) it.next(); Field field = form.getField(fieldName); if (field != null) { String bindingString = field.getBindingStr(); if (!StringUtils.isEmpty(bindingString)) { bindingString = bindingString.substring(1, bindingString.length() - 1); boolean canBind = bindingString.indexOf("/") > 0; if (canBind) { String holderId = bindingString.substring(0, bindingString.indexOf("/")); String holderFieldId = bindingString.substring(holderId.length() + 1); DataHolder holder = form.getDataHolderById(holderId); if (holder != null && !StringUtils.isEmpty(holderFieldId)) holder.writeValue(context.getBindingData().get(holderId), holderFieldId, mapToPersist.get(fieldName)); else canBind = false; } if (!canBind) { log.debug("Unable to bind DataHolder for field '" + fieldName + "' to '" + bindingString + "'. This may be caused because bindingString is incorrect or the form doesn't contains the defined DataHolder."); context.getBindingData().put(bindingString, mapToPersist.get(fieldName)); } } } } } public Map getMapRepresentationToPersist(Form form, String namespace) throws Exception { namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE); flushPendingCalculations(form, namespace); Map m = new HashMap(); FormStatus formStatus = getFormStatus(form, namespace); if (!formStatus.getWrongFields().isEmpty()) { throw new IllegalArgumentException("Validation error."); } fillObjectValues(m, formStatus.getInputValues(), form); Set s = (Set) m.get(MODIFIED_FIELD_NAMES); if (s == null) { m.put(MODIFIED_FIELD_NAMES, s = new TreeSet()); } s.addAll(form.getFieldNames()); return m; } protected Map getFilteredMapRepresentationToPersist(Form form, String namespace) throws Exception { Map inputValues = getMapRepresentationToPersist(form, namespace); Map mapToPersist = filterMapRepresentationToPersist(inputValues); return mapToPersist; } public Map filterMapRepresentationToPersist(Map inputValues) throws Exception { Map filteredMap = new HashMap(); Set keys = inputValues.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); filteredMap.put(key, inputValues.get(key)); } return filteredMap; } /** * Copy to obj values read from status map values * * @param obj * @param values * @throws Exception */ protected void fillObjectValues(final Map obj, Map values, Form form) throws Exception { Map valuesToSet = new HashMap(); for (Iterator it = values.keySet().iterator(); it.hasNext();) { String propertyName = (String) it.next(); Object propertyValue = values.get(propertyName); valuesToSet.put(propertyName, propertyValue); } obj.putAll(valuesToSet); } protected FormManagerImpl getFormsManager() { return (FormManagerImpl) CDIBeanLocator.getBeanByType(FormManagerImpl.class); } @Override public void clear(FormRenderContext context) { clear(context.getForm(), context.getUID()); } @Override public void clear(String ctxUID) { clear(formRenderContextManager.getFormRenderContext(ctxUID)); } public void clear(Form form, String namespace) { if (log.isDebugEnabled()) log.debug("Clearing form status for form " + form.getName() + " with namespace '" + namespace + "'"); destroyFormStatus(form, namespace); } public void clearField(Form form, String namespace, String fieldName) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getInputValues().remove(fieldName); } public void clearFieldErrors(Form form, String namespace) { FormStatusManager.lookup().cascadeClearWrongFields(form.getId(), namespace); } public void forceWrongField(Form form, String namespace, String fieldName) { FormStatusManager.lookup().getFormStatus(form.getId(), namespace).getWrongFields().add(fieldName); } protected String getPrefix(Form form, String namespace) { return namespace + FormProcessor.NAMESPACE_SEPARATOR + form.getId() + FormProcessor.NAMESPACE_SEPARATOR; } }
jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java
/** * Copyright (C) 2012 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jbpm.formModeler.core.processing.impl; import au.com.bytecode.opencsv.CSVParser; import org.apache.commons.logging.Log; import org.jbpm.formModeler.api.model.DataHolder; import org.jbpm.formModeler.core.FieldHandlersManager; import org.jbpm.formModeler.core.processing.FieldHandler; import org.jbpm.formModeler.core.processing.FormProcessor; import org.jbpm.formModeler.core.processing.FormStatusData; import org.jbpm.formModeler.core.processing.ProcessingMessagedException; import org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler; import org.jbpm.formModeler.core.processing.formProcessing.FormChangeProcessor; import org.jbpm.formModeler.core.processing.formProcessing.FormChangeResponse; import org.jbpm.formModeler.core.processing.formProcessing.NamespaceManager; import org.jbpm.formModeler.core.processing.formStatus.FormStatus; import org.jbpm.formModeler.core.processing.formStatus.FormStatusManager; import org.jbpm.formModeler.api.model.Field; import org.jbpm.formModeler.api.model.Form; import org.jbpm.formModeler.api.model.wrappers.I18nSet; import org.apache.commons.lang.StringUtils; import org.jbpm.formModeler.core.config.FormManagerImpl; import org.jbpm.formModeler.api.client.FormRenderContext; import org.jbpm.formModeler.api.client.FormRenderContextManager; import org.jbpm.formModeler.service.cdi.CDIBeanLocator; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import java.io.Serializable; import java.util.*; @ApplicationScoped public class FormProcessorImpl implements FormProcessor, Serializable { @Inject private Log log; // TODO: fix formulas //@Inject private FormChangeProcessor formChangeProcessor; @Inject private FieldHandlersManager fieldHandlersManager; @Inject FormRenderContextManager formRenderContextManager; private CSVParser rangeParser = new CSVParser(';'); private CSVParser optionParser = new CSVParser(','); protected FormStatus getContextFormStatus(FormRenderContext context) { return FormStatusManager.lookup().getFormStatus(context.getForm().getId(), context.getUID()); } protected FormStatus getFormStatus(Form form, String namespace) { return getFormStatus(form, namespace, new HashMap()); } protected FormStatus getFormStatus(Form form, String namespace, Map currentValues) { FormStatus formStatus = FormStatusManager.lookup().getFormStatus(form.getId(), namespace); return formStatus != null ? formStatus : createFormStatus(form, namespace, currentValues); } protected boolean existsFormStatus(Long formId, String namespace) { FormStatus formStatus = FormStatusManager.lookup().getFormStatus(formId, namespace); return formStatus != null; } protected FormStatus createFormStatus(Form form, String namespace, Map currentValues) { FormStatus fStatus = FormStatusManager.lookup().createFormStatus(form.getId(), namespace); setDefaultValues(form, namespace, currentValues); return fStatus; } protected void setDefaultValues(Form form, String namespace, Map currentValues) { if (form != null) { Set formFields = form.getFormFields(); Map params = new HashMap(5); Map rangeFormulas = (Map) getAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS); if (rangeFormulas == null) { rangeFormulas = new HashMap(); setAttribute(form, namespace, FormStatusData.CALCULATED_RANGE_FORMULAS, rangeFormulas); } for (Iterator iterator = formFields.iterator(); iterator.hasNext();) { Field field = (Field) iterator.next(); Object value = currentValues.get(field.getFieldName()); String inputName = getPrefix(form, namespace) + field.getFieldName(); try { FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType()); if ((value instanceof Map && !((Map)value).containsKey(FORM_MODE)) && !(value instanceof I18nSet)) ((Map)value).put(FORM_MODE, currentValues.get(FORM_MODE)); Map paramValue = handler.getParamValue(inputName, value, field.getFieldPattern()); if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); // Init ranges for simple combos String rangeFormula = field.getRangeFormula(); if (!StringUtils.isEmpty(rangeFormula) && rangeFormula.startsWith("{") && rangeFormula.endsWith("}")) { rangeFormula = rangeFormula.substring(1, rangeFormula.length() - 1); String[] options = rangeParser.parseLine(rangeFormula); if (options != null) { Map rangeValues = new HashMap(); for (String option : options) { String[] values = optionParser.parseLine(option); if (values != null && values.length == 2) { rangeValues.put(values[0], values[1]); } } rangeFormulas.put(field.getFieldName(), rangeValues); } } /* TODO: implement again formulas for default values Object defaultValue = pField.get("defaultValueFormula"); String inputName = getPrefix(pf, namespace) + pField.getFieldName(); try { String pattern = (String) pField.get("pattern"); Object value = currentValues.get(pField.getFieldName()); FieldHandler handler = pField.getFieldType().getManager(); if (value == null) { if (defaultValue != null) { if (!defaultValue.toString().startsWith("=")) { log.error("Incorrect formula specified for field " + pField.getFieldName()); continue; } if (handler instanceof DefaultFieldHandler) value = ((DefaultFieldHandler) handler).evaluateFormula(pField, defaultValue.toString().substring(1), "", new HashMap(0), "", namespace, new Date()); } } if ((value instanceof Map && !((Map)value).containsKey(FormProcessor.FORM_MODE)) && !(value instanceof I18nSet) && !(value instanceof I18nObject)) ((Map)value).put(FormProcessor.FORM_MODE, currentValues.get(FormProcessor.FORM_MODE)); Map paramValue = handler.getParamValue(inputName, value, pattern); if (paramValue != null && !paramValue.isEmpty()) params.putAll(paramValue); */ } catch (Exception e) { log.error("Error obtaining default values for " + inputName, e); } } setValues(form, namespace, params, null, true); } } protected void destroyFormStatus(Form form, String namespace) { FormStatusManager.lookup().destroyFormStatus(form.getId(), namespace); } public void setValues(Form form, String namespace, Map parameterMap, Map filesMap) { setValues(form, namespace, parameterMap, filesMap, false); } public void setValues(Form form, String namespace, Map parameterMap, Map filesMap, boolean incremental) { if (form != null) { namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE); FormStatus formStatus = getFormStatus(form, namespace); // if (!incremental) formStatus.getWrongFields().clear(); if (incremental) { Map mergedParameterMap = new HashMap(); if (formStatus.getLastParameterMap() != null) mergedParameterMap.putAll(formStatus.getLastParameterMap()); if (parameterMap != null) mergedParameterMap.putAll(parameterMap); formStatus.setLastParameterMap(mergedParameterMap); } else { formStatus.setLastParameterMap(parameterMap); } String inputsPrefix = getPrefix(form, namespace); for (Field field : form.getFormFields()) { setFieldValue(field, formStatus, inputsPrefix, parameterMap, filesMap, incremental); } } } public void modify(Form form, String namespace, String fieldName, Object value) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getInputValues().put(fieldName, value); propagateChangesToParentFormStatuses(formStatus, fieldName, value); } public void setAttribute(Form form, String namespace, String attributeName, Object attributeValue) { if (form != null) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getAttributes().put(attributeName, attributeValue); } } public Object getAttribute(Form form, String namespace, String attributeName) { if (form != null){ FormStatus formStatus = getFormStatus(form, namespace); return formStatus.getAttributes().get(attributeName); } return null; } protected void setFieldValue(Field field, FormStatus formStatus, String inputsPrefix, Map parameterMap, Map filesMap, boolean incremental) { String fieldName = field.getFieldName(); String inputName = inputsPrefix + fieldName; FieldHandler handler = fieldHandlersManager.getHandler(field.getFieldType()); try { Object previousValue = formStatus.getInputValues().get(fieldName); boolean isRequired = field.getFieldRequired().booleanValue(); if (!handler.isEvaluable(inputName, parameterMap, filesMap) && !(handler.isEmpty(previousValue) && isRequired)) return; Object value = null; boolean emptyNumber = false; try { value = handler.getValue(field, inputName, parameterMap, filesMap, field.getFieldType().getFieldClass(), previousValue); } catch (NumericFieldHandler.EmptyNumberException ene) { //Treat this case in particular, as returning null in a numeric field would make related formulas not working. emptyNumber = true; } if (incremental && value == null && !emptyNumber) { if (log.isDebugEnabled()) log.debug("Refusing to overwrite input value for parameter " + fieldName); } else { formStatus.getInputValues().put(fieldName, value); try { propagateChangesToParentFormStatuses(formStatus, fieldName, value); } catch (Exception e) { log.error("Error modifying formStatus: ", e); } boolean isEmpty = handler.isEmpty(value); if (isRequired && isEmpty && !incremental) { log.debug("Missing required field " + fieldName); formStatus.getWrongFields().add(fieldName); } else { formStatus.removeWrongField(fieldName); } } } catch (ProcessingMessagedException pme) { log.debug("Processing field: ", pme); formStatus.addErrorMessages(fieldName, pme.getMessages()); } catch (Exception e) { log.debug("Error setting field value:", e); if (!incremental) { formStatus.getInputValues().put(fieldName, null); formStatus.getWrongFields().add(fieldName); } } } protected void propagateChangesToParentFormStatuses(FormStatus formStatus, String fieldName, Object value) { FormStatus parent = FormStatusManager.lookup().getParent(formStatus); if (parent != null) { String fieldNameInParent = NamespaceManager.lookup().getNamespace(formStatus.getNamespace()).getFieldNameInParent(); Object valueInParent = parent.getInputValues().get(fieldNameInParent); if (valueInParent != null) { Map parentMapObjectRepresentation = null; if (valueInParent instanceof Map) { parentMapObjectRepresentation = (Map) valueInParent; } else if (valueInParent instanceof Map[]) { //Take the correct value Map editFieldPositions = (Map) parent.getAttributes().get(FormStatusData.EDIT_FIELD_POSITIONS); if (editFieldPositions != null) { Integer pos = (Integer) editFieldPositions.get(fieldNameInParent); if (pos != null) { parentMapObjectRepresentation = ((Map[]) valueInParent)[pos.intValue()]; } } } if (parentMapObjectRepresentation != null) { //Copy my value to parent parentMapObjectRepresentation.put(fieldName, value); propagateChangesToParentFormStatuses(parent, fieldNameInParent, valueInParent); } } } } public FormStatusData read(String ctxUid) { FormStatusDataImpl data = null; try { FormRenderContext context = formRenderContextManager.getFormRenderContext(ctxUid); if (context == null ) return null; FormStatus formStatus = getContextFormStatus(context); boolean isNew = formStatus == null; if (isNew) { formStatus = createContextFormStatus(context); } data = new FormStatusDataImpl(formStatus, isNew); } catch (Exception e) { log.error("Error: ", e); } return data; } protected FormStatus createContextFormStatus(FormRenderContext context) throws Exception { Map values = new HashMap(); Map<String, Object> bindingData = context.getBindingData(); if (bindingData != null && !bindingData.isEmpty()) { Form form = context.getForm(); Set<Field> fields = form.getFormFields(); if (fields != null) { for (Field field : form.getFormFields()) { String bindingString = field.getBindingStr(); if (!StringUtils.isEmpty(bindingString)) { bindingString = bindingString.substring(1, bindingString.length() - 1); boolean canSetValue = bindingString.indexOf("/") > 0; if (canSetValue) { String holderId = bindingString.substring(0, bindingString.indexOf("/")); String holderFieldId = bindingString.substring(holderId.length() + 1); DataHolder holder = form.getDataHolderById(holderId); if (holder != null && !StringUtils.isEmpty(holderFieldId)) { Object value = bindingData.get(holder.getId()); if (value == null) continue; values.put(field.getFieldName(), holder.readValue(value, holderFieldId)); } } else { Object value = bindingData.get(bindingString); if (value != null) values.put(bindingString, value); } } } } } return getFormStatus(context.getForm(), context.getUID(), values); } public FormStatusData read(Form form, String namespace, Map currentValues) { boolean exists = existsFormStatus(form.getId(), namespace); if (currentValues == null) currentValues = new HashMap(); FormStatus formStatus = getFormStatus(form, namespace, currentValues); FormStatusDataImpl data = null; try { data = new FormStatusDataImpl(formStatus, !exists); } catch (Exception e) { log.error("Error: ", e); } return data; } public FormStatusData read(Form form, String namespace) { return read(form, namespace, new HashMap<String, Object>()); } public void flushPendingCalculations(Form form, String namespace) { if (formChangeProcessor != null) { formChangeProcessor.process(form, namespace, new FormChangeResponse());//Response is ignored, we just need the session values. } } public void persist(String ctxUid) throws Exception { ctxUid = StringUtils.defaultIfEmpty(ctxUid, FormProcessor.DEFAULT_NAMESPACE); persist(formRenderContextManager.getFormRenderContext(ctxUid)); } public void persist(FormRenderContext context) throws Exception { Form form = context.getForm(); Map mapToPersist = getFilteredMapRepresentationToPersist(form, context.getUID()); for (Iterator it = mapToPersist.keySet().iterator(); it.hasNext();) { String fieldName = (String) it.next(); Field field = form.getField(fieldName); if (field != null) { String bindingString = field.getBindingStr(); if (!StringUtils.isEmpty(bindingString)) { bindingString = bindingString.substring(1, bindingString.length() - 1); boolean canBind = bindingString.indexOf("/") > 0; if (canBind) { String holderId = bindingString.substring(0, bindingString.indexOf("/")); String holderFieldId = bindingString.substring(holderId.length() + 1); DataHolder holder = form.getDataHolderById(holderId); if (holder != null && !StringUtils.isEmpty(holderFieldId)) holder.writeValue(context.getBindingData().get(holderId), holderFieldId, mapToPersist.get(fieldName)); else canBind = false; } if (!canBind) { log.debug("Unable to bind DataHolder for field '" + fieldName + "' to '" + bindingString + "'. This may be caused because bindingString is incorrect or the form doesn't contains the defined DataHolder."); context.getBindingData().put(bindingString, mapToPersist.get(fieldName)); } } } } } public Map getMapRepresentationToPersist(Form form, String namespace) throws Exception { namespace = StringUtils.defaultIfEmpty(namespace, DEFAULT_NAMESPACE); flushPendingCalculations(form, namespace); Map m = new HashMap(); FormStatus formStatus = getFormStatus(form, namespace); if (!formStatus.getWrongFields().isEmpty()) { throw new IllegalArgumentException("Validation error."); } fillObjectValues(m, formStatus.getInputValues(), form); Set s = (Set) m.get(MODIFIED_FIELD_NAMES); if (s == null) { m.put(MODIFIED_FIELD_NAMES, s = new TreeSet()); } s.addAll(form.getFieldNames()); return m; } protected Map getFilteredMapRepresentationToPersist(Form form, String namespace) throws Exception { Map inputValues = getMapRepresentationToPersist(form, namespace); Map mapToPersist = filterMapRepresentationToPersist(inputValues); return mapToPersist; } public Map filterMapRepresentationToPersist(Map inputValues) throws Exception { Map filteredMap = new HashMap(); Set keys = inputValues.keySet(); for (Iterator iterator = keys.iterator(); iterator.hasNext();) { String key = (String) iterator.next(); filteredMap.put(key, inputValues.get(key)); } return filteredMap; } /** * Copy to obj values read from status map values * * @param obj * @param values * @throws Exception */ protected void fillObjectValues(final Map obj, Map values, Form form) throws Exception { Map valuesToSet = new HashMap(); for (Iterator it = values.keySet().iterator(); it.hasNext();) { String propertyName = (String) it.next(); Object propertyValue = values.get(propertyName); valuesToSet.put(propertyName, propertyValue); } obj.putAll(valuesToSet); } protected FormManagerImpl getFormsManager() { return (FormManagerImpl) CDIBeanLocator.getBeanByType(FormManagerImpl.class); } @Override public void clear(FormRenderContext context) { clear(context.getForm(), context.getUID()); } @Override public void clear(String ctxUID) { clear(formRenderContextManager.getFormRenderContext(ctxUID)); } public void clear(Form form, String namespace) { if (log.isDebugEnabled()) log.debug("Clearing form status for form " + form.getName() + " with namespace '" + namespace + "'"); destroyFormStatus(form, namespace); } public void clearField(Form form, String namespace, String fieldName) { FormStatus formStatus = getFormStatus(form, namespace); formStatus.getInputValues().remove(fieldName); } public void clearFieldErrors(Form form, String namespace) { FormStatusManager.lookup().cascadeClearWrongFields(form.getId(), namespace); } public void forceWrongField(Form form, String namespace, String fieldName) { FormStatusManager.lookup().getFormStatus(form.getId(), namespace).getWrongFields().add(fieldName); } protected String getPrefix(Form form, String namespace) { return namespace + FormProcessor.NAMESPACE_SEPARATOR + form.getId() + FormProcessor.NAMESPACE_SEPARATOR; } }
little refactor
jbpm-form-modeler-core/jbpm-form-modeler-service/jbpm-form-modeler-ui/src/main/java/org/jbpm/formModeler/core/processing/impl/FormProcessorImpl.java
little refactor
Java
apache-2.0
1cf095c4f62b9f634ed2f4f09bca8d391575bee1
0
CS-SI/Orekit,CS-SI/Orekit,petrushy/Orekit,petrushy/Orekit
/* Copyright 2002-2018 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.bodies; import java.io.Serializable; import java.text.NumberFormat; import org.hipparchus.geometry.euclidean.threed.Vector3D; import org.hipparchus.util.CompositeFormat; import org.hipparchus.util.FastMath; import org.hipparchus.util.MathUtils; /** Point location relative to a 2D body surface. * <p>Instance of this class are guaranteed to be immutable.</p> * @see BodyShape * @see FieldGeodeticPoint * @author Luc Maisonobe */ public class GeodeticPoint implements Serializable { /** Serializable UID. */ private static final long serialVersionUID = 7862466825590075399L; /** Latitude of the point (rad). */ private final double latitude; /** Longitude of the point (rad). */ private final double longitude; /** Altitude of the point (m). */ private final double altitude; /** Zenith direction. */ private transient Vector3D zenith; /** Nadir direction. */ private transient Vector3D nadir; /** North direction. */ private transient Vector3D north; /** South direction. */ private transient Vector3D south; /** East direction. */ private transient Vector3D east; /** West direction. */ private transient Vector3D west; /** * Build a new instance. The angular coordinates will be normalized so that * the latitude is between ±π/2 and the longitude is between ±π. * * @param latitude latitude of the point * @param longitude longitude of the point * @param altitude altitude of the point */ public GeodeticPoint(final double latitude, final double longitude, final double altitude) { double lat = MathUtils.normalizeAngle(latitude, FastMath.PI / 2); double lon = MathUtils.normalizeAngle(longitude, 0); if (lat > FastMath.PI / 2.0) { // latitude is beyond the pole -> add 180 to longitude lat = FastMath.PI - lat; lon = MathUtils.normalizeAngle(longitude + FastMath.PI, 0); } this.latitude = lat; this.longitude = lon; this.altitude = altitude; } /** Get the latitude. * @return latitude, an angular value in the range [-π/2, π/2] */ public double getLatitude() { return latitude; } /** Get the longitude. * @return longitude, an angular value in the range [-π, π] */ public double getLongitude() { return longitude; } /** Get the altitude. * @return altitude */ public double getAltitude() { return altitude; } /** Get the direction above the point, expressed in parent shape frame. * <p>The zenith direction is defined as the normal to local horizontal plane.</p> * @return unit vector in the zenith direction * @see #getNadir() */ public Vector3D getZenith() { if (zenith == null) { final double cosLat = FastMath.cos(latitude); final double sinLat = FastMath.sin(latitude); final double cosLon = FastMath.cos(longitude); final double sinLon = FastMath.sin(longitude); zenith = new Vector3D(cosLon * cosLat, sinLon * cosLat, sinLat); } return zenith; } /** Get the direction below the point, expressed in parent shape frame. * <p>The nadir direction is the opposite of zenith direction.</p> * @return unit vector in the nadir direction * @see #getZenith() */ public Vector3D getNadir() { if (nadir == null) { nadir = getZenith().negate(); } return nadir; } /** Get the direction to the north of point, expressed in parent shape frame. * <p>The north direction is defined in the horizontal plane * (normal to zenith direction) and following the local meridian.</p> * @return unit vector in the north direction * @see #getSouth() */ public Vector3D getNorth() { if (north == null) { final double cosLat = FastMath.cos(latitude); final double sinLat = FastMath.sin(latitude); final double cosLon = FastMath.cos(longitude); final double sinLon = FastMath.sin(longitude); north = new Vector3D(-cosLon * sinLat, -sinLon * sinLat, cosLat); } return north; } /** Get the direction to the south of point, expressed in parent shape frame. * <p>The south direction is the opposite of north direction.</p> * @return unit vector in the south direction * @see #getNorth() */ public Vector3D getSouth() { if (south == null) { south = getNorth().negate(); } return south; } /** Get the direction to the east of point, expressed in parent shape frame. * <p>The east direction is defined in the horizontal plane * in order to complete direct triangle (east, north, zenith).</p> * @return unit vector in the east direction * @see #getWest() */ public Vector3D getEast() { if (east == null) { east = new Vector3D(-FastMath.sin(longitude), FastMath.cos(longitude), 0); } return east; } /** Get the direction to the west of point, expressed in parent shape frame. * <p>The west direction is the opposite of east direction.</p> * @return unit vector in the west direction * @see #getEast() */ public Vector3D getWest() { if (west == null) { west = getEast().negate(); } return west; } @Override public boolean equals(final Object object) { if (object instanceof GeodeticPoint) { final GeodeticPoint other = (GeodeticPoint) object; return this.getLatitude() == other.getLatitude() && this.getLongitude() == other.getLongitude() && this.getAltitude() == other.getAltitude(); } return false; } @Override public int hashCode() { return Double.valueOf(this.getLatitude()).hashCode() ^ Double.valueOf(this.getLongitude()).hashCode() ^ Double.valueOf(this.getAltitude()).hashCode(); } @Override public String toString() { final NumberFormat format = CompositeFormat.getDefaultNumberFormat(); return "{lat: " + format.format(FastMath.toDegrees(this.getLatitude())) + " deg, lon: " + format.format(FastMath.toDegrees(this.getLongitude())) + " deg, alt: " + format.format(this.getAltitude()) + "}"; } }
src/main/java/org/orekit/bodies/GeodeticPoint.java
/* Copyright 2002-2018 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.orekit.bodies; import java.io.Serializable; import java.text.NumberFormat; import org.hipparchus.geometry.euclidean.threed.Vector3D; import org.hipparchus.util.CompositeFormat; import org.hipparchus.util.FastMath; import org.hipparchus.util.MathUtils; /** Point location relative to a 2D body surface. * <p>Instance of this class are guaranteed to be immutable.</p> * @see BodyShape * @see FieldGeodeticPoint * @author Luc Maisonobe */ public class GeodeticPoint implements Serializable { /** Serializable UID. */ private static final long serialVersionUID = 7862466825590075399L; /** Latitude of the point (rad). */ private final double latitude; /** Longitude of the point (rad). */ private final double longitude; /** Altitude of the point (m). */ private final double altitude; /** Zenith direction. */ private transient Vector3D zenith; /** Nadir direction. */ private transient Vector3D nadir; /** North direction. */ private transient Vector3D north; /** South direction. */ private transient Vector3D south; /** East direction. */ private transient Vector3D east; /** West direction. */ private transient Vector3D west; /** * Build a new instance. The angular coordinates will be normalized so that * the latitude is between ±π/2 and the longitude is between ±π. * * @param latitude latitude of the point * @param longitude longitude of the point * @param altitude altitude of the point */ public GeodeticPoint(final double latitude, final double longitude, final double altitude) { double lat = MathUtils.normalizeAngle(latitude, FastMath.PI / 2); double lon = MathUtils.normalizeAngle(longitude, 0); if (lat > FastMath.PI / 2.0) { // latitude is beyond the pole -> add 180 to longitude lat = FastMath.PI - lat; lon = MathUtils.normalizeAngle(longitude + FastMath.PI, 0); } this.latitude = lat; this.longitude = lon; this.altitude = altitude; } /** Get the latitude. * @return latitude, an angular value in the range [-π/2, π/2] */ public double getLatitude() { return latitude; } /** Get the longitude. * @return longitude, an angular value in the range [-π, π] */ public double getLongitude() { return longitude; } /** Get the altitude. * @return altitude */ public double getAltitude() { return altitude; } /** Get the direction above the point, expressed in parent shape frame. * <p>The zenith direction is defined as the normal to local horizontal plane.</p> * @return unit vector in the zenith direction * @see #getNadir() */ public Vector3D getZenith() { if (zenith == null) { final double cosLat = FastMath.cos(latitude); final double sinLat = FastMath.sin(latitude); final double cosLon = FastMath.cos(longitude); final double sinLon = FastMath.sin(longitude); zenith = new Vector3D(cosLon * cosLat, sinLon * cosLat, sinLat); } return zenith; } /** Get the direction below the point, expressed in parent shape frame. * <p>The nadir direction is the opposite of zenith direction.</p> * @return unit vector in the nadir direction * @see #getZenith() */ public Vector3D getNadir() { if (nadir == null) { nadir = getZenith().negate(); } return nadir; } /** Get the direction to the north of point, expressed in parent shape frame. * <p>The north direction is defined in the horizontal plane * (normal to zenith direction) and following the local meridian.</p> * @return unit vector in the north direction * @see #getSouth() */ public Vector3D getNorth() { if (north == null) { final double cosLat = FastMath.cos(latitude); final double sinLat = FastMath.sin(latitude); final double cosLon = FastMath.cos(longitude); final double sinLon = FastMath.sin(longitude); north = new Vector3D(-cosLon * sinLat, -sinLon * sinLat, cosLat); } return north; } /** Get the direction to the south of point, expressed in parent shape frame. * <p>The south direction is the opposite of north direction.</p> * @return unit vector in the south direction * @see #getNorth() */ public Vector3D getSouth() { if (south == null) { south = getNorth().negate(); } return south; } /** Get the direction to the east of point, expressed in parent shape frame. * <p>The east direction is defined in the horizontal plane * in order to complete direct triangle (east, north, zenith).</p> * @return unit vector in the east direction * @see #getWest() */ public Vector3D getEast() { if (east == null) { east = new Vector3D(-FastMath.sin(longitude), FastMath.cos(longitude), 0); } return east; } /** Get the direction to the west of point, expressed in parent shape frame. * <p>The west direction is the opposite of east direction.</p> * @return unit vector in the west direction * @see #getEast() */ public Vector3D getWest() { if (west == null) { west = getEast().negate(); } return west; } @Override public boolean equals(final Object object) { if (object instanceof GeodeticPoint) { final GeodeticPoint other = (GeodeticPoint) object; return this.getLatitude() == other.getLatitude() && this.getLongitude() == other.getLongitude() && this.getAltitude() == other.getAltitude(); } return false; } @Override public int hashCode() { return new Double(this.getLatitude()).hashCode() ^ new Double(this.getLongitude()).hashCode() ^ new Double(this.getAltitude()).hashCode(); } @Override public String toString() { final NumberFormat format = CompositeFormat.getDefaultNumberFormat(); return "{lat: " + format.format(FastMath.toDegrees(this.getLatitude())) + " deg, lon: " + format.format(FastMath.toDegrees(this.getLongitude())) + " deg, alt: " + format.format(this.getAltitude()) + "}"; } }
Fixed compiler warning.
src/main/java/org/orekit/bodies/GeodeticPoint.java
Fixed compiler warning.
Java
apache-2.0
3aaca3bd5657bedbcaa03370ebf14846edb1f6b1
0
Graphity/graphity-client,AtomGraph/Web-Client,Graphity/graphity-client,AtomGraph/Web-Client,AtomGraph/Web-Client
/** * Copyright 2012 Martynas Jusevičius <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.atomgraph.client.writer; import com.atomgraph.client.exception.OntClassNotFoundException; import com.atomgraph.client.exception.OntologyException; import com.atomgraph.client.util.Constructor; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import com.sun.jersey.spi.resource.Singleton; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.*; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.jena.iri.IRI; import org.apache.jena.iri.IRIFactory; import org.apache.jena.rdf.model.RDFWriter; import org.apache.jena.rdfxml.xmloutput.impl.Basic; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFLanguages; import org.apache.jena.riot.checker.CheckerIRI; import org.apache.jena.riot.system.ErrorHandlerFactory; import com.atomgraph.client.util.DataManager; import com.atomgraph.client.util.OntologyProvider; import com.atomgraph.client.util.XSLTBuilder; import com.atomgraph.client.vocabulary.AC; import com.atomgraph.client.vocabulary.LDT; import com.atomgraph.core.vocabulary.A; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.HashSet; import java.util.Locale; import java.util.Set; import javax.xml.transform.sax.SAXTransformerFactory; import net.sf.saxon.trans.UnparsedTextURIResolver; import org.apache.jena.ontology.OntClass; import org.apache.jena.ontology.OntDocumentManager; import org.apache.jena.query.Dataset; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Transforms RDF with XSLT stylesheet and writes (X)HTML result to response. * Needs to be registered in the application. * * @author Martynas Jusevičius <[email protected]> * @see org.apache.jena.query.Dataset * @see javax.ws.rs.ext.MessageBodyWriter */ @Provider @Singleton @Produces({MediaType.TEXT_HTML + ";charset=UTF-8"}) // MediaType.APPLICATION_XHTML_XML + ";charset=UTF-8", public class DatasetXSLTWriter implements MessageBodyWriter<Dataset> { private static final Logger log = LoggerFactory.getLogger(DatasetXSLTWriter.class); private static final Set<String> NAMESPACES; static { NAMESPACES = new HashSet<>(); NAMESPACES.add(AC.NS); } private final Templates templates; private final OntModelSpec ontModelSpec; @Context private UriInfo uriInfo; @Context private Request request; @Context private HttpHeaders httpHeaders; @Context private Providers providers; @Context private HttpServletRequest httpServletRequest; /** * Constructs from XSLT builder. * * @param templates compiled XSLT stylesheet * @param ontModelSpec ontology model specification * @see com.atomgraph.client.util.XSLTBuilder */ public DatasetXSLTWriter(Templates templates, OntModelSpec ontModelSpec) { if (templates == null) throw new IllegalArgumentException("Templates cannot be null"); if (ontModelSpec == null) throw new IllegalArgumentException("OntModelSpec cannot be null"); this.templates = templates; this.ontModelSpec = ontModelSpec; } @Override public void writeTo(Dataset dataset, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headerMap, OutputStream entityStream) throws IOException { if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", headerMap, mediaType); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { Templates stylesheet = getTemplates(); //RDFWriter writer = model.getWriter(RDFLanguages.RDFXML.getName()); RDFWriter writer = new Basic(); // workaround for Jena 3.0.1 bug: https://issues.apache.org/jira/browse/JENA-1168 writer.setProperty("allowBadURIs", true); // round-tripping RDF/POST with user input may contain invalid URIs writer.write(dataset.getDefaultModel(), baos, null); XSLTBuilder builder = setParameters(com.atomgraph.client.util.saxon.XSLTBuilder.newInstance(getTransformerFactory()). resolver((UnparsedTextURIResolver)getDataManager()). stylesheet(stylesheet). document(new ByteArrayInputStream(baos.toByteArray())), dataset, headerMap). resolver(getDataManager()). result(new StreamResult(entityStream)); builder.outputProperty(OutputKeys.ENCODING, UTF_8.name()); if (mediaType.isCompatible(MediaType.TEXT_HTML_TYPE)) { builder.outputProperty(OutputKeys.METHOD, "html"); builder.outputProperty(OutputKeys.MEDIA_TYPE, MediaType.TEXT_HTML); builder.outputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/html4/strict.dtd"); builder.outputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01//EN"); } if (mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)) { builder.outputProperty(OutputKeys.METHOD, "xhtml"); builder.outputProperty(OutputKeys.MEDIA_TYPE, MediaType.APPLICATION_XHTML_XML); builder.outputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"); builder.outputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN"); } builder.transform(); } catch (TransformerException ex) { if (log.isErrorEnabled()) log.error("XSLT transformation failed", ex); throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); // TO-DO: make Mapper } } public void write(Dataset dataset, OutputStream entityStream) throws TransformerException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); dataset.getDefaultModel().write(baos, RDFLanguages.RDFXML.getName(), null); XSLTBuilder.newInstance(getTransformerFactory()). stylesheet(getTemplates()). document(new ByteArrayInputStream(baos.toByteArray())). resolver(getDataManager()). result(new StreamResult(entityStream)). transform(); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Dataset.class.isAssignableFrom(type); } @Override public long getSize(Dataset dataset, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public URI getAbsolutePath() { return getUriInfo().getAbsolutePath(); } public URI getRequestURI() { return getUriInfo().getRequestUri(); } public URI getURIParam(UriInfo uriInfo, String name) throws URISyntaxException { if (uriInfo == null) throw new IllegalArgumentException("UriInfo cannot be null"); if (name == null) throw new IllegalArgumentException("String cannot be null"); if (uriInfo.getQueryParameters().containsKey(name)) return new URI(uriInfo.getQueryParameters().getFirst(name)); return null; } public URI getURI() throws URISyntaxException { return getURIParam(getUriInfo(), AC.uri.getLocalName()); } public URI getEndpointURI() throws URISyntaxException { return getURIParam(getUriInfo(), AC.endpoint.getLocalName()); } public String getQuery() { if (getUriInfo().getQueryParameters().containsKey(AC.query.getLocalName())) return getUriInfo().getQueryParameters().getFirst(AC.query.getLocalName()); return null; } public static Source getSource(Model model) throws IOException { if (model == null) throw new IllegalArgumentException("Model cannot be null"); if (log.isDebugEnabled()) log.debug("Number of Model stmts read: {}", model.size()); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { model.write(stream, RDFLanguages.RDFXML.getName(), null); if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length); return new StreamSource(new ByteArrayInputStream(stream.toByteArray())); } } public static Source getSource(OntModel ontModel, boolean writeAll) throws IOException { if (!writeAll) return getSource(ontModel); if (ontModel == null) throw new IllegalArgumentException("OntModel cannot be null"); if (log.isDebugEnabled()) log.debug("Number of OntModel stmts read: {}", ontModel.size()); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { ontModel.writeAll(stream, Lang.RDFXML.getName(), null); if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length); return new StreamSource(new ByteArrayInputStream(stream.toByteArray())); } } public URI getContextURI() { return URI.create(getHttpServletRequest().getRequestURL().toString()). resolve(getHttpServletRequest().getContextPath() + "/"); } public Templates getTemplates() { if (templates != null) return templates; else { ContextResolver<Templates> cr = getProviders().getContextResolver(Templates.class, null); return cr.getContext(Templates.class); } } public XSLTBuilder setParameters(XSLTBuilder builder, Dataset dataset, MultivaluedMap<String, Object> headerMap) throws TransformerException { if (builder == null) throw new IllegalArgumentException("XSLTBuilder cannot be null"); if (headerMap == null) throw new IllegalArgumentException("MultivaluedMap cannot be null"); builder. //parameter("{" + A.absolutePath.getNameSpace() + "}" + A.absolutePath.getLocalName(), getAbsolutePath()). //parameter("{" + A.requestUri.getNameSpace() + "}" + A.requestUri.getLocalName(), getRequestURI()). parameter("{" + A.method.getNameSpace() + "}" + A.method.getLocalName(), getRequest().getMethod()). parameter("{" + A.httpHeaders.getNameSpace() + "}" + A.httpHeaders.getLocalName(), headerMap.toString()). parameter("{" + AC.contextUri.getNameSpace() + "}" + AC.contextUri.getLocalName(), getContextURI()); try { if (getURI() != null) builder.parameter("{" + AC.uri.getNameSpace() + "}" + AC.uri.getLocalName(), getURI()); if (getEndpointURI() != null) builder.parameter("{" + AC.endpoint.getNameSpace() + "}" + AC.endpoint.getLocalName(), getEndpointURI()); if (getQuery() != null) builder.parameter("{" + AC.query.getNameSpace() + "}" + AC.query.getLocalName(), getQuery()); List<URI> modes = getModes(getSupportedNamespaces()); // check if explicit mode URL parameter is provided URI ontologyURI = (URI)getHttpServletRequest().getAttribute(LDT.ontology.getURI()); if (ontologyURI != null) { builder.parameter("{" + LDT.ontology.getNameSpace() + "}" + LDT.ontology.getLocalName(), ontologyURI); OntModel sitemap = getOntModel(ontologyURI.toString()); builder.parameter("{" + AC.sitemap.getNameSpace() + "}" + AC.sitemap.getLocalName(), getSource(sitemap, true)); if (getBaseUri() != null) { builder.parameter("{" + LDT.base.getNameSpace() + "}" + LDT.base.getLocalName(), getBaseUri()); String forClassURI = getUriInfo().getQueryParameters().getFirst(AC.forClass.getLocalName()); if (forClassURI != null) { OntClass forClass = sitemap.getOntClass(forClassURI); if (forClass == null) throw new OntClassNotFoundException(forClassURI); // do we need this check here? builder.parameter("{" + AC.forClass.getNameSpace() + "}" + AC.forClass.getLocalName(), URI.create(forClass.getURI())); } } if (getTemplateURI() != null) { builder.parameter("{" + LDT.template.getNameSpace() + "}" + LDT.template.getLocalName(), getTemplateURI()); if (modes.isEmpty()) // attempt to retrieve default mode via matched template Link from the app (server) sitemap ontology { Resource template = sitemap.getResource(getTemplateURI().toString()); StmtIterator it = template.listProperties(AC.mode); try { while (it.hasNext()) { Statement modeStmt = it.next(); if (!modeStmt.getObject().isURIResource()) throw new OntologyException("Value is not a URI resource", template, AC.mode); modes.add(URI.create(modeStmt.getResource().getURI())); } } finally { it.close(); } } } } builder.parameter("{" + AC.mode.getNameSpace() + "}" + AC.mode.getLocalName(), modes); // workaround for Google Maps and Saxon-CE // They currently seem to work only in HTML mode and not in XHTML, because of document.write() usage // https://saxonica.plan.io/issues/1447 // // https://code.google.com/p/gmaps-api-issues/issues/detail?id=2820 // MediaType customMediaType = getCustomMediaType(modes); // if (customMediaType != null) // { // if (log.isDebugEnabled()) log.debug("Overriding response media type with '{}'", customMediaType); // List<Object> contentTypes = new ArrayList(); // contentTypes.add(customMediaType); // headerMap.put(HttpHeaders.CONTENT_TYPE, contentTypes); // } MediaType contentType = (MediaType)headerMap.getFirst(HttpHeaders.CONTENT_TYPE); if (contentType != null) { if (log.isDebugEnabled()) log.debug("Writing Model using XSLT media type: {}", contentType); builder.outputProperty(OutputKeys.MEDIA_TYPE, contentType.toString()); } Locale locale = (Locale)headerMap.getFirst(HttpHeaders.CONTENT_LANGUAGE); if (locale != null) { if (log.isDebugEnabled()) log.debug("Writing Model using language: {}", locale.toLanguageTag()); builder.parameter("{" + LDT.lang.getNameSpace() + "}" + LDT.lang.getLocalName(), locale.toLanguageTag()); } return builder; } catch (IOException ex) { if (log.isErrorEnabled()) log.error("Error reading Source stream"); throw new TransformerException(ex); } catch (URISyntaxException ex) { if (log.isErrorEnabled()) log.error("URI syntax exception"); throw new TransformerException(ex); } } public Set<String> getSupportedNamespaces() { return NAMESPACES; } public OntDocumentManager getOntDocumentManager() { return OntDocumentManager.getInstance(); } public OntModel getOntModel(String ontologyURI) { return getOntModel(ontologyURI, getOntModelSpec()); } public OntModel getOntModel(String ontologyURI, OntModelSpec ontModelSpec) { return new OntologyProvider().getOntModel(getOntDocumentManager(), ontologyURI, ontModelSpec); } public List<URI> getModes(Set<String> namespaces) { return getModes(getUriInfo(), namespaces); } public List<URI> getModes(UriInfo uriInfo, Set<String> namespaces) // mode is a client parameter, no need to parse hypermedia state here { if (uriInfo == null) throw new IllegalArgumentException("UriInfo cannot be null"); if (namespaces == null) throw new IllegalArgumentException("Namespace Set cannot be null"); List<URI> modes = new ArrayList<>(); if (uriInfo.getQueryParameters().containsKey(AC.mode.getLocalName())) { // matching parameter names not to namespace URIs, but to local names instead! List<String> modeParamValues = uriInfo.getQueryParameters().get(AC.mode.getLocalName()); for (String modeParamValue : modeParamValues) { Resource paramMode = ResourceFactory.createResource(modeParamValue); // only consider values from the known namespaces if (namespaces.contains(paramMode.getNameSpace())) modes.add(URI.create(modeParamValue)); } } return modes; } public static IRI checkURI(String classIRIStr) { if (classIRIStr == null) throw new IllegalArgumentException("URI String cannot be null"); IRI classIRI = IRIFactory.iriImplementation().create(classIRIStr); // throws Exceptions on bad URIs: CheckerIRI.iriViolations(classIRI, ErrorHandlerFactory.getDefaultErrorHandler()); return classIRI; } public static Source getConstructedSource(URI ontologyURI, List<URI> classURIs, URI baseURI) throws URISyntaxException, IOException { if (ontologyURI == null) throw new IllegalArgumentException("Ontology URI cannot be null"); if (classURIs == null) throw new IllegalArgumentException("Class URIs cannot be null"); if (baseURI == null) throw new IllegalArgumentException("Base URI cannot be null"); OntModel ontModel = OntDocumentManager.getInstance().getOntology(ontologyURI.toString(), OntModelSpec.OWL_MEM); Model instances = ModelFactory.createDefaultModel(); for (URI classURI : classURIs) { OntClass forClass = ontModel.getOntClass(checkURI(classURI.toString()).toURI().toString()); if (forClass != null) new Constructor().construct(forClass, instances, baseURI.toString()); // TO-DO: else throw error? } return getSource(instances); } public URI getBaseUri() { return (URI)getHttpServletRequest().getAttribute(LDT.base.getURI()); // set in ProxyResourceBase } public URI getTemplateURI() { return (URI)getHttpServletRequest().getAttribute(LDT.template.getURI()); // set in ProxyResourceBase } public UriInfo getUriInfo() { return uriInfo; } public Request getRequest() { return request; } public HttpHeaders getHttpHeaders() { return httpHeaders; } public HttpServletRequest getHttpServletRequest() { return httpServletRequest; } public OntModelSpec getOntModelSpec() { return ontModelSpec; } public Providers getProviders() { return providers; } public DataManager getDataManager() { ContextResolver<DataManager> cr = getProviders().getContextResolver(DataManager.class, null); return cr.getContext(DataManager.class); } public SAXTransformerFactory getTransformerFactory() { return ((SAXTransformerFactory)TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null)); } }
src/main/java/com/atomgraph/client/writer/DatasetXSLTWriter.java
/** * Copyright 2012 Martynas Jusevičius <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.atomgraph.client.writer; import com.atomgraph.client.exception.OntClassNotFoundException; import com.atomgraph.client.exception.OntologyException; import com.atomgraph.client.util.Constructor; import org.apache.jena.ontology.OntModel; import org.apache.jena.ontology.OntModelSpec; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import com.sun.jersey.spi.resource.Singleton; import java.io.*; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.*; import javax.ws.rs.ext.ContextResolver; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.Providers; import javax.xml.transform.*; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.jena.iri.IRI; import org.apache.jena.iri.IRIFactory; import org.apache.jena.rdf.model.RDFWriter; import org.apache.jena.rdfxml.xmloutput.impl.Basic; import org.apache.jena.riot.Lang; import org.apache.jena.riot.RDFLanguages; import org.apache.jena.riot.checker.CheckerIRI; import org.apache.jena.riot.system.ErrorHandlerFactory; import com.atomgraph.client.util.DataManager; import com.atomgraph.client.util.OntologyProvider; import com.atomgraph.client.util.XSLTBuilder; import com.atomgraph.client.vocabulary.AC; import com.atomgraph.client.vocabulary.LDT; import com.atomgraph.core.vocabulary.A; import static java.nio.charset.StandardCharsets.UTF_8; import java.util.HashSet; import java.util.Locale; import java.util.Set; import javax.xml.transform.sax.SAXTransformerFactory; import net.sf.saxon.trans.UnparsedTextURIResolver; import org.apache.jena.ontology.OntClass; import org.apache.jena.ontology.OntDocumentManager; import org.apache.jena.query.Dataset; import org.apache.jena.rdf.model.ModelFactory; import org.apache.jena.rdf.model.ResourceFactory; import org.apache.jena.rdf.model.Statement; import org.apache.jena.rdf.model.StmtIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Transforms RDF with XSLT stylesheet and writes (X)HTML result to response. * Needs to be registered in the application. * * @author Martynas Jusevičius <[email protected]> * @see org.apache.jena.query.Dataset * @see javax.ws.rs.ext.MessageBodyWriter */ @Provider @Singleton @Produces({MediaType.TEXT_HTML + ";charset=UTF-8"}) // MediaType.APPLICATION_XHTML_XML + ";charset=UTF-8", public class DatasetXSLTWriter implements MessageBodyWriter<Dataset> { private static final Logger log = LoggerFactory.getLogger(DatasetXSLTWriter.class); private static final Set<String> NAMESPACES; static { NAMESPACES = new HashSet<>(); NAMESPACES.add(AC.NS); } private final Templates templates; private final OntModelSpec ontModelSpec; private final Map<URI, MediaType> modeMediaTypeMap = new HashMap<>(); // would String not suffice as the key? { modeMediaTypeMap.put(URI.create(AC.EditMode.getURI()), MediaType.TEXT_HTML_TYPE); modeMediaTypeMap.put(URI.create(AC.MapMode.getURI()), MediaType.TEXT_HTML_TYPE); } @Context private UriInfo uriInfo; @Context private Request request; @Context private HttpHeaders httpHeaders; @Context private Providers providers; @Context private HttpServletRequest httpServletRequest; /** * Constructs from XSLT builder. * * @param templates compiled XSLT stylesheet * @param ontModelSpec ontology model specification * @see com.atomgraph.client.util.XSLTBuilder */ public DatasetXSLTWriter(Templates templates, OntModelSpec ontModelSpec) { if (templates == null) throw new IllegalArgumentException("Templates cannot be null"); if (ontModelSpec == null) throw new IllegalArgumentException("OntModelSpec cannot be null"); this.templates = templates; this.ontModelSpec = ontModelSpec; } @Override public void writeTo(Dataset dataset, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> headerMap, OutputStream entityStream) throws IOException { if (log.isTraceEnabled()) log.trace("Writing Model with HTTP headers: {} MediaType: {}", headerMap, mediaType); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { Templates stylesheet = getTemplates(); //RDFWriter writer = model.getWriter(RDFLanguages.RDFXML.getName()); RDFWriter writer = new Basic(); // workaround for Jena 3.0.1 bug: https://issues.apache.org/jira/browse/JENA-1168 writer.setProperty("allowBadURIs", true); // round-tripping RDF/POST with user input may contain invalid URIs writer.write(dataset.getDefaultModel(), baos, null); XSLTBuilder builder = setParameters(com.atomgraph.client.util.saxon.XSLTBuilder.newInstance(getTransformerFactory()). resolver((UnparsedTextURIResolver)getDataManager()). stylesheet(stylesheet). document(new ByteArrayInputStream(baos.toByteArray())), dataset, headerMap). resolver(getDataManager()). result(new StreamResult(entityStream)); builder.outputProperty(OutputKeys.ENCODING, UTF_8.name()); if (mediaType.isCompatible(MediaType.TEXT_HTML_TYPE)) { builder.outputProperty(OutputKeys.METHOD, "html"); builder.outputProperty(OutputKeys.MEDIA_TYPE, MediaType.TEXT_HTML); builder.outputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/html4/strict.dtd"); builder.outputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01//EN"); } if (mediaType.isCompatible(MediaType.APPLICATION_XHTML_XML_TYPE)) { builder.outputProperty(OutputKeys.METHOD, "xhtml"); builder.outputProperty(OutputKeys.MEDIA_TYPE, MediaType.APPLICATION_XHTML_XML); builder.outputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"); builder.outputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD XHTML 1.0 Strict//EN"); } builder.transform(); } catch (TransformerException ex) { if (log.isErrorEnabled()) log.error("XSLT transformation failed", ex); throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR); // TO-DO: make Mapper } } public void write(Dataset dataset, OutputStream entityStream) throws TransformerException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); dataset.getDefaultModel().write(baos, RDFLanguages.RDFXML.getName(), null); XSLTBuilder.newInstance(getTransformerFactory()). stylesheet(getTemplates()). document(new ByteArrayInputStream(baos.toByteArray())). resolver(getDataManager()). result(new StreamResult(entityStream)). transform(); } @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return Dataset.class.isAssignableFrom(type); } @Override public long getSize(Dataset dataset, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } public URI getAbsolutePath() { return getUriInfo().getAbsolutePath(); } public URI getRequestURI() { return getUriInfo().getRequestUri(); } public URI getURIParam(UriInfo uriInfo, String name) throws URISyntaxException { if (uriInfo == null) throw new IllegalArgumentException("UriInfo cannot be null"); if (name == null) throw new IllegalArgumentException("String cannot be null"); if (uriInfo.getQueryParameters().containsKey(name)) return new URI(uriInfo.getQueryParameters().getFirst(name)); return null; } public URI getURI() throws URISyntaxException { return getURIParam(getUriInfo(), AC.uri.getLocalName()); } public URI getEndpointURI() throws URISyntaxException { return getURIParam(getUriInfo(), AC.endpoint.getLocalName()); } public String getQuery() { if (getUriInfo().getQueryParameters().containsKey(AC.query.getLocalName())) return getUriInfo().getQueryParameters().getFirst(AC.query.getLocalName()); return null; } public static Source getSource(Model model) throws IOException { if (model == null) throw new IllegalArgumentException("Model cannot be null"); if (log.isDebugEnabled()) log.debug("Number of Model stmts read: {}", model.size()); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { model.write(stream, RDFLanguages.RDFXML.getName(), null); if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length); return new StreamSource(new ByteArrayInputStream(stream.toByteArray())); } } public static Source getSource(OntModel ontModel, boolean writeAll) throws IOException { if (!writeAll) return getSource(ontModel); if (ontModel == null) throw new IllegalArgumentException("OntModel cannot be null"); if (log.isDebugEnabled()) log.debug("Number of OntModel stmts read: {}", ontModel.size()); try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { ontModel.writeAll(stream, Lang.RDFXML.getName(), null); if (log.isDebugEnabled()) log.debug("RDF/XML bytes written: {}", stream.toByteArray().length); return new StreamSource(new ByteArrayInputStream(stream.toByteArray())); } } public URI getContextURI() { return URI.create(getHttpServletRequest().getRequestURL().toString()). resolve(getHttpServletRequest().getContextPath() + "/"); } public Templates getTemplates() { if (templates != null) return templates; else { ContextResolver<Templates> cr = getProviders().getContextResolver(Templates.class, null); return cr.getContext(Templates.class); } } public XSLTBuilder setParameters(XSLTBuilder builder, Dataset dataset, MultivaluedMap<String, Object> headerMap) throws TransformerException { if (builder == null) throw new IllegalArgumentException("XSLTBuilder cannot be null"); if (headerMap == null) throw new IllegalArgumentException("MultivaluedMap cannot be null"); builder. //parameter("{" + A.absolutePath.getNameSpace() + "}" + A.absolutePath.getLocalName(), getAbsolutePath()). //parameter("{" + A.requestUri.getNameSpace() + "}" + A.requestUri.getLocalName(), getRequestURI()). parameter("{" + A.method.getNameSpace() + "}" + A.method.getLocalName(), getRequest().getMethod()). parameter("{" + A.httpHeaders.getNameSpace() + "}" + A.httpHeaders.getLocalName(), headerMap.toString()). parameter("{" + AC.contextUri.getNameSpace() + "}" + AC.contextUri.getLocalName(), getContextURI()); try { if (getURI() != null) builder.parameter("{" + AC.uri.getNameSpace() + "}" + AC.uri.getLocalName(), getURI()); if (getEndpointURI() != null) builder.parameter("{" + AC.endpoint.getNameSpace() + "}" + AC.endpoint.getLocalName(), getEndpointURI()); if (getQuery() != null) builder.parameter("{" + AC.query.getNameSpace() + "}" + AC.query.getLocalName(), getQuery()); List<URI> modes = getModes(getSupportedNamespaces()); // check if explicit mode URL parameter is provided URI ontologyURI = (URI)getHttpServletRequest().getAttribute(LDT.ontology.getURI()); if (ontologyURI != null) { builder.parameter("{" + LDT.ontology.getNameSpace() + "}" + LDT.ontology.getLocalName(), ontologyURI); OntModel sitemap = getOntModel(ontologyURI.toString()); builder.parameter("{" + AC.sitemap.getNameSpace() + "}" + AC.sitemap.getLocalName(), getSource(sitemap, true)); if (getBaseUri() != null) { builder.parameter("{" + LDT.base.getNameSpace() + "}" + LDT.base.getLocalName(), getBaseUri()); String forClassURI = getUriInfo().getQueryParameters().getFirst(AC.forClass.getLocalName()); if (forClassURI != null) { OntClass forClass = sitemap.getOntClass(forClassURI); if (forClass == null) throw new OntClassNotFoundException(forClassURI); // do we need this check here? builder.parameter("{" + AC.forClass.getNameSpace() + "}" + AC.forClass.getLocalName(), URI.create(forClass.getURI())); } } if (getTemplateURI() != null) { builder.parameter("{" + LDT.template.getNameSpace() + "}" + LDT.template.getLocalName(), getTemplateURI()); if (modes.isEmpty()) // attempt to retrieve default mode via matched template Link from the app (server) sitemap ontology { Resource template = sitemap.getResource(getTemplateURI().toString()); StmtIterator it = template.listProperties(AC.mode); try { while (it.hasNext()) { Statement modeStmt = it.next(); if (!modeStmt.getObject().isURIResource()) throw new OntologyException("Value is not a URI resource", template, AC.mode); modes.add(URI.create(modeStmt.getResource().getURI())); } } finally { it.close(); } } } } builder.parameter("{" + AC.mode.getNameSpace() + "}" + AC.mode.getLocalName(), modes); // workaround for Google Maps and Saxon-CE // They currently seem to work only in HTML mode and not in XHTML, because of document.write() usage // https://saxonica.plan.io/issues/1447 // // https://code.google.com/p/gmaps-api-issues/issues/detail?id=2820 // MediaType customMediaType = getCustomMediaType(modes); // if (customMediaType != null) // { // if (log.isDebugEnabled()) log.debug("Overriding response media type with '{}'", customMediaType); // List<Object> contentTypes = new ArrayList(); // contentTypes.add(customMediaType); // headerMap.put(HttpHeaders.CONTENT_TYPE, contentTypes); // } MediaType contentType = (MediaType)headerMap.getFirst(HttpHeaders.CONTENT_TYPE); if (contentType != null) { if (log.isDebugEnabled()) log.debug("Writing Model using XSLT media type: {}", contentType); builder.outputProperty(OutputKeys.MEDIA_TYPE, contentType.toString()); } Locale locale = (Locale)headerMap.getFirst(HttpHeaders.CONTENT_LANGUAGE); if (locale != null) { if (log.isDebugEnabled()) log.debug("Writing Model using language: {}", locale.toLanguageTag()); builder.parameter("{" + LDT.lang.getNameSpace() + "}" + LDT.lang.getLocalName(), locale.toLanguageTag()); } return builder; } catch (IOException ex) { if (log.isErrorEnabled()) log.error("Error reading Source stream"); throw new TransformerException(ex); } catch (URISyntaxException ex) { if (log.isErrorEnabled()) log.error("URI syntax exception"); throw new TransformerException(ex); } } public Set<String> getSupportedNamespaces() { return NAMESPACES; } public OntDocumentManager getOntDocumentManager() { return OntDocumentManager.getInstance(); } public OntModel getOntModel(String ontologyURI) { return getOntModel(ontologyURI, getOntModelSpec()); } public OntModel getOntModel(String ontologyURI, OntModelSpec ontModelSpec) { return new OntologyProvider().getOntModel(getOntDocumentManager(), ontologyURI, ontModelSpec); } public MediaType getCustomMediaType(List<URI> modes) { if (modes == null) throw new IllegalArgumentException("List<URI> cannot be null"); if (getUriInfo().getQueryParameters().containsKey(AC.forClass.getLocalName())) return MediaType.TEXT_HTML_TYPE; for (URI mode : modes) if (getModeMediaTypeMap().containsKey(mode)) return getModeMediaTypeMap().get(mode); return null; } public List<URI> getModes(Set<String> namespaces) { return getModes(getUriInfo(), namespaces); } public List<URI> getModes(UriInfo uriInfo, Set<String> namespaces) // mode is a client parameter, no need to parse hypermedia state here { if (uriInfo == null) throw new IllegalArgumentException("UriInfo cannot be null"); if (namespaces == null) throw new IllegalArgumentException("Namespace Set cannot be null"); List<URI> modes = new ArrayList<>(); if (uriInfo.getQueryParameters().containsKey(AC.mode.getLocalName())) { // matching parameter names not to namespace URIs, but to local names instead! List<String> modeParamValues = uriInfo.getQueryParameters().get(AC.mode.getLocalName()); for (String modeParamValue : modeParamValues) { Resource paramMode = ResourceFactory.createResource(modeParamValue); // only consider values from the known namespaces if (namespaces.contains(paramMode.getNameSpace())) modes.add(URI.create(modeParamValue)); } } return modes; } public static IRI checkURI(String classIRIStr) { if (classIRIStr == null) throw new IllegalArgumentException("URI String cannot be null"); IRI classIRI = IRIFactory.iriImplementation().create(classIRIStr); // throws Exceptions on bad URIs: CheckerIRI.iriViolations(classIRI, ErrorHandlerFactory.getDefaultErrorHandler()); return classIRI; } public static Source getConstructedSource(URI ontologyURI, List<URI> classURIs, URI baseURI) throws URISyntaxException, IOException { if (ontologyURI == null) throw new IllegalArgumentException("Ontology URI cannot be null"); if (classURIs == null) throw new IllegalArgumentException("Class URIs cannot be null"); if (baseURI == null) throw new IllegalArgumentException("Base URI cannot be null"); OntModel ontModel = OntDocumentManager.getInstance().getOntology(ontologyURI.toString(), OntModelSpec.OWL_MEM); Model instances = ModelFactory.createDefaultModel(); for (URI classURI : classURIs) { OntClass forClass = ontModel.getOntClass(checkURI(classURI.toString()).toURI().toString()); if (forClass != null) new Constructor().construct(forClass, instances, baseURI.toString()); // TO-DO: else throw error? } return getSource(instances); } public URI getBaseUri() { return (URI)getHttpServletRequest().getAttribute(LDT.base.getURI()); // set in ProxyResourceBase } public URI getTemplateURI() { return (URI)getHttpServletRequest().getAttribute(LDT.template.getURI()); // set in ProxyResourceBase } public UriInfo getUriInfo() { return uriInfo; } public Request getRequest() { return request; } public HttpHeaders getHttpHeaders() { return httpHeaders; } public HttpServletRequest getHttpServletRequest() { return httpServletRequest; } public Map<URI, MediaType> getModeMediaTypeMap() { return modeMediaTypeMap; } public OntModelSpec getOntModelSpec() { return ontModelSpec; } public Providers getProviders() { return providers; } public DataManager getDataManager() { ContextResolver<DataManager> cr = getProviders().getContextResolver(DataManager.class, null); return cr.getContext(DataManager.class); } public SAXTransformerFactory getTransformerFactory() { return ((SAXTransformerFactory)TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl", null)); } }
Removed mode-based HTML/XHTML MediaType switching in DatasetXSLTWriter
src/main/java/com/atomgraph/client/writer/DatasetXSLTWriter.java
Removed mode-based HTML/XHTML MediaType switching in DatasetXSLTWriter
Java
apache-2.0
74461da343e85e5ae4dd6995b32c6e2f88bd19d0
0
JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse,JayanthyChengan/dataverse
package edu.harvard.iq.dataverse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.harvard.iq.dataverse.api.AbstractApiBean; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.json.JsonObject; import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; public class ProvUtilFragmentBean extends AbstractApiBean implements java.io.Serializable{ HashMap<String,ProvEntityFileData> provJsonParsedEntities; JsonParser parser = new JsonParser(); private static final Logger logger = Logger.getLogger(ProvUtilFragmentBean.class.getCanonicalName()); public HashMap<String,ProvEntityFileData> startRecurseNames(String jsonString) { provJsonParsedEntities = new HashMap<>(); com.google.gson.JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject(); recurseNames(jsonObject, null, false); return provJsonParsedEntities; } /** Parsing recurser for prov json. Pulls out all names/types inside entity, including the name of each entry inside entity * Note that if a later entity is found with the same entity name (not name tag) its parsed contents will replace values that are stored * Current parsing code does not parse json arrays. My understanding of the schema is that these do not take place * Schema: https://www.w3.org/Submission/2013/SUBM-prov-json-20130424/schema */ protected JsonElement recurseNames(JsonElement element, String outerKey, boolean atEntity) { //we need to know when we are inside of entity //we also need to know when we are inside of each entity so we correctly connect the values if(element.isJsonObject()) { com.google.gson.JsonObject jsonObject = element.getAsJsonObject(); Set<Map.Entry<String,JsonElement>> entrySet = jsonObject.entrySet(); entrySet.forEach((s) -> { if(atEntity) { String key = s.getKey(); if("name".equals(key) || key.endsWith(":name")) { ProvEntityFileData e = provJsonParsedEntities.get(outerKey); e.fileName = s.getValue().getAsString(); } else if("type".equals(key) || key.endsWith(":type")) { if(s.getValue().isJsonObject()) { for ( Map.Entry tEntry : s.getValue().getAsJsonObject().entrySet()) { String tKey = (String) tEntry.getKey(); if("type".equals(tKey) || tKey.endsWith(":type")) { ProvEntityFileData e = provJsonParsedEntities.get(outerKey); String value = tEntry.getValue().toString(); e.fileType = value; } } } else if(s.getValue().isJsonPrimitive()){ ProvEntityFileData e = provJsonParsedEntities.get(outerKey); String value = s.getValue().getAsString(); e.fileType = value; } } } if(null != outerKey && (outerKey.equals("entity") || outerKey.endsWith(":entity"))) { //we are storing the entity name both as the key and in the object, the former for access and the later for ease of use when converted to a list //Also, when we initialize the entity the freeform is set to null, after this recursion provJsonParsedEntities.put(s.getKey(), new ProvEntityFileData(s.getKey(), null, null)); recurseNames(s.getValue(),s.getKey(),true); } else { recurseNames(s.getValue(),s.getKey(),false); } }); } //// My understanding of the prov standard is there should be no entities in arrays //// But if that changes the below code should be flushed out --MAD 4.8.6 // else if(element.isJsonArray()) { // JsonArray jsonArray = element.getAsJsonArray(); // for (JsonElement childElement : jsonArray) { // JsonElement result = recurseNames(childElement); // if(result != null) { // return result; // } // } // } return null; } public String getPrettyJsonString(JsonObject jsonObject) { JsonParser jp = new JsonParser(); JsonElement je = jp.parse(jsonObject.toString()); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(je); } public boolean isProvValid(String jsonInput) { try { schema.validate(new JSONObject(jsonInput)); // throws a ValidationException if this object is invalid } catch (ValidationException vx) { logger.info("Prov schema error : " + vx); //without classLoader is blows up in actual deployment return false; } return true; } //Pulled from https://www.w3.org/Submission/2013/SUBM-prov-json-20130424/schema //Not the prettiest way of accessing the schema, but loading the .json file as an external resource //turned out to be very painful, especially when also trying to exercise it via unit tests public final String provSchema = "{\n" + " \"id\": \"http://provenance.ecs.soton.ac.uk/prov-json/schema#\",\n" + " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + " \"description\": \"Schema for a PROV-JSON document\",\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": false,\n" + " \"properties\": {\n" + " \"prefix\": {\n" + " \"type\": \"object\",\n" + " \"patternProperties\": {\n" + " \"^[a-zA-Z0-9_\\\\-]+$\": { \"type\" : \"string\", \"format\": \"uri\" }\n" + " }\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/entity\" }\n" + " },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/activity\" }\n" + " },\n" + " \"agent\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/agent\" }\n" + " },\n" + " \"wasGeneratedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/generation\" }\n" + " },\n" + " \"used\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/usage\" }\n" + " },\n" + " \"wasInformedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/communication\" }\n" + " },\n" + " \"wasStartedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/start\" }\n" + " },\n" + " \"wasEndedby\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/end\" }\n" + " },\n" + " \"wasInvalidatedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/invalidation\" }\n" + " },\n" + " \"wasDerivedFrom\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/derivation\" }\n" + " },\n" + " \"wasAttributedTo\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/attribution\" }\n" + " },\n" + " \"wasAssociatedWith\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/association\" }\n" + " },\n" + " \"actedOnBehalfOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/delegation\" }\n" + " },\n" + " \"wasInfluencedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/influence\" }\n" + " },\n" + " \"specializationOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/specialization\" }\n" + " },\n" + " \"alternateOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/alternate\" }\n" + " },\n" + " \"hadMember\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/membership\" }\n" + " },\n" + " \"bundle\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/bundle\" }\n" + " }\n" + " },\n" + " \"definitions\": {\n" + " \"typedLiteral\": {\n" + " \"title\": \"PROV-JSON Typed Literal\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"$\": { \"type\": \"string\" },\n" + " \"type\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"lang\": { \"type\": \"string\" }\n" + " },\n" + " \"required\": [\"$\"],\n" + " \"additionalProperties\": false\n" + " },\n" + " \"stringLiteral\": {\"type\": \"string\"},\n" + " \"numberLiteral\": {\"type\": \"number\"},\n" + " \"booleanLiteral\": {\"type\": \"boolean\"},\n" + " \"literalArray\": {\n" + " \"type\": \"array\",\n" + " \"minItems\": 1,\n" + " \"items\": {\n" + " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/stringLiteral\" },\n" + " { \"$ref\": \"#/definitions/numberLiteral\" },\n" + " { \"$ref\": \"#/definitions/booleanLiteral\" },\n" + " { \"$ref\": \"#/definitions/typedLiteral\" }\n" + " ]\n" + " }\n" + " },\n" + " \"attributeValues\": {\n" + " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/stringLiteral\" },\n" + " { \"$ref\": \"#/definitions/numberLiteral\" },\n" + " { \"$ref\": \"#/definitions/booleanLiteral\" },\n" + " { \"$ref\": \"#/definitions/typedLiteral\" },\n" + " { \"$ref\": \"#/definitions/literalArray\" }\n" + " ]\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"entity\",\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"agent\": { \"$ref\": \"#/definitions/entity\" },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"activity\",\n" + " \"prov:startTime\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"prov:endTime\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"generation\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"generation/usage\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:time\": { \"type\": \"string\", \"format\": \"date-time\" }\n" + " },\n" + " \"required\": [\"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"usage\": {\"$ref\":\"#/definitions/generation\"},\n" + " \"communication\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"communication\",\n" + " \"properties\": {\n" + " \"prov:informant\": {\"type\": \"string\", \"format\": \"uri\"},\n" + " \"prov:informed\": {\"type\": \"string\", \"format\": \"uri\"}\n" + " },\n" + " \"required\": [\"prov:informant\", \"prov:informed\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"start\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"start/end\",\n" + " \"properties\": {\n" + " \"prov:activity\": {\"type\": \"string\", \"format\": \"uri\"},\n" + " \"prov:time\": {\"type\": \"string\", \"format\": \"date-time\"},\n" + " \"prov:trigger\": {\"type\": \"string\", \"format\": \"uri\"}\n" + " },\n" + " \"required\": [\"prov:activity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"end\": {\"$ref\":\"#/definitions/start\"},\n" + " \"invalidation\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"invalidation\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:time\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"derivation\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"derivation\",\n" + " \"properties\": {\n" + " \"prov:generatedEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:usedEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:generation\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:usage\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:generatedEntity\", \"prov:usedEntity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"attribution\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"attribution\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:agent\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:entity\", \"prov:agent\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"association\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"association\",\n" + " \"properties\": {\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:agent\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:plan\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:activity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"delegation\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"delegation\",\n" + " \"properties\": {\n" + " \"prov:delegate\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:responsible\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:delegate\", \"prov:responsible\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"influence\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"\",\n" + " \"properties\": {\n" + " \"prov:influencer\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:influencee\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:influencer\", \"prov:influencee\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"specialization\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"specialization\",\n" + " \"properties\": {\n" + " \"prov:generalEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:specificEntity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:generalEntity\", \"prov:specificEntity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"alternate\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"alternate\",\n" + " \"properties\": {\n" + " \"prov:alternate1\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:alternate2\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:alternate1\", \"prov:alternate2\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"membership\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"membership\",\n" + " \"properties\": {\n" + " \"prov:collection\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:collection\", \"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"bundle\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"bundle\",\n" + " \"properties\":{\n" + " \"prefix\": {\n" + " \"type\": \"object\",\n" + " \"patternProperties\": {\n" + " \"^[a-zA-Z0-9_\\\\-]+$\": { \"type\" : \"string\", \"format\": \"uri\" }\n" + " }\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/entity\" }\n" + " },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/activity\" }\n" + " },\n" + " \"agent\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/agent\" }\n" + " },\n" + " \"wasGeneratedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/generation\" }\n" + " },\n" + " \"used\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/usage\" }\n" + " },\n" + " \"wasInformedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/communication\" }\n" + " },\n" + " \"wasStartedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/start\" }\n" + " },\n" + " \"wasEndedby\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/end\" }\n" + " },\n" + " \"wasInvalidatedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/invalidation\" }\n" + " },\n" + " \"wasDerivedFrom\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/derivation\" }\n" + " },\n" + " \"wasAttributedTo\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/attribution\" }\n" + " },\n" + " \"wasAssociatedWith\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/association\" }\n" + " },\n" + " \"actedOnBehalfOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/delegation\" }\n" + " },\n" + " \"wasInfluencedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/influence\" }\n" + " },\n" + " \"specializationOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/specialization\" }\n" + " },\n" + " \"alternateOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/alternate\" }\n" + " },\n" + " \"hadMember\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/membership\" }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; JSONObject rawSchema = new JSONObject(new JSONTokener(provSchema)); Schema schema = SchemaLoader.load(rawSchema); }
src/main/java/edu/harvard/iq/dataverse/ProvUtilFragmentBean.java
package edu.harvard.iq.dataverse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import edu.harvard.iq.dataverse.api.AbstractApiBean; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.json.JsonObject; import org.everit.json.schema.Schema; import org.everit.json.schema.ValidationException; import org.everit.json.schema.loader.SchemaLoader; import org.json.JSONObject; import org.json.JSONTokener; public class ProvUtilFragmentBean extends AbstractApiBean implements java.io.Serializable{ HashMap<String,ProvEntityFileData> provJsonParsedEntities; JsonParser parser = new JsonParser(); private static final Logger logger = Logger.getLogger(ProvUtilFragmentBean.class.getCanonicalName()); public HashMap<String,ProvEntityFileData> startRecurseNames(String jsonString) { provJsonParsedEntities = new HashMap<>(); com.google.gson.JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject(); recurseNames(jsonObject, null, false); return provJsonParsedEntities; } /** Parsing recurser for prov json. Pulls out all names/types inside entity, including the name of each entry inside entity * Note that if a later entity is found with the same entity name (not name tag) its parsed contents will replace values that are stored * Current parsing code does not parse json arrays. My understanding of the schema is that these do not take place * Schema: https://www.w3.org/Submission/2013/SUBM-prov-json-20130424/schema */ protected JsonElement recurseNames(JsonElement element, String outerKey, boolean atEntity) { //we need to know when we are inside of entity //we also need to know when we are inside of each entity so we correctly connect the values if(element.isJsonObject()) { com.google.gson.JsonObject jsonObject = element.getAsJsonObject(); Set<Map.Entry<String,JsonElement>> entrySet = jsonObject.entrySet(); entrySet.forEach((s) -> { if(atEntity) { String key = s.getKey(); if("name".equals(key) || key.endsWith(":name")) { ProvEntityFileData e = provJsonParsedEntities.get(outerKey); e.fileName = s.getValue().getAsString(); } else if("type".equals(key) || key.endsWith(":type")) { if(s.getValue().isJsonObject()) { for ( Map.Entry tEntry : s.getValue().getAsJsonObject().entrySet()) { String tKey = (String) tEntry.getKey(); if("type".equals(tKey) || tKey.endsWith(":type")) { ProvEntityFileData e = provJsonParsedEntities.get(outerKey); String value = tEntry.getValue().toString(); e.fileType = value; } } } else if(s.getValue().isJsonPrimitive()){ ProvEntityFileData e = provJsonParsedEntities.get(outerKey); String value = s.getValue().getAsString(); e.fileType = value; } } } if(null != outerKey && (outerKey.equals("entity") || outerKey.endsWith(":entity"))) { //we are storing the entity name both as the key and in the object, the former for access and the later for ease of use when converted to a list //Also, when we initialize the entity the freeform is set to null, after this recursion provJsonParsedEntities.put(s.getKey(), new ProvEntityFileData(s.getKey(), null, null)); recurseNames(s.getValue(),s.getKey(),true); } else { recurseNames(s.getValue(),s.getKey(),false); } }); } //// My understanding of the prov standard is there should be no entities in arrays //// But if that changes the below code should be flushed out --MAD 4.8.6 // else if(element.isJsonArray()) { // JsonArray jsonArray = element.getAsJsonArray(); // for (JsonElement childElement : jsonArray) { // JsonElement result = recurseNames(childElement); // if(result != null) { // return result; // } // } // } return null; } public String getPrettyJsonString(JsonObject jsonObject) { JsonParser jp = new JsonParser(); JsonElement je = jp.parse(jsonObject.toString()); Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(je); } public boolean isProvValid(String jsonInput) { try { schema.validate(new JSONObject(jsonInput)); // throws a ValidationException if this object is invalid } catch (ValidationException vx) { logger.info("Prov schema error : " + vx); //without classLoader is blows up in actual deployment return false; } return true; } //Pulled from https://www.w3.org/Submission/2013/SUBM-prov-json-20130424/schema //Not the prettiest way of accessing the schema, but loading the .json file as an external resource //turned out to be very painful, especially when also trying to exercise it via unit tests public final String provSchema = "{\n" + " \"id\": \"http://provenance.ecs.soton.ac.uk/prov-json/schema#\",\n" + " \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n" + " \"description\": \"Schema for a PROV-JSON document\",\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": false,\n" + " \"properties\": {\n" + " \"prefix\": {\n" + " \"type\": \"object\",\n" + " \"patternProperties\": {\n" + " \"^[a-zA-Z0-9_\\\\-]+$\": { \"type\" : \"string\", \"format\": \"uri\" }\n" + " }\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/entity\" }\n" + " },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/activity\" }\n" + " },\n" + " \"agent\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/agent\" }\n" + " },\n" + " \"wasGeneratedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/generation\" }\n" + " },\n" + " \"used\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/usage\" }\n" + " },\n" + " \"wasInformedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/communication\" }\n" + " },\n" + " \"wasStartedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/start\" }\n" + " },\n" + " \"wasEndedby\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/end\" }\n" + " },\n" + " \"wasInvalidatedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/invalidation\" }\n" + " },\n" + " \"wasDerivedFrom\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/derivation\" }\n" + " },\n" + " \"wasAttributedTo\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/attribution\" }\n" + " },\n" + " \"wasAssociatedWith\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/association\" }\n" + " },\n" + " \"actedOnBehalfOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/delegation\" }\n" + " },\n" + " \"wasInfluencedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/influence\" }\n" + " },\n" + " \"specializationOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/specialization\" }\n" + " },\n" + " \"alternateOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/alternate\" }\n" + " },\n" + " \"hadMember\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/membership\" }\n" + " },\n" + " \"bundle\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/bundle\" }\n" + " }\n" + " },\n" + " \"definitions\": {\n" + " \"typedLiteral\": {\n" + " \"title\": \"PROV-JSON Typed Literal\",\n" + " \"type\": \"object\",\n" + " \"properties\": {\n" + " \"$\": { \"type\": \"string\" },\n" + " \"type\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"lang\": { \"type\": \"string\" }\n" + " },\n" + " \"required\": [\"$\"],\n" + " \"additionalProperties\": false\n" + " },\n" + " \"stringLiteral\": {\"type\": \"string\"},\n" + " \"numberLiteral\": {\"type\": \"number\"},\n" + " \"booleanLiteral\": {\"type\": \"boolean\"},\n" + " \"literalArray\": {\n" + " \"type\": \"array\",\n" + " \"minItems\": 1,\n" + " \"items\": {\n" + " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/stringLiteral\" },\n" + " { \"$ref\": \"#/definitions/numberLiteral\" },\n" + " { \"$ref\": \"#/definitions/booleanLiteral\" },\n" + " { \"$ref\": \"#/definitions/typedLiteral\" }\n" + " ]\n" + " }\n" + " },\n" + " \"attributeValues\": {\n" + " \"anyOf\": [\n" + " { \"$ref\": \"#/definitions/stringLiteral\" },\n" + " { \"$ref\": \"#/definitions/numberLiteral\" },\n" + " { \"$ref\": \"#/definitions/booleanLiteral\" },\n" + " { \"$ref\": \"#/definitions/typedLiteral\" },\n" + " { \"$ref\": \"#/definitions/literalArray\" }\n" + " ]\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"entity\",\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"agent\": { \"$ref\": \"#/definitions/entity\" },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"activity\",\n" + " \"prov:startTime\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"prov:endTime\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"generation\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"generation/usage\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:time\": { \"type\": \"string\", \"format\": \"date-time\" }\n" + " },\n" + " \"required\": [\"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"usage\": {\"$ref\":\"#/definitions/generation\"},\n" + " \"communication\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"communication\",\n" + " \"properties\": {\n" + " \"prov:informant\": {\"type\": \"string\", \"format\": \"uri\"},\n" + " \"prov:informed\": {\"type\": \"string\", \"format\": \"uri\"}\n" + " },\n" + " \"required\": [\"prov:informant\", \"prov:informed\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"start\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"start/end\",\n" + " \"properties\": {\n" + " \"prov:activity\": {\"type\": \"string\", \"format\": \"uri\"},\n" + " \"prov:time\": {\"type\": \"string\", \"format\": \"date-time\"},\n" + " \"prov:trigger\": {\"type\": \"string\", \"format\": \"uri\"}\n" + " },\n" + " \"required\": [\"prov:activity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"end\": {\"$ref\":\"#/definitions/start\"},\n" + " \"invalidation\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"invalidation\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:time\": { \"type\": \"string\", \"format\": \"date-time\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"derivation\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"derivation\",\n" + " \"properties\": {\n" + " \"prov:generatedEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:usedEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:generation\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:usage\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:generatedEntity\", \"prov:usedEntity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"attribution\":{\n" + " \"type\": \"object\",\n" + " \"title\": \"attribution\",\n" + " \"properties\": {\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:agent\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:entity\", \"prov:agent\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"association\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"association\",\n" + " \"properties\": {\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:agent\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:plan\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:activity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"delegation\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"delegation\",\n" + " \"properties\": {\n" + " \"prov:delegate\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:responsible\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:activity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:delegate\", \"prov:responsible\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"influence\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"\",\n" + " \"properties\": {\n" + " \"prov:influencer\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:influencee\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:influencer\", \"prov:influencee\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"specialization\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"specialization\",\n" + " \"properties\": {\n" + " \"prov:generalEntity\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:specificEntity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:generalEntity\", \"prov:specificEntity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"alternate\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"alternate\",\n" + " \"properties\": {\n" + " \"prov:alternate1\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:alternate2\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:alternate1\", \"prov:alternate2\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"membership\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"membership\",\n" + " \"properties\": {\n" + " \"prov:collection\": { \"type\": \"string\", \"format\": \"uri\" },\n" + " \"prov:entity\": { \"type\": \"string\", \"format\": \"uri\" }\n" + " },\n" + " \"required\": [\"prov:collection\", \"prov:entity\"],\n" + " \"additionalProperties\": { \"$ref\": \"#/definitions/attributeValues\" }\n" + " },\n" + " \"bundle\": {\n" + " \"type\": \"object\",\n" + " \"title\": \"bundle\",\n" + " \"properties\":{\n" + " \"prefix\": {\n" + " \"type\": \"object\",\n" + " \"patternProperties\": {\n" + " \"^[a-zA-Z0-9_\\\\-]+$\": { \"type\" : \"string\", \"format\": \"uri\" }\n" + " }\n" + " },\n" + " \"entity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/entity\" }\n" + " },\n" + " \"activity\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/activity\" }\n" + " },\n" + " \"agent\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/agent\" }\n" + " },\n" + " \"wasGeneratedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/generation\" }\n" + " },\n" + " \"used\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/usage\" }\n" + " },\n" + " \"wasInformedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/communication\" }\n" + " },\n" + " \"wasStartedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/start\" }\n" + " },\n" + " \"wasEndedby\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/end\" }\n" + " },\n" + " \"wasInvalidatedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/invalidation\" }\n" + " },\n" + " \"wasDerivedFrom\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/derivation\" }\n" + " },\n" + " \"wasAttributedTo\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/attribution\" }\n" + " },\n" + " \"wasAssociatedWith\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/association\" }\n" + " },\n" + " \"actedOnBehalfOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/delegation\" }\n" + " },\n" + " \"wasInfluencedBy\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/influence\" }\n" + " },\n" + " \"specializationOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/specialization\" }\n" + " },\n" + " \"alternateOf\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/alternate\" }\n" + " },\n" + " \"hadMember\": {\n" + " \"type\": \"object\",\n" + " \"additionalProperties\": { \"$ref\":\"#/definitions/membership\" }\n" + " }\n" + " }\n" + " }\n" + " }\n" + "}"; JSONObject rawSchema = new JSONObject(new JSONTokener(provSchema)); //BOOM NULL Schema schema = SchemaLoader.load(rawSchema); }
comment clean-up #4378
src/main/java/edu/harvard/iq/dataverse/ProvUtilFragmentBean.java
comment clean-up #4378
Java
apache-2.0
cbee56caef19e7eb1bbccee08d5ebc6c5cefcacd
0
LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb,LucidDB/luciddb
/* // Saffron preprocessor and data engine. // Copyright (C) 2002-2005 Disruptive Tech // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.saffron.oj.xlat; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import net.sf.saffron.jdbc.SaffronJdbcConnection; import net.sf.saffron.oj.stmt.OJStatement; import openjava.ptree.*; import org.eigenbase.rel.JoinRel; import org.eigenbase.relopt.RelOptConnection; import org.eigenbase.relopt.RelOptSchema; import org.eigenbase.relopt.RelOptTable; import org.eigenbase.reltype.RelDataType; import org.eigenbase.reltype.RelDataTypeField; import org.eigenbase.sql.*; import org.eigenbase.sql.fun.SqlStdOperatorTable; import org.eigenbase.sql.parser.SqlParseException; import org.eigenbase.sql.parser.SqlParser; import org.eigenbase.sql.type.SqlTypeName; import org.eigenbase.sql.validate.*; import org.eigenbase.util.NlsString; import org.eigenbase.util.Util; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * A <code>SqlToOpenjavaConverter</code> converts a tree of {@link SqlNode} * objects a {@link openjava.ptree.ParseTree} tree. * * @author jhyde * @version $Id$ * * @since Mar 19, 2003 */ public class SqlToOpenjavaConverter { /** * Maps names of {@link SqlBinaryOperator} to codes of * {@link BinaryExpression}, wrapped as {@link Integer}. For example, * <code>mapBinarySqlToOj.get("/")</code> returns * <code>Integer({@link BinaryExpression#DIVIDE}</code>. */ static final HashMap mapBinarySqlToOj = new HashMap(); /** * Inverse of {@link #mapBinarySqlToOj}. */ static final HashMap mapBinaryOjToSql = new HashMap(); static { initMaps(); } private final SqlValidator validator; public SqlToOpenjavaConverter(SqlValidator validator) { this.validator = validator; } public Expression convertQuery(SqlNode query) { query = validator.validate(query); return convertQueryRecursive(query); } public Expression convertSelect(SqlSelect query) { final SqlNode from = query.getFrom(); final SqlNodeList groupList = query.getGroup(); final SqlNodeList orderList = query.getOrderList(); final SqlNodeList selectList = query.getSelectList(); final SqlNode where = query.getWhere(); final SqlValidatorScope selectScope = validator.getSelectScope(query); final ExpressionList convertedSelectList = convertSelectList(selectScope, selectList, query); final SqlValidatorScope groupScope = validator.getGroupScope(query); final ExpressionList convertedGroup = convertGroup(groupScope, groupList); final SqlValidatorScope fromScope = validator.getFromScope(query); final Expression convertedFrom = convertFrom(fromScope, from, false); final Expression convertedWhere = (where == null) ? null : convertExpression(selectScope, where); final SqlValidatorScope orderScope = validator.getOrderScope(query); final ExpressionList convertedOrder = convertOrder(orderScope, orderList); QueryExpression queryExpression = new QueryExpression(convertedSelectList, true, convertedGroup, convertedFrom, convertedWhere, convertedOrder); if (query.isDistinct()) { throw new UnsupportedOperationException( "SELECT DISTINCT is not implemented"); // todo: } final SqlNode having = query.getHaving(); if (having != null) { throw new UnsupportedOperationException( "HAVING is not implemented"); // todo: } return queryExpression; } /** * Standard method recognised by JUnit. */ public static Test suite() { return new TestSuite(ConverterTest.class); } private Expression convertExpression( SqlValidatorScope scope, SqlNode node) { final SqlNode [] operands; switch (node.getKind().getOrdinal()) { case SqlKind.AsORDINAL: operands = ((SqlCall) node).getOperands(); return new AliasedExpression( convertExpression(scope, operands[0]), operands[1].toString()); case SqlKind.IdentifierORDINAL: return convertIdentifier(scope, (SqlIdentifier) node); case SqlKind.LiteralORDINAL: return convertLiteral((SqlLiteral) node); default: if (node instanceof SqlCall) { SqlCall call = (SqlCall) node; operands = call.getOperands(); if (call.getOperator() instanceof SqlBinaryOperator) { final SqlBinaryOperator binop = (SqlBinaryOperator) call.getOperator(); final Integer integer = (Integer) mapBinarySqlToOj.get(binop.getName()); if (integer == null) { throw new UnsupportedOperationException( "unknown binary operator " + binop); } int op = integer.intValue(); return new BinaryExpression( convertExpression(scope, operands[0]), op, convertExpression(scope, operands[1])); } else if (call.getOperator() instanceof SqlFunction) { throw new UnsupportedOperationException("todo:" + node); } else if (call.getOperator() instanceof SqlPrefixOperator) { throw new UnsupportedOperationException("todo:" + node); } else if (call.getOperator() instanceof SqlPostfixOperator) { throw new UnsupportedOperationException("todo:" + node); } else { throw new UnsupportedOperationException("todo:" + node); } } else { throw new UnsupportedOperationException("todo:" + node); } } } private Expression convertFrom( SqlValidatorScope scope, SqlNode from, boolean inAs) { switch (from.getKind().getOrdinal()) { case SqlKind.AsORDINAL: final SqlNode [] operands = ((SqlCall) from).getOperands(); return new AliasedExpression( convertFrom(scope, operands[0], true), operands[1].toString()); case SqlKind.IdentifierORDINAL: Expression e = new Variable(OJStatement.connectionVariable); final SqlIdentifier id = (SqlIdentifier) from; String schemaName = null; String tableName; if (id.names.length == 1) { tableName = id.names[0]; } else if (id.names.length == 2) { schemaName = id.names[0]; tableName = id.names[1]; } else { throw Util.newInternal("improperly qualified id: " + id); } return new TableReference(e, schemaName, tableName); case SqlKind.JoinORDINAL: final SqlJoin join = (SqlJoin) from; SqlNode left = join.getLeft(); SqlNode right = join.getRight(); SqlNode condition = join.getCondition(); boolean isNatural = join.isNatural(); SqlJoinOperator.JoinType joinType = join.getJoinType(); SqlJoinOperator.ConditionType conditionType = join.getConditionType(); Expression leftExp = convertFrom(scope, left, false); Expression rightExp = convertFrom(scope, right, false); Expression conditionExp = null; int convertedJoinType = convertJoinType(joinType); if (isNatural) { throw new UnsupportedOperationException( "todo: implement natural join"); } if (condition != null) { switch (conditionType.getOrdinal()) { case SqlJoinOperator.ConditionType.On_ORDINAL: conditionExp = convertExpression(scope, condition); break; case SqlJoinOperator.ConditionType.Using_ORDINAL: SqlNodeList list = (SqlNodeList) condition; for (int i = 0; i < list.size(); i++) { final SqlNode columnName = list.get(i); assert (columnName instanceof SqlIdentifier); Expression exp = convertExpression(scope, columnName); if (i == 0) { conditionExp = exp; } else { conditionExp = new BinaryExpression(conditionExp, BinaryExpression.LOGICAL_AND, exp); } } default: throw conditionType.unexpected(); } } if (conditionExp == null) { conditionExp = Literal.makeLiteral(true); } if (convertedJoinType == JoinRel.JoinType.RIGHT) { // "class Join" does not support RIGHT, so swap... return new JoinExpression(rightExp, leftExp, JoinRel.JoinType.LEFT, conditionExp); } else { return new JoinExpression(leftExp, rightExp, convertedJoinType, conditionExp); } case SqlKind.SelectORDINAL: case SqlKind.IntersectORDINAL: case SqlKind.ExceptORDINAL: case SqlKind.UnionORDINAL: return convertQueryRecursive(from); case SqlKind.ValuesORDINAL: return convertValues(scope, (SqlCall) from, inAs); default: throw Util.newInternal("not a join operator " + from); } } private static int convertJoinType(SqlJoinOperator.JoinType joinType) { switch (joinType.getOrdinal()) { case SqlJoinOperator.JoinType.Comma_ORDINAL: case SqlJoinOperator.JoinType.Inner_ORDINAL: case SqlJoinOperator.JoinType.Cross_ORDINAL: return JoinRel.JoinType.INNER; case SqlJoinOperator.JoinType.Full_ORDINAL: return JoinRel.JoinType.FULL; case SqlJoinOperator.JoinType.Left_ORDINAL: return JoinRel.JoinType.LEFT; case SqlJoinOperator.JoinType.Right_ORDINAL: return JoinRel.JoinType.RIGHT; default: throw joinType.unexpected(); } } private ExpressionList convertGroup( SqlValidatorScope scope, SqlNodeList groupList) { if (groupList == null) { return null; } ExpressionList list = new ExpressionList(); for (int i = 0; i < groupList.size(); i++) { Expression expression = convertExpression( scope, groupList.get(i)); list.add(expression); } return list; } private Expression convertLiteral(final SqlLiteral literal) { final Object value = literal.getValue(); switch (literal.getTypeName().getOrdinal()) { case SqlTypeName.Decimal_ordinal: case SqlTypeName.Double_ordinal: BigDecimal bd = (BigDecimal) value; // Convert to integer if possible. if (bd.scale() == 0) { int i = bd.intValue(); return Literal.makeLiteral(i); } else { // TODO: preserve fixed-point precision and large integers return Literal.makeLiteral(bd.doubleValue()); } case SqlTypeName.Char_ordinal: NlsString nlsStr = (NlsString) value; return Literal.makeLiteral(nlsStr.getValue()); case SqlTypeName.Boolean_ordinal: if (value != null) { return Literal.makeLiteral((Boolean) value); } // fall through to handle UNKNOWN (the boolean NULL value) case SqlTypeName.Null_ordinal: return Literal.constantNull(); default: throw literal.getTypeName().unexpected(); } } private ExpressionList convertOrder( SqlValidatorScope scope, SqlNodeList orderList) { if (orderList == null) { return null; } ExpressionList result = new ExpressionList(); for (int i = 0; i < orderList.size(); i++) { SqlNode order = orderList.get(i); result.add(convertExpression(scope, order)); } return result; } private Expression convertQueryRecursive(SqlNode query) { if (query instanceof SqlSelect) { return convertSelect((SqlSelect) query); } else if (query instanceof SqlCall) { final SqlCall call = (SqlCall) query; int op; final SqlKind kind = call.getKind(); switch (kind.getOrdinal()) { case SqlKind.UnionORDINAL: op = BinaryExpression.UNION; break; case SqlKind.IntersectORDINAL: op = BinaryExpression.INTERSECT; break; case SqlKind.ExceptORDINAL: op = BinaryExpression.EXCEPT; break; default: throw kind.unexpected(); } final SqlNode [] operands = call.getOperands(); final Expression left = convertQueryRecursive(operands[0]); final Expression right = convertQueryRecursive(operands[1]); return new BinaryExpression(left, op, right); } else { throw Util.newInternal("not a query: " + query); } } private static void initMaps() { addBinary("/", BinaryExpression.DIVIDE); addBinary("=", BinaryExpression.EQUAL); addBinary(">", BinaryExpression.GREATER); addBinary(">=", BinaryExpression.GREATEREQUAL); addBinary("<", BinaryExpression.LESS); addBinary("<=", BinaryExpression.LESSEQUAL); addBinary("AND", BinaryExpression.LOGICAL_AND); addBinary("OR", BinaryExpression.LOGICAL_OR); addBinary("-", BinaryExpression.MINUS); addBinary("*", BinaryExpression.NOTEQUAL); addBinary("+", BinaryExpression.PLUS); addBinary("*", BinaryExpression.TIMES); } private static void addBinary( String name, int code) { mapBinarySqlToOj.put( name, new Integer(code)); mapBinaryOjToSql.put( new Integer(code), name); } /** * Converts an identifier into an expression in a given scope. For * example, the "empno" in "select empno from emp join dept" becomes * "emp.empno". */ private Expression convertIdentifier( SqlValidatorScope scope, SqlIdentifier identifier) { identifier = scope.fullyQualify(identifier); Expression e = new Variable(identifier.names[0]); for (int i = 1; i < identifier.names.length; i++) { String name = identifier.names[i]; e = new FieldAccess(e, name); } return e; } private QueryExpression convertRowConstructor( SqlValidatorScope scope, SqlCall rowConstructor) { final SqlNode [] operands = rowConstructor.getOperands(); ExpressionList selectList = new ExpressionList(); for (int i = 0; i < operands.length; ++i) { // TODO: when column-aliases are supported and provided, use them Expression value = convertExpression(scope, operands[i]); Expression alias = new AliasedExpression(value, validator.deriveAlias(operands[i], i)); selectList.add(alias); } // SELECT value-list FROM onerow return new QueryExpression(selectList, true, null, null, null, null); } private ExpressionList convertSelectList( SqlValidatorScope scope, SqlNodeList selectList, SqlSelect select) { ExpressionList list = new ExpressionList(); selectList = validator.expandStar(selectList, select); for (int i = 0; i < selectList.size(); i++) { final SqlNode node = selectList.get(i); Expression expression = convertExpression(scope, node); list.add(expression); } return list; } private Expression convertValues( SqlValidatorScope scope, SqlCall values, boolean inAs) { SqlNodeList rowConstructorList = (SqlNodeList) (values.getOperands()[0]); Expression expr = null; // NOTE jvs 10-Sept-2003: If there are multiple rows, we will build a // left-deep UNION ALL tree with the first row left-most. It might be // a little more natural to generate a right-deep tree instead. // FIXME jvs 10-Sept-2003: The multi-row stuff doesn't actually work // yet, so it's disabled in the validator. For one thing, the // expression below should be a UNION ALL, not a UNION. But even this // way, Saffron validation or codegen fails depending on how it's // used. Single-row is fine. Iterator iter = rowConstructorList.getList().iterator(); while (iter.hasNext()) { SqlCall rowConstructor = (SqlCall) iter.next(); QueryExpression queryExpr = convertRowConstructor(scope, rowConstructor); if (expr == null) { expr = queryExpr; } else { expr = new BinaryExpression(expr, BinaryExpression.UNION, queryExpr); } } // Only provide an alias we're not below an AS operator. if (!inAs) { String alias = "foo"; // todo: generate something unique expr = new AliasedExpression(expr, alias); } return expr; } /** * Unit test for <code>SqlToOpenjavaConverter</code>. */ public static class ConverterTest extends TestCase { public void testConvert() { check("select 1 from \"emps\""); } public void testOrder(TestCase test) { check( "select * from \"emps\" order by \"empno\" asc, \"salary\", \"deptno\" desc"); } private void check(String s) { TestContext testContext = TestContext.instance(); final SqlNode sqlQuery; try { sqlQuery = new SqlParser(s).parseQuery(); } catch (SqlParseException e) { throw new AssertionFailedError(e.toString()); } final SqlValidator validator = SqlValidatorUtil.newValidator( SqlStdOperatorTable.instance(), testContext.seeker, testContext.schema.getTypeFactory()); final SqlToOpenjavaConverter converter = new SqlToOpenjavaConverter(validator); final Expression expression = converter.convertQuery(sqlQuery); assertTrue(expression != null); } } /** * A <code>SchemaCatalogReader</code> looks up catalog information from a * {@link RelOptSchema saffron schema object}. */ public static class SchemaCatalogReader implements SqlValidatorCatalogReader { private final RelOptSchema schema; private final boolean upperCase; public SchemaCatalogReader( RelOptSchema schema, boolean upperCase) { this.schema = schema; this.upperCase = upperCase; } public SqlValidatorTable getTable(String [] names) { if (names.length != 1) { return null; } final RelOptTable table = schema.getTableForMember( new String [] { maybeUpper(names[0]) }); if (table != null) { return new SqlValidatorTable() { public RelDataType getRowType() { return table.getRowType(); } public String [] getQualifiedName() { return null; } public List getColumnNames() { final RelDataType rowType = table.getRowType(); final RelDataTypeField [] fields = rowType.getFields(); ArrayList list = new ArrayList(); for (int i = 0; i < fields.length; i++) { RelDataTypeField field = fields[i]; list.add(maybeUpper(field.getName())); } return list; } public boolean isMonotonic(String columnName) { return false; } }; } return null; } public RelDataType getNamedType(SqlIdentifier sqlIdentifier) { // TODO jvs 12-Feb-2005: use OpenJava/reflection? return null; } public SqlMoniker [] getAllSchemaObjectNames(String [] names) { throw new UnsupportedOperationException(); } private String maybeUpper(String s) { return upperCase ? s.toUpperCase() : s; } } static class TestContext { private final SqlValidatorCatalogReader seeker; private final Connection jdbcConnection; private final RelOptConnection connection; private final RelOptSchema schema; private static TestContext instance; TestContext() { try { Class.forName("net.sf.saffron.jdbc.SaffronJdbcDriver"); } catch (ClassNotFoundException e) { throw Util.newInternal(e, "Error loading JDBC driver"); } try { jdbcConnection = DriverManager.getConnection( "jdbc:saffron:schema=sales.SalesInMemory"); } catch (SQLException e) { throw Util.newInternal(e); } connection = ((SaffronJdbcConnection) jdbcConnection).saffronConnection; schema = connection.getRelOptSchema(); seeker = new SchemaCatalogReader(schema, false); OJStatement.setupFactories(); } static TestContext instance() { if (instance == null) { instance = new TestContext(); } return instance; } } } // End SqlToOpenjavaConverter.java
saffron/src/net/sf/saffron/oj/xlat/SqlToOpenjavaConverter.java
/* // Saffron preprocessor and data engine. // Copyright (C) 2002-2005 Disruptive Tech // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.saffron.oj.xlat; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import net.sf.saffron.jdbc.SaffronJdbcConnection; import net.sf.saffron.oj.stmt.OJStatement; import openjava.ptree.*; import org.eigenbase.rel.JoinRel; import org.eigenbase.relopt.RelOptConnection; import org.eigenbase.relopt.RelOptSchema; import org.eigenbase.relopt.RelOptTable; import org.eigenbase.reltype.RelDataType; import org.eigenbase.reltype.RelDataTypeField; import org.eigenbase.sql.*; import org.eigenbase.sql.fun.SqlStdOperatorTable; import org.eigenbase.sql.parser.SqlParseException; import org.eigenbase.sql.parser.SqlParser; import org.eigenbase.sql.type.SqlTypeName; import org.eigenbase.sql.validate.*; import org.eigenbase.util.NlsString; import org.eigenbase.util.Util; import java.math.BigDecimal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * A <code>SqlToOpenjavaConverter</code> converts a tree of {@link SqlNode} * objects a {@link openjava.ptree.ParseTree} tree. * * @author jhyde * @version $Id$ * * @since Mar 19, 2003 */ public class SqlToOpenjavaConverter { /** * Maps names of {@link SqlBinaryOperator} to codes of * {@link BinaryExpression}, wrapped as {@link Integer}. For example, * <code>mapBinarySqlToOj.get("/")</code> returns * <code>Integer({@link BinaryExpression#DIVIDE}</code>. */ static final HashMap mapBinarySqlToOj = new HashMap(); /** * Inverse of {@link #mapBinarySqlToOj}. */ static final HashMap mapBinaryOjToSql = new HashMap(); static { initMaps(); } private final SqlValidator validator; public SqlToOpenjavaConverter(SqlValidator validator) { this.validator = validator; } public Expression convertQuery(SqlNode query) { query = validator.validate(query); return convertQueryRecursive(query); } public Expression convertSelect(SqlSelect query) { final SqlNode from = query.getFrom(); final SqlNodeList groupList = query.getGroup(); final SqlNodeList orderList = query.getOrderList(); final SqlNodeList selectList = query.getSelectList(); final SqlNode where = query.getWhere(); final SqlValidatorScope selectScope = validator.getSelectScope(query); final ExpressionList convertedSelectList = convertSelectList(selectScope, selectList, query); final SqlValidatorScope groupScope = validator.getGroupScope(query); final ExpressionList convertedGroup = convertGroup(groupScope, groupList); final SqlValidatorScope fromScope = validator.getFromScope(query); final Expression convertedFrom = convertFrom(fromScope, from, false); final Expression convertedWhere = (where == null) ? null : convertExpression(selectScope, where); final SqlValidatorScope orderScope = validator.getOrderScope(query); final ExpressionList convertedOrder = convertOrder(orderScope, orderList); QueryExpression queryExpression = new QueryExpression(convertedSelectList, true, convertedGroup, convertedFrom, convertedWhere, convertedOrder); if (query.isDistinct()) { throw new UnsupportedOperationException( "SELECT DISTINCT is not implemented"); // todo: } final SqlNode having = query.getHaving(); if (having != null) { throw new UnsupportedOperationException( "HAVING is not implemented"); // todo: } return queryExpression; } /** * Standard method recognised by JUnit. */ public static Test suite() { return new TestSuite(ConverterTest.class); } private Expression convertExpression( SqlValidatorScope scope, SqlNode node) { final SqlNode [] operands; switch (node.getKind().getOrdinal()) { case SqlKind.AsORDINAL: operands = ((SqlCall) node).getOperands(); return new AliasedExpression( convertExpression(scope, operands[0]), operands[1].toString()); case SqlKind.IdentifierORDINAL: return convertIdentifier(scope, (SqlIdentifier) node); case SqlKind.LiteralORDINAL: return convertLiteral((SqlLiteral) node); default: if (node instanceof SqlCall) { SqlCall call = (SqlCall) node; operands = call.getOperands(); if (call.getOperator() instanceof SqlBinaryOperator) { final SqlBinaryOperator binop = (SqlBinaryOperator) call.getOperator(); final Integer integer = (Integer) mapBinarySqlToOj.get(binop.getName()); if (integer == null) { throw new UnsupportedOperationException( "unknown binary operator " + binop); } int op = integer.intValue(); return new BinaryExpression( convertExpression(scope, operands[0]), op, convertExpression(scope, operands[1])); } else if (call.getOperator() instanceof SqlFunction) { throw new UnsupportedOperationException("todo:" + node); } else if (call.getOperator() instanceof SqlPrefixOperator) { throw new UnsupportedOperationException("todo:" + node); } else if (call.getOperator() instanceof SqlPostfixOperator) { throw new UnsupportedOperationException("todo:" + node); } else { throw new UnsupportedOperationException("todo:" + node); } } else { throw new UnsupportedOperationException("todo:" + node); } } } private Expression convertFrom( SqlValidatorScope scope, SqlNode from, boolean inAs) { switch (from.getKind().getOrdinal()) { case SqlKind.AsORDINAL: final SqlNode [] operands = ((SqlCall) from).getOperands(); return new AliasedExpression( convertFrom(scope, operands[0], true), operands[1].toString()); case SqlKind.IdentifierORDINAL: Expression e = new Variable(OJStatement.connectionVariable); final SqlIdentifier id = (SqlIdentifier) from; String schemaName = null; String tableName; if (id.names.length == 1) { tableName = id.names[0]; } else if (id.names.length == 2) { schemaName = id.names[0]; tableName = id.names[1]; } else { throw Util.newInternal("improperly qualified id: " + id); } return new TableReference(e, schemaName, tableName); case SqlKind.JoinORDINAL: final SqlJoin join = (SqlJoin) from; SqlNode left = join.getLeft(); SqlNode right = join.getRight(); SqlNode condition = join.getCondition(); boolean isNatural = join.isNatural(); SqlJoinOperator.JoinType joinType = join.getJoinType(); SqlJoinOperator.ConditionType conditionType = join.getConditionType(); Expression leftExp = convertFrom(scope, left, false); Expression rightExp = convertFrom(scope, right, false); Expression conditionExp = null; int convertedJoinType = convertJoinType(joinType); if (isNatural) { throw new UnsupportedOperationException( "todo: implement natural join"); } if (condition != null) { switch (conditionType.getOrdinal()) { case SqlJoinOperator.ConditionType.On_ORDINAL: conditionExp = convertExpression(scope, condition); break; case SqlJoinOperator.ConditionType.Using_ORDINAL: SqlNodeList list = (SqlNodeList) condition; for (int i = 0; i < list.size(); i++) { final SqlNode columnName = list.get(i); assert (columnName instanceof SqlIdentifier); Expression exp = convertExpression(scope, columnName); if (i == 0) { conditionExp = exp; } else { conditionExp = new BinaryExpression(conditionExp, BinaryExpression.LOGICAL_AND, exp); } } default: throw conditionType.unexpected(); } } if (conditionExp == null) { conditionExp = Literal.makeLiteral(true); } if (convertedJoinType == JoinRel.JoinType.RIGHT) { // "class Join" does not support RIGHT, so swap... return new JoinExpression(rightExp, leftExp, JoinRel.JoinType.LEFT, conditionExp); } else { return new JoinExpression(leftExp, rightExp, convertedJoinType, conditionExp); } case SqlKind.SelectORDINAL: case SqlKind.IntersectORDINAL: case SqlKind.ExceptORDINAL: case SqlKind.UnionORDINAL: return convertQueryRecursive(from); case SqlKind.ValuesORDINAL: return convertValues(scope, (SqlCall) from, inAs); default: throw Util.newInternal("not a join operator " + from); } } private static int convertJoinType(SqlJoinOperator.JoinType joinType) { switch (joinType.getOrdinal()) { case SqlJoinOperator.JoinType.Comma_ORDINAL: case SqlJoinOperator.JoinType.Inner_ORDINAL: case SqlJoinOperator.JoinType.Cross_ORDINAL: return JoinRel.JoinType.INNER; case SqlJoinOperator.JoinType.Full_ORDINAL: return JoinRel.JoinType.FULL; case SqlJoinOperator.JoinType.Left_ORDINAL: return JoinRel.JoinType.LEFT; case SqlJoinOperator.JoinType.Right_ORDINAL: return JoinRel.JoinType.RIGHT; default: throw joinType.unexpected(); } } private ExpressionList convertGroup( SqlValidatorScope scope, SqlNodeList groupList) { if (groupList == null) { return null; } ExpressionList list = new ExpressionList(); for (int i = 0; i < groupList.size(); i++) { Expression expression = convertExpression( scope, groupList.get(i)); list.add(expression); } return list; } private Expression convertLiteral(final SqlLiteral literal) { final Object value = literal.getValue(); switch (literal.getTypeName().getOrdinal()) { case SqlTypeName.Decimal_ordinal: case SqlTypeName.Double_ordinal: BigDecimal bd = (BigDecimal) value; // Convert to integer if possible. if (bd.scale() == 0) { int i = bd.intValue(); return Literal.makeLiteral(i); } else { // TODO: preserve fixed-point precision and large integers return Literal.makeLiteral(bd.doubleValue()); } case SqlTypeName.Char_ordinal: NlsString nlsStr = (NlsString) value; return Literal.makeLiteral(nlsStr.getValue()); case SqlTypeName.Boolean_ordinal: if (value != null) { return Literal.makeLiteral((Boolean) value); } // fall through to handle UNKNOWN (the boolean NULL value) case SqlTypeName.Null_ordinal: return Literal.constantNull(); default: throw literal.getTypeName().unexpected(); } } private ExpressionList convertOrder( SqlValidatorScope scope, SqlNodeList orderList) { if (orderList == null) { return null; } ExpressionList result = new ExpressionList(); for (int i = 0; i < orderList.size(); i++) { SqlNode order = orderList.get(i); result.add(convertExpression(scope, order)); } return result; } private Expression convertQueryRecursive(SqlNode query) { if (query instanceof SqlSelect) { return convertSelect((SqlSelect) query); } else if (query instanceof SqlCall) { final SqlCall call = (SqlCall) query; int op; final SqlKind kind = call.getKind(); switch (kind.getOrdinal()) { case SqlKind.UnionORDINAL: op = BinaryExpression.UNION; break; case SqlKind.IntersectORDINAL: op = BinaryExpression.INTERSECT; break; case SqlKind.ExceptORDINAL: op = BinaryExpression.EXCEPT; break; default: throw kind.unexpected(); } final SqlNode [] operands = call.getOperands(); final Expression left = convertQueryRecursive(operands[0]); final Expression right = convertQueryRecursive(operands[1]); return new BinaryExpression(left, op, right); } else { throw Util.newInternal("not a query: " + query); } } private static void initMaps() { addBinary("/", BinaryExpression.DIVIDE); addBinary("=", BinaryExpression.EQUAL); addBinary(">", BinaryExpression.GREATER); addBinary(">=", BinaryExpression.GREATEREQUAL); addBinary("<", BinaryExpression.LESS); addBinary("<=", BinaryExpression.LESSEQUAL); addBinary("AND", BinaryExpression.LOGICAL_AND); addBinary("OR", BinaryExpression.LOGICAL_OR); addBinary("-", BinaryExpression.MINUS); addBinary("*", BinaryExpression.NOTEQUAL); addBinary("+", BinaryExpression.PLUS); addBinary("*", BinaryExpression.TIMES); } private static void addBinary( String name, int code) { mapBinarySqlToOj.put( name, new Integer(code)); mapBinaryOjToSql.put( new Integer(code), name); } /** * Converts an identifier into an expression in a given scope. For * example, the "empno" in "select empno from emp join dept" becomes * "emp.empno". */ private Expression convertIdentifier( SqlValidatorScope scope, SqlIdentifier identifier) { identifier = scope.fullyQualify(identifier); Expression e = new Variable(identifier.names[0]); for (int i = 1; i < identifier.names.length; i++) { String name = identifier.names[i]; e = new FieldAccess(e, name); } return e; } private QueryExpression convertRowConstructor( SqlValidatorScope scope, SqlCall rowConstructor) { final SqlNode [] operands = rowConstructor.getOperands(); ExpressionList selectList = new ExpressionList(); for (int i = 0; i < operands.length; ++i) { // TODO: when column-aliases are supported and provided, use them Expression value = convertExpression(scope, operands[i]); Expression alias = new AliasedExpression(value, validator.deriveAlias(operands[i], i)); selectList.add(alias); } // SELECT value-list FROM onerow return new QueryExpression(selectList, true, null, null, null, null); } private ExpressionList convertSelectList( SqlValidatorScope scope, SqlNodeList selectList, SqlSelect select) { ExpressionList list = new ExpressionList(); selectList = validator.expandStar(selectList, select); for (int i = 0; i < selectList.size(); i++) { final SqlNode node = selectList.get(i); Expression expression = convertExpression(scope, node); list.add(expression); } return list; } private Expression convertValues( SqlValidatorScope scope, SqlCall values, boolean inAs) { SqlNodeList rowConstructorList = (SqlNodeList) (values.getOperands()[0]); Expression expr = null; // NOTE jvs 10-Sept-2003: If there are multiple rows, we will build a // left-deep UNION ALL tree with the first row left-most. It might be // a little more natural to generate a right-deep tree instead. // FIXME jvs 10-Sept-2003: The multi-row stuff doesn't actually work // yet, so it's disabled in the validator. For one thing, the // expression below should be a UNION ALL, not a UNION. But even this // way, Saffron validation or codegen fails depending on how it's // used. Single-row is fine. Iterator iter = rowConstructorList.getList().iterator(); while (iter.hasNext()) { SqlCall rowConstructor = (SqlCall) iter.next(); QueryExpression queryExpr = convertRowConstructor(scope, rowConstructor); if (expr == null) { expr = queryExpr; } else { expr = new BinaryExpression(expr, BinaryExpression.UNION, queryExpr); } } // Only provide an alias we're not below an AS operator. if (!inAs) { String alias = "foo"; // todo: generate something unique expr = new AliasedExpression(expr, alias); } return expr; } /** * Unit test for <code>SqlToOpenjavaConverter</code>. */ public static class ConverterTest extends TestCase { public void testConvert() { check("select 1 from \"emps\""); } public void testOrder(TestCase test) { check( "select * from \"emps\" order by \"empno\" asc, \"salary\", \"deptno\" desc"); } private void check(String s) { TestContext testContext = TestContext.instance(); final SqlNode sqlQuery; try { sqlQuery = new SqlParser(s).parseQuery(); } catch (SqlParseException e) { throw new AssertionFailedError(e.toString()); } final SqlValidator validator = SqlValidatorUtil.newValidator( SqlStdOperatorTable.instance(), testContext.seeker, testContext.schema.getTypeFactory()); final SqlToOpenjavaConverter converter = new SqlToOpenjavaConverter(validator); final Expression expression = converter.convertQuery(sqlQuery); assertTrue(expression != null); } } /** * A <code>SchemaCatalogReader</code> looks up catalog information from a * {@link RelOptSchema saffron schema object}. */ public static class SchemaCatalogReader implements SqlValidatorCatalogReader { private final RelOptSchema schema; private final boolean upperCase; public SchemaCatalogReader( RelOptSchema schema, boolean upperCase) { this.schema = schema; this.upperCase = upperCase; } public SqlValidatorTable getTable(String [] names) { if (names.length != 1) { return null; } final RelOptTable table = schema.getTableForMember( new String [] { maybeUpper(names[0]) }); if (table != null) { return new SqlValidatorTable() { public RelDataType getRowType() { return table.getRowType(); } public String [] getQualifiedName() { return null; } public List getColumnNames() { final RelDataType rowType = table.getRowType(); final RelDataTypeField [] fields = rowType.getFields(); ArrayList list = new ArrayList(); for (int i = 0; i < fields.length; i++) { RelDataTypeField field = fields[i]; list.add(maybeUpper(field.getName())); } return list; } public boolean isMonotonic(String columnName) { return false; } }; } return null; } public RelDataType getNamedType(SqlIdentifier sqlIdentifier) { // TODO jvs 12-Feb-2005: use OpenJava/reflection? return null; } public Moniker [] getAllSchemaObjectNames(String [] names) { throw new UnsupportedOperationException(); } private String maybeUpper(String s) { return upperCase ? s.toUpperCase() : s; } } static class TestContext { private final SqlValidatorCatalogReader seeker; private final Connection jdbcConnection; private final RelOptConnection connection; private final RelOptSchema schema; private static TestContext instance; TestContext() { try { Class.forName("net.sf.saffron.jdbc.SaffronJdbcDriver"); } catch (ClassNotFoundException e) { throw Util.newInternal(e, "Error loading JDBC driver"); } try { jdbcConnection = DriverManager.getConnection( "jdbc:saffron:schema=sales.SalesInMemory"); } catch (SQLException e) { throw Util.newInternal(e); } connection = ((SaffronJdbcConnection) jdbcConnection).saffronConnection; schema = connection.getRelOptSchema(); seeker = new SchemaCatalogReader(schema, false); OJStatement.setupFactories(); } static TestContext instance() { if (instance == null) { instance = new TestContext(); } return instance; } } } // End SqlToOpenjavaConverter.java
FARRAGO: matching eigenbase 3662 (saffron changes for Moniker* class renaming to SqlMoniker*) [git-p4: depot-paths = "//open/dt/dev/": change = 3664]
saffron/src/net/sf/saffron/oj/xlat/SqlToOpenjavaConverter.java
FARRAGO: matching eigenbase 3662 (saffron changes for Moniker* class renaming to SqlMoniker*)
Java
apache-2.0
038884735b5a72e7b2af2b1ee110d1f9de8d6369
0
bric3/nCGLIB
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package net.sf.cglib; /** * @author baliuka */ public class UndeclaredThrowableException extends CodeGenerationException { /** * Creates a new instance of <code>UndeclaredThrowableException</code> without detail message. */ public UndeclaredThrowableException(Throwable t) { super(t); } public Throwable getUndeclaredThrowable() { return getCause(); } }
cglib/src/proxy/net/sf/cglib/UndeclaredThrowableException.java
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2002 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Apache" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package net.sf.cglib; /** * * @author baliuka */ public class UndeclaredThrowableException extends CodeGenerationException { private Throwable t; /** * Creates a new instance of <code>UndeclaredThrowableException</code> without detail message. */ public UndeclaredThrowableException(Throwable t) { super(t); this.t = t; } public Throwable getUndeclaredThrowable() { return t; } // for jdk1.4 compatibility public Throwable getCause() { return t; } }
Remove redundant code.
cglib/src/proxy/net/sf/cglib/UndeclaredThrowableException.java
Remove redundant code.
Java
apache-2.0
9b9de982bb25671b9a3f44f96abe0b958f0d136b
0
skoulouzis/lobcder,skoulouzis/lobcder,skoulouzis/lobcder
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import io.milton.common.Path; import io.milton.http.Range; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.xml.bind.annotation.XmlRootElement; import lombok.extern.java.Log; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.io.CircularStreamBufferTransferer; import nl.uva.vlet.vrl.VRL; import org.apache.http.HttpStatus; /** * * @author S. Koulouzis */ @Log public class WorkerServlet extends HttpServlet { // private Client restClient; private String restURL; private final String username; private final String password; private Map<String, Long> weightPDRIMap; private long size; // private HttpClient client; private final String davURL; private int numOfTries = 0; private long numOfGets; private long sleepTime = 2; private String token; private final DefaultClientConfig clientConfig; public WorkerServlet() throws FileNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream("/auth.properties"); // String propBasePath = File.separator + "test.proprties"; Properties prop = Util.getTestProperties(in); restURL = prop.getProperty(("rest.url"), "http://localhost:8080/lobcder/rest/"); davURL = prop.getProperty(("rest.url"), "http://localhost:8080/lobcder/dav/"); username = prop.getProperty(("rest.username"), "user"); password = prop.getProperty(("rest.password"), "pass"); clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); weightPDRIMap = new HashMap<String, Long>(); } /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = request.getPathInfo(); if (filePath.length() > 1) { Path pathAndToken = Path.path(filePath); token = pathAndToken.getName(); String path = pathAndToken.getParent().toString(); try { numOfGets++; long start = System.currentTimeMillis(); PDRI pdri = getPDRI(path); if (pdri == null) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { OutputStream out = response.getOutputStream(); String rangeStr = request.getHeader(Constants.RANGE_HEADER_NAME); if (rangeStr != null) { Range range = Range.parse(rangeStr.split("=")[1]); pdri.copyRange(range, out); response.setStatus(HttpStatus.SC_PARTIAL_CONTENT); } else { trasfer(pdri, out, false); } long elapsed = System.currentTimeMillis() - start; long elapsedSec = elapsed / 1000; if (elapsedSec <= 0) { elapsedSec = 1; } long speed = size / elapsedSec; Long oldSpeed = weightPDRIMap.get(pdri.getHost()); if (oldSpeed == null) { oldSpeed = speed; } long averagre = (speed + oldSpeed) / numOfGets; this.weightPDRIMap.put(pdri.getHost(), averagre); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Average speed for : {0} : " + averagre, pdri.getHost()); } numOfTries = 0; sleepTime = 2; } catch (Exception ex) { if (ex.getMessage() != null && ex.getMessage().contains("returned a response status of 401 Unauthorized")) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); return; // throw new IOException(ex); } if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime + 2; Thread.sleep(sleepTime); doGet(request, response); } catch (InterruptedException ex1) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex1); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } else { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } } } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "LOBCDER worker"; } private PDRI getPDRI(String filePath) throws IOException, URISyntaxException { PDRIDesc pdriDesc = null;//new PDRIDesc(); try { Client restClient = Client.create(clientConfig); restClient.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, token)); WebResource webResource = restClient.resource(restURL); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("path", filePath); WebResource res = webResource.path("items").path("query").queryParams(params); List<LogicalDataWrapped> list = res.accept(MediaType.APPLICATION_XML). get(new GenericType<List<LogicalDataWrapped>>() { }); int count = 0; for (LogicalDataWrapped ld : list) { if (ld != null) { Set<PDRIDesc> pdris = ld.pdriList; size = ld.logicalData.length; if (pdris != null && !pdris.isEmpty()) { pdriDesc = selectBestPDRI(pdris); while (pdriDesc == null) { count++; pdriDesc = selectBestPDRI(pdris); if (count > 10) { break; } } } } } } catch (Exception ex) { if (ex.getMessage().contains("returned a response status of 401 Unauthorized")) { throw new IOException(ex); } if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime + 2; Thread.sleep(sleepTime); getPDRI(filePath); } catch (InterruptedException ex1) { throw new IOException(ex1); } } } numOfTries = 0; sleepTime = 2; return new WorkerVPDRI(pdriDesc.name, pdriDesc.id, pdriDesc.resourceUrl, pdriDesc.username, pdriDesc.password, pdriDesc.encrypt, BigInteger.ZERO, false); } private void trasfer(PDRI pdri, OutputStream out, boolean withCircularStream) throws IOException { InputStream in = null; try { in = pdri.getData(); int bufferSize; if (pdri.getLength() < Constants.BUF_SIZE) { bufferSize = (int) pdri.getLength(); } else { bufferSize = Constants.BUF_SIZE; } if (!pdri.getEncrypted() && withCircularStream) { CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((bufferSize), in, out); cBuff.startTransfer(new Long(-1)); cBuff.setStop(withCircularStream); } else if (!pdri.getEncrypted() && !withCircularStream) { int read; byte[] copyBuffer = new byte[bufferSize]; while ((read = in.read(copyBuffer, 0, copyBuffer.length)) != -1) { out.write(copyBuffer, 0, read); } } numOfTries = 0; sleepTime = 2; } catch (Exception ex) { withCircularStream = false; // if (ex instanceof nl.uva.vlet.exception.VlException) { // withCircularStream = false; // } if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime * 2; Thread.sleep(sleepTime); trasfer(pdri, out, withCircularStream); } catch (InterruptedException ex1) { throw new IOException(ex1.getMessage()); } } else { throw new IOException(ex.getMessage()); } } finally { try { if (out != null) { out.flush(); out.close(); } if (in != null) { in.close(); } } catch (java.net.SocketException ex) { // } } } private PDRIDesc selectBestPDRI(Set<PDRIDesc> pdris) throws URISyntaxException, UnknownHostException { if (weightPDRIMap.isEmpty() || weightPDRIMap.size() < pdris.size()) { //Just return one at random; int index = new Random().nextInt(pdris.size()); PDRIDesc[] array = pdris.toArray(new PDRIDesc[pdris.size()]); return array[index]; } long sumOfSpeed = 0; for (PDRIDesc p : pdris) { URI uri = new URI(p.resourceUrl); String host; if (uri.getScheme().equals("file") || StringUtil.isEmpty(uri.getHost()) || uri.getHost().equals("localhost") || uri.getHost().equals("127.0.0.1")) { host = InetAddress.getLocalHost().getHostName(); } else { host = uri.getHost(); } Long speed = weightPDRIMap.get(host); // if(speed == null){ // speed = Long.valueOf(100); // } Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Speed: : {0}", speed); sumOfSpeed += speed; } int itemIndex = new Random().nextInt((int) sumOfSpeed); for (PDRIDesc p : pdris) { Long speed = weightPDRIMap.get(new URI(p.resourceUrl).getHost()); if (itemIndex < speed) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Returning : {0}", p.resourceUrl); return p; } itemIndex -= speed; } // long sum = 0; // int i = 0; // // while (sum < itemIndex) { // i++; // winner = pdris.iterator().next(); //// sum = sum + weightPDRIMap.get(new URI(winner.resourceUrl).getHost()); // sum = sum + weightPDRIMap.get(new URI(winner.resourceUrl).getHost()); // } // PDRIDesc[] array = pdris.toArray(new PDRIDesc[pdris.size()]); // int index; // if (i > 0) { // index = i - 1; // } else { // index = i; // } return null; } @XmlRootElement public static class PDRIDesc { public boolean encrypt; public long id; public String name; public String password; public String resourceUrl; public String username; } @XmlRootElement public static class LogicalDataWrapped { public LogicalData logicalData; public String path; public Set<PDRIDesc> pdriList; public Set<Permissions> permissions; } @XmlRootElement public static class LogicalData { public int checksum; public String contentTypesAsString; public long createDate; public long lastValidationDate; public long length; public int lockTimeout; public long modifiedDate; public String name; public String owner; public int parentRef; public int pdriGroupId; public boolean supervised; public String type; public int uid; } @XmlRootElement public static class Permissions { public String owner; public Set<String> read; public Set<String> write; } }
lobcder-worker/src/main/java/nl/uva/cs/lobcder/WorkerServlet.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import io.milton.http.Range; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.xml.bind.annotation.XmlRootElement; import lombok.extern.java.Log; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.io.CircularStreamBufferTransferer; import org.apache.http.HttpStatus; /** * * @author S. Koulouzis */ @Log public class WorkerServlet extends HttpServlet { private Client restClient; private String restURL; private final String username; private final String password; private Map<String, Long> weightPDRIMap; private long size; // private HttpClient client; private final String davURL; private int numOfTries = 0; private long numOfGets; private long sleepTime = 2; public WorkerServlet() throws FileNotFoundException, IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream in = classLoader.getResourceAsStream("/auth.properties"); // String propBasePath = File.separator + "test.proprties"; Properties prop = Util.getTestProperties(in); restURL = prop.getProperty(("rest.url"), "http://localhost:8080/lobcder/rest/"); davURL = prop.getProperty(("rest.url"), "http://localhost:8080/lobcder/dav/"); username = prop.getProperty(("rest.username"), "user"); password = prop.getProperty(("rest.password"), "pass"); ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); restClient = Client.create(clientConfig); restClient.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password)); weightPDRIMap = new HashMap<String, Long>(); } /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = request.getPathInfo(); if (filePath.length() > 1) { try { numOfGets++; long start = System.currentTimeMillis(); PDRI pdri = getPDRI(filePath); if (pdri == null) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { OutputStream out = response.getOutputStream(); String rangeStr = request.getHeader(Constants.RANGE_HEADER_NAME); if (rangeStr != null) { Range range = Range.parse(rangeStr.split("=")[1]); pdri.copyRange(range, out); response.setStatus(HttpStatus.SC_PARTIAL_CONTENT); } else { trasfer(pdri, out, false); } long elapsed = System.currentTimeMillis() - start; long elapsedSec = elapsed / 1000; if (elapsedSec <= 0) { elapsedSec = 1; } long speed = size / elapsedSec; Long oldSpeed = weightPDRIMap.get(pdri.getHost()); if (oldSpeed == null) { oldSpeed = speed; } long averagre = (speed + oldSpeed) / numOfGets; this.weightPDRIMap.put(pdri.getHost(), averagre); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Average speed for : {0} : " + averagre, pdri.getHost()); } numOfTries = 0; sleepTime = 2; } catch (Exception ex) { if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime + 2; Thread.sleep(sleepTime); doGet(request, response); } catch (InterruptedException ex1) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex1); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } else { Logger.getLogger(WorkerServlet.class.getName()).log(Level.SEVERE, null, ex); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } } } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "LOBCDER worker"; } private PDRI getPDRI(String filePath) throws IOException, URISyntaxException { PDRIDesc pdriDesc = null;//new PDRIDesc(); try { WebResource webResource = restClient.resource(restURL); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("path", filePath); WebResource res = webResource.path("items").path("query").queryParams(params); List<LogicalDataWrapped> list = res.accept(MediaType.APPLICATION_XML). get(new GenericType<List<LogicalDataWrapped>>() { }); int count = 0; for (LogicalDataWrapped ld : list) { if (ld != null) { Set<PDRIDesc> pdris = ld.pdriList; size = ld.logicalData.length; if (pdris != null && !pdris.isEmpty()) { pdriDesc = selectBestPDRI(pdris); while (pdriDesc == null) { count++; pdriDesc = selectBestPDRI(pdris); if (count > 10) { break; } } } } } } catch (Exception ex) { if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime + 2; Thread.sleep(sleepTime); getPDRI(filePath); } catch (InterruptedException ex1) { throw new IOException(ex1); } } } numOfTries = 0; sleepTime = 2; return new WorkerVPDRI(pdriDesc.name, pdriDesc.id, pdriDesc.resourceUrl, pdriDesc.username, pdriDesc.password, pdriDesc.encrypt, BigInteger.ZERO, false); } private void trasfer(PDRI pdri, OutputStream out, boolean withCircularStream) throws IOException { InputStream in = null; try { in = pdri.getData(); int bufferSize; if (pdri.getLength() < Constants.BUF_SIZE) { bufferSize = (int) pdri.getLength(); } else { bufferSize = Constants.BUF_SIZE; } if (!pdri.getEncrypted() && withCircularStream) { CircularStreamBufferTransferer cBuff = new CircularStreamBufferTransferer((bufferSize), in, out); cBuff.startTransfer(new Long(-1)); cBuff.setStop(withCircularStream); } else if (!pdri.getEncrypted() && !withCircularStream) { int read; byte[] copyBuffer = new byte[bufferSize]; while ((read = in.read(copyBuffer, 0, copyBuffer.length)) != -1) { out.write(copyBuffer, 0, read); } } numOfTries = 0; sleepTime = 2; } catch (Exception ex) { withCircularStream = false; // if (ex instanceof nl.uva.vlet.exception.VlException) { // withCircularStream = false; // } if (numOfTries < Constants.RECONNECT_NTRY) { try { numOfTries++; sleepTime = sleepTime * 2; Thread.sleep(sleepTime); trasfer(pdri, out, withCircularStream); } catch (InterruptedException ex1) { throw new IOException(ex1.getMessage()); } } else { throw new IOException(ex.getMessage()); } } finally { try { if (out != null) { out.flush(); out.close(); } if (in != null) { in.close(); } } catch (java.net.SocketException ex) { // } } } private PDRIDesc selectBestPDRI(Set<PDRIDesc> pdris) throws URISyntaxException { if (weightPDRIMap.isEmpty() || weightPDRIMap.size() < pdris.size()) { //Just return one at random; int index = new Random().nextInt(pdris.size()); PDRIDesc[] array = pdris.toArray(new PDRIDesc[pdris.size()]); return array[index]; } long sumOfSpeed = 0; for (PDRIDesc p : pdris) { Long speed = weightPDRIMap.get(new URI(p.resourceUrl).getHost()); Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Speed: : {0}", speed); sumOfSpeed += speed; } int itemIndex = new Random().nextInt((int) sumOfSpeed); for (PDRIDesc p : pdris) { Long speed = weightPDRIMap.get(new URI(p.resourceUrl).getHost()); if (itemIndex < speed) { Logger.getLogger(WorkerServlet.class.getName()).log(Level.FINE, "Returning : {0}", p.resourceUrl); return p; } itemIndex -= speed; } // long sum = 0; // int i = 0; // // while (sum < itemIndex) { // i++; // winner = pdris.iterator().next(); //// sum = sum + weightPDRIMap.get(new URI(winner.resourceUrl).getHost()); // sum = sum + weightPDRIMap.get(new URI(winner.resourceUrl).getHost()); // } // PDRIDesc[] array = pdris.toArray(new PDRIDesc[pdris.size()]); // int index; // if (i > 0) { // index = i - 1; // } else { // index = i; // } return null; } @XmlRootElement public static class PDRIDesc { public boolean encrypt; public long id; public String name; public String password; public String resourceUrl; public String username; } @XmlRootElement public static class LogicalDataWrapped { public LogicalData logicalData; public String path; public Set<PDRIDesc> pdriList; public Set<Permissions> permissions; } @XmlRootElement public static class LogicalData { public int checksum; public String contentTypesAsString; public long createDate; public long lastValidationDate; public long length; public int lockTimeout; public long modifiedDate; public String name; public String owner; public int parentRef; public int pdriGroupId; public boolean supervised; public String type; public int uid; } @XmlRootElement public static class Permissions { public String owner; public Set<String> read; public Set<String> write; } }
Implemented worker one-time authentication
lobcder-worker/src/main/java/nl/uva/cs/lobcder/WorkerServlet.java
Implemented worker one-time authentication
Java
apache-2.0
53dbe735571287ad1f4cb0b29d7d4284882e6510
0
ddrown/irssiconnectbot,SEC-squad/irssiconnectbot,SEC-squad/irssiconnectbot,ddrown/irssiconnectbot,SEC-squad/irssiconnectbot,SEC-squad/irssiconnectbot,ddrown/irssiconnectbot
/* * This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform". * * (c) Matthias L. Jugel, Marcus Meissner 1996-2005. All Rights Reserved. * * Please visit http://javatelnet.org/ for updates and contact. * * --LICENSE NOTICE-- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * --LICENSE NOTICE-- * */ package de.mud.terminal; import android.text.AndroidCharacter; import java.util.Properties; /** * Implementation of a VT terminal emulation plus ANSI compatible. * <P> * <B>Maintainer:</B> Marcus Meissner * * @version $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $ * @author Matthias L. Jugel, Marcus Meissner */ public abstract class vt320 extends VDUBuffer implements VDUInput { /** The current version id tag.<P> * $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $ * */ public final static String ID = "$Id: vt320.java 507 2005-10-25 10:14:52Z marcus $"; /** the debug level */ private final static int debug = 0; private StringBuilder debugStr; public abstract void debug(String notice); /** * Write an answer back to the remote host. This is needed to be able to * send terminal answers requests like status and type information. * @param b the array of bytes to be sent */ public abstract void write(byte[] b); /** * Write an answer back to the remote host. This is needed to be able to * send terminal answers requests like status and type information. * @param b the array of bytes to be sent */ public abstract void write(int b); /** * Play the beep sound ... */ public void beep() { /* do nothing by default */ } /** * Convenience function for putString(char[], int, int) */ public void putString(String s) { int len = s.length(); char[] tmp = new char[len]; s.getChars(0, len, tmp, 0); putString(tmp, null, 0, len); } /** * Put string at current cursor position. Moves cursor * according to the String. Does NOT wrap. * @param s character array * @param start place to start in array * @param len number of characters to process */ public void putString(char[] s, byte[] fullwidths, int start, int len) { if (len > 0) { //markLine(R, 1); int lastChar = -1; char c; boolean isWide = false; for (int i = 0; i < len; i++) { c = s[start + i]; // Shortcut for my favorite ASCII if (c <= 0x7F) { if (lastChar != -1) putChar((char) lastChar, isWide, false); lastChar = c; isWide = false; } else if (!Character.isLowSurrogate(c) && !Character.isHighSurrogate(c)) { if (Character.getType(c) == Character.NON_SPACING_MARK) { if (lastChar != -1) { char nc = Precomposer.precompose((char) lastChar, c); putChar(nc, isWide, false); lastChar = -1; } } else { if (lastChar != -1) putChar((char) lastChar, isWide, false); lastChar = c; if (fullwidths != null) { final byte width = fullwidths[i]; isWide = (width == AndroidCharacter.EAST_ASIAN_WIDTH_WIDE) || (width == AndroidCharacter.EAST_ASIAN_WIDTH_FULL_WIDTH); } } } } if (lastChar != -1) putChar((char) lastChar, isWide, false); setCursorPosition(C, R); redraw(); } } protected void sendTelnetCommand(byte cmd) { } /** * Sent the changed window size from the terminal to all listeners. */ protected void setWindowSize(int c, int r) { /* To be overridden by Terminal.java */ } @Override public void setScreenSize(int c, int r, boolean broadcast) { int oldrows = height; if (debug>2) { if (debugStr == null) debugStr = new StringBuilder(); debugStr.append("setscreensize (") .append(c) .append(',') .append(r) .append(',') .append(broadcast) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); } super.setScreenSize(c,r,false); boolean cursorChanged = false; // Don't let the cursor go off the screen. if (C >= c) { C = c - 1; cursorChanged = true; } if (R >= r) { R = r - 1; cursorChanged = true; } if (cursorChanged) { setCursorPosition(C, R); redraw(); } if (broadcast) { setWindowSize(c, r); /* broadcast up */ } } /** * Create a new vt320 terminal and intialize it with useful settings. */ public vt320(int width, int height) { super(width, height); debugStr = new StringBuilder(); setVMS(false); setIBMCharset(false); setTerminalID("vt320"); setBufferSize(100); //setBorder(2, false); gx = new char[4]; reset(); /* top row of numpad */ PF1 = "\u001bOP"; PF2 = "\u001bOQ"; PF3 = "\u001bOR"; PF4 = "\u001bOS"; /* the 3x2 keyblock on PC keyboards */ Insert = new String[4]; Remove = new String[4]; KeyHome = new String[4]; KeyEnd = new String[4]; NextScn = new String[4]; PrevScn = new String[4]; Escape = new String[4]; BackSpace = new String[4]; TabKey = new String[4]; Insert[0] = Insert[1] = Insert[2] = Insert[3] = "\u001b[2~"; Remove[0] = Remove[1] = Remove[2] = Remove[3] = "\u001b[3~"; PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[5~"; NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[6~"; KeyHome[0] = KeyHome[1] = KeyHome[2] = KeyHome[3] = "\u001b[1~"; KeyEnd[0] = KeyEnd[1] = KeyEnd[2] = KeyEnd[3] = "\u001b[4~"; Escape[0] = Escape[1] = Escape[2] = Escape[3] = "\u001b"; if (vms) { BackSpace[1] = "" + (char) 10; // VMS shift deletes word back BackSpace[2] = "\u0018"; // VMS control deletes line back BackSpace[0] = BackSpace[3] = "\u007f"; // VMS other is delete } else { //BackSpace[0] = BackSpace[1] = BackSpace[2] = BackSpace[3] = "\b"; // ConnectBot modifications. BackSpace[0] = "\b"; BackSpace[1] = "\u007f"; BackSpace[2] = "\u001b[3~"; BackSpace[3] = "\u001b[2~"; } /* some more VT100 keys */ Help = "\u001b[28~"; Do = "\u001b[29~"; FunctionKey = new String[21]; FunctionKey[0] = ""; FunctionKey[1] = PF1; FunctionKey[2] = PF2; FunctionKey[3] = PF3; FunctionKey[4] = PF4; /* following are defined differently for vt220 / vt132 ... */ FunctionKey[5] = "\u001b[15~"; FunctionKey[6] = "\u001b[17~"; FunctionKey[7] = "\u001b[18~"; FunctionKey[8] = "\u001b[19~"; FunctionKey[9] = "\u001b[20~"; FunctionKey[10] = "\u001b[21~"; FunctionKey[11] = "\u001b[23~"; FunctionKey[12] = "\u001b[24~"; FunctionKey[13] = "\u001b[25~"; FunctionKey[14] = "\u001b[26~"; FunctionKey[15] = Help; FunctionKey[16] = Do; FunctionKey[17] = "\u001b[31~"; FunctionKey[18] = "\u001b[32~"; FunctionKey[19] = "\u001b[33~"; FunctionKey[20] = "\u001b[34~"; FunctionKeyShift = new String[21]; FunctionKeyAlt = new String[21]; FunctionKeyCtrl = new String[21]; for (int i = 0; i < 20; i++) { FunctionKeyShift[i] = ""; FunctionKeyAlt[i] = ""; FunctionKeyCtrl[i] = ""; } TabKey[0] = "\u0009"; TabKey[1] = "\u001bOP\u0009"; TabKey[2] = TabKey[3] = ""; KeyUp = new String[4]; KeyUp[0] = "\u001b[A"; KeyDown = new String[4]; KeyDown[0] = "\u001b[B"; KeyRight = new String[4]; KeyRight[0] = "\u001b[C"; KeyLeft = new String[4]; KeyLeft[0] = "\u001b[D"; Numpad = new String[10]; Numpad[0] = "\u001bOp"; Numpad[1] = "\u001bOq"; Numpad[2] = "\u001bOr"; Numpad[3] = "\u001bOs"; Numpad[4] = "\u001bOt"; Numpad[5] = "\u001bOu"; Numpad[6] = "\u001bOv"; Numpad[7] = "\u001bOw"; Numpad[8] = "\u001bOx"; Numpad[9] = "\u001bOy"; KPMinus = PF4; KPComma = "\u001bOl"; KPPeriod = "\u001bOn"; KPEnter = "\u001bOM"; NUMPlus = new String[4]; NUMPlus[0] = "+"; NUMDot = new String[4]; NUMDot[0] = "."; } public void setBackspace(int type) { switch (type) { case DELETE_IS_DEL: BackSpace[0] = "\u007f"; BackSpace[1] = "\b"; break; case DELETE_IS_BACKSPACE: BackSpace[0] = "\b"; BackSpace[1] = "\u007f"; break; } } /** * Create a default vt320 terminal with 80 columns and 24 lines. */ public vt320() { this(80, 24); } /** * Terminal is mouse-aware and requires (x,y) coordinates of * on the terminal (character coordinates) and the button clicked. * @param x * @param y * @param modifiers */ public void mousePressed(int x, int y, int modifiers) { if (mouserpt == 0) return; int mods = modifiers; mousebut = 3; if ((mods & 16) == 16) mousebut = 0; if ((mods & 8) == 8) mousebut = 1; if ((mods & 4) == 4) mousebut = 2; int mousecode; if (mouserpt == 9) /* X10 Mouse */ mousecode = 0x20 | mousebut; else /* normal xterm mouse reporting */ mousecode = mousebut | 0x20 | ((mods & 7) << 2); byte b[] = new byte[6]; b[0] = 27; b[1] = (byte) '['; b[2] = (byte) 'M'; b[3] = (byte) mousecode; b[4] = (byte) (0x20 + x + 1); b[5] = (byte) (0x20 + y + 1); write(b); // FIXME: writeSpecial here } /** * Terminal is mouse-aware and requires the coordinates and button * of the release. * @param x * @param y * @param modifiers */ public void mouseReleased(int x, int y, int modifiers) { if (mouserpt == 0) return; /* problem is tht modifiers still have the released button set in them. int mods = modifiers; mousebut = 3; if ((mods & 16)==16) mousebut=0; if ((mods & 8)==8 ) mousebut=1; if ((mods & 4)==4 ) mousebut=2; */ int mousecode; if (mouserpt == 9) mousecode = 0x20 + mousebut; /* same as press? appears so. */ else mousecode = '#'; byte b[] = new byte[6]; b[0] = 27; b[1] = (byte) '['; b[2] = (byte) 'M'; b[3] = (byte) mousecode; b[4] = (byte) (0x20 + x + 1); b[5] = (byte) (0x20 + y + 1); write(b); // FIXME: writeSpecial here mousebut = 0; } /** we should do localecho (passed from other modules). false is default */ private boolean localecho = false; /** * Enable or disable the local echo property of the terminal. * @param echo true if the terminal should echo locally */ public void setLocalEcho(boolean echo) { localecho = echo; } /** * Enable the VMS mode of the terminal to handle some things differently * for VMS hosts. * @param vms true for vms mode, false for normal mode */ public void setVMS(boolean vms) { this.vms = vms; } /** * Enable the usage of the IBM character set used by some BBS's. Special * graphical character are available in this mode. * @param ibm true to use the ibm character set */ public void setIBMCharset(boolean ibm) { useibmcharset = ibm; } /** * Override the standard key codes used by the terminal emulation. * @param codes a properties object containing key code definitions */ public void setKeyCodes(Properties codes) { String res, prefixes[] = {"", "S", "C", "A"}; int i; for (i = 0; i < 10; i++) { res = codes.getProperty("NUMPAD" + i); if (res != null) Numpad[i] = unEscape(res); } for (i = 1; i < 20; i++) { res = codes.getProperty("F" + i); if (res != null) FunctionKey[i] = unEscape(res); res = codes.getProperty("SF" + i); if (res != null) FunctionKeyShift[i] = unEscape(res); res = codes.getProperty("CF" + i); if (res != null) FunctionKeyCtrl[i] = unEscape(res); res = codes.getProperty("AF" + i); if (res != null) FunctionKeyAlt[i] = unEscape(res); } for (i = 0; i < 4; i++) { res = codes.getProperty(prefixes[i] + "PGUP"); if (res != null) PrevScn[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "PGDOWN"); if (res != null) NextScn[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "END"); if (res != null) KeyEnd[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "HOME"); if (res != null) KeyHome[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "INSERT"); if (res != null) Insert[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "REMOVE"); if (res != null) Remove[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "UP"); if (res != null) KeyUp[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "DOWN"); if (res != null) KeyDown[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "LEFT"); if (res != null) KeyLeft[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "RIGHT"); if (res != null) KeyRight[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "ESCAPE"); if (res != null) Escape[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "BACKSPACE"); if (res != null) BackSpace[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "TAB"); if (res != null) TabKey[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "NUMPLUS"); if (res != null) NUMPlus[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "NUMDECIMAL"); if (res != null) NUMDot[i] = unEscape(res); } } /** * Set the terminal id used to identify this terminal. * @param terminalID the id string */ public void setTerminalID(String terminalID) { this.terminalID = terminalID; if (terminalID.equals("scoansi")) { FunctionKey[1] = "\u001b[M"; FunctionKey[2] = "\u001b[N"; FunctionKey[3] = "\u001b[O"; FunctionKey[4] = "\u001b[P"; FunctionKey[5] = "\u001b[Q"; FunctionKey[6] = "\u001b[R"; FunctionKey[7] = "\u001b[S"; FunctionKey[8] = "\u001b[T"; FunctionKey[9] = "\u001b[U"; FunctionKey[10] = "\u001b[V"; FunctionKey[11] = "\u001b[W"; FunctionKey[12] = "\u001b[X"; FunctionKey[13] = "\u001b[Y"; FunctionKey[14] = "?"; FunctionKey[15] = "\u001b[a"; FunctionKey[16] = "\u001b[b"; FunctionKey[17] = "\u001b[c"; FunctionKey[18] = "\u001b[d"; FunctionKey[19] = "\u001b[e"; FunctionKey[20] = "\u001b[f"; PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[I"; NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[G"; // more theoretically. } } public void setAnswerBack(String ab) { this.answerBack = unEscape(ab); } /** * Get the terminal id used to identify this terminal. */ public String getTerminalID() { return terminalID; } /** * A small conveniance method thar converts the string to a byte array * for sending. * @param s the string to be sent */ private boolean write(String s, boolean doecho) { if (debug > 2) { debugStr.append("write(|") .append(s) .append("|,") .append(doecho); debug(debugStr.toString()); debugStr.setLength(0); } if (s == null) // aka the empty string. return true; /* NOTE: getBytes() honours some locale, it *CONVERTS* the string. * However, we output only 7bit stuff towards the target, and *some* * 8 bit control codes. We must not mess up the latter, so we do hand * by hand copy. */ byte arr[] = new byte[s.length()]; for (int i = 0; i < s.length(); i++) { arr[i] = (byte) s.charAt(i); } write(arr); if (doecho) putString(s); return true; } private boolean write(int s, boolean doecho) { if (debug > 2) { debugStr.append("write(|") .append(s) .append("|,") .append(doecho); debug(debugStr.toString()); debugStr.setLength(0); } write(s); // TODO check if character is wide if (doecho) putChar((char)s, false, false); return true; } private boolean write(String s) { return write(s, localecho); } // =================================================================== // the actual terminal emulation code comes here: // =================================================================== private String terminalID = "vt320"; private String answerBack = "Use Terminal.answerback to set ...\n"; // X - COLUMNS, Y - ROWS int R,C; int attributes = 0; int Sc,Sr,Sa,Stm,Sbm; char Sgr,Sgl; char Sgx[]; int insertmode = 0; int statusmode = 0; boolean vt52mode = false; boolean keypadmode = false; /* false - numeric, true - application */ boolean output8bit = false; int normalcursor = 0; boolean moveoutsidemargins = true; boolean wraparound = true; boolean sendcrlf = true; boolean capslock = false; boolean numlock = false; int mouserpt = 0; byte mousebut = 0; boolean useibmcharset = false; int lastwaslf = 0; boolean usedcharsets = false; private final static char ESC = 27; private final static char IND = 132; private final static char NEL = 133; private final static char RI = 141; private final static char SS2 = 142; private final static char SS3 = 143; private final static char DCS = 144; private final static char HTS = 136; private final static char CSI = 155; private final static char OSC = 157; private final static int TSTATE_DATA = 0; private final static int TSTATE_ESC = 1; /* ESC */ private final static int TSTATE_CSI = 2; /* ESC [ */ private final static int TSTATE_DCS = 3; /* ESC P */ private final static int TSTATE_DCEQ = 4; /* ESC [? */ private final static int TSTATE_ESCSQUARE = 5; /* ESC # */ private final static int TSTATE_OSC = 6; /* ESC ] */ private final static int TSTATE_SETG0 = 7; /* ESC (? */ private final static int TSTATE_SETG1 = 8; /* ESC )? */ private final static int TSTATE_SETG2 = 9; /* ESC *? */ private final static int TSTATE_SETG3 = 10; /* ESC +? */ private final static int TSTATE_CSI_DOLLAR = 11; /* ESC [ Pn $ */ private final static int TSTATE_CSI_EX = 12; /* ESC [ ! */ private final static int TSTATE_ESCSPACE = 13; /* ESC <space> */ private final static int TSTATE_VT52X = 14; private final static int TSTATE_VT52Y = 15; private final static int TSTATE_CSI_TICKS = 16; private final static int TSTATE_CSI_EQUAL = 17; /* ESC [ = */ private final static int TSTATE_TITLE = 18; /* xterm title */ /* Keys we support */ public final static int KEY_PAUSE = 1; public final static int KEY_F1 = 2; public final static int KEY_F2 = 3; public final static int KEY_F3 = 4; public final static int KEY_F4 = 5; public final static int KEY_F5 = 6; public final static int KEY_F6 = 7; public final static int KEY_F7 = 8; public final static int KEY_F8 = 9; public final static int KEY_F9 = 10; public final static int KEY_F10 = 11; public final static int KEY_F11 = 12; public final static int KEY_F12 = 13; public final static int KEY_UP = 14; public final static int KEY_DOWN =15 ; public final static int KEY_LEFT = 16; public final static int KEY_RIGHT = 17; public final static int KEY_PAGE_DOWN = 18; public final static int KEY_PAGE_UP = 19; public final static int KEY_INSERT = 20; public final static int KEY_DELETE = 21; public final static int KEY_BACK_SPACE = 22; public final static int KEY_HOME = 23; public final static int KEY_END = 24; public final static int KEY_NUM_LOCK = 25; public final static int KEY_CAPS_LOCK = 26; public final static int KEY_SHIFT = 27; public final static int KEY_CONTROL = 28; public final static int KEY_ALT = 29; public final static int KEY_ENTER = 30; public final static int KEY_NUMPAD0 = 31; public final static int KEY_NUMPAD1 = 32; public final static int KEY_NUMPAD2 = 33; public final static int KEY_NUMPAD3 = 34; public final static int KEY_NUMPAD4 = 35; public final static int KEY_NUMPAD5 = 36; public final static int KEY_NUMPAD6 = 37; public final static int KEY_NUMPAD7 = 38; public final static int KEY_NUMPAD8 = 39; public final static int KEY_NUMPAD9 = 40; public final static int KEY_DECIMAL = 41; public final static int KEY_ADD = 42; public final static int KEY_ESCAPE = 43; public final static int DELETE_IS_DEL = 0; public final static int DELETE_IS_BACKSPACE = 1; /* The graphics charsets * B - default ASCII * A - ISO Latin 1 * 0 - DEC SPECIAL * < - User defined * .... */ char gx[]; char gl; // GL (left charset) char gr; // GR (right charset) int onegl; // single shift override for GL. // Map from scoansi linedrawing to DEC _and_ unicode (for the stuff which // is not in linedrawing). Got from experimenting with scoadmin. private final static String scoansi_acs = "Tm7k3x4u?kZl@mYjEnB\u2566DqCtAvM\u2550:\u2551N\u2557I\u2554;\u2557H\u255a0a<\u255d"; // array to store DEC Special -> Unicode mapping // Unicode DEC Unicode name (DEC name) private static char DECSPECIAL[] = { '\u0040', //5f blank '\u2666', //60 black diamond '\u2592', //61 grey square '\u2409', //62 Horizontal tab (ht) pict. for control '\u240c', //63 Form Feed (ff) pict. for control '\u240d', //64 Carriage Return (cr) pict. for control '\u240a', //65 Line Feed (lf) pict. for control '\u00ba', //66 Masculine ordinal indicator '\u00b1', //67 Plus or minus sign '\u2424', //68 New Line (nl) pict. for control '\u240b', //69 Vertical Tab (vt) pict. for control '\u2518', //6a Forms light up and left '\u2510', //6b Forms light down and left '\u250c', //6c Forms light down and right '\u2514', //6d Forms light up and right '\u253c', //6e Forms light vertical and horizontal '\u2594', //6f Upper 1/8 block (Scan 1) '\u2580', //70 Upper 1/2 block (Scan 3) '\u2500', //71 Forms light horizontal or ?em dash? (Scan 5) '\u25ac', //72 \u25ac black rect. or \u2582 lower 1/4 (Scan 7) '\u005f', //73 \u005f underscore or \u2581 lower 1/8 (Scan 9) '\u251c', //74 Forms light vertical and right '\u2524', //75 Forms light vertical and left '\u2534', //76 Forms light up and horizontal '\u252c', //77 Forms light down and horizontal '\u2502', //78 vertical bar '\u2264', //79 less than or equal '\u2265', //7a greater than or equal '\u00b6', //7b paragraph '\u2260', //7c not equal '\u00a3', //7d Pound Sign (british) '\u00b7' //7e Middle Dot }; /** Strings to send on function key pressing */ private String Numpad[]; private String FunctionKey[]; private String FunctionKeyShift[]; private String FunctionKeyCtrl[]; private String FunctionKeyAlt[]; private String TabKey[]; private String KeyUp[],KeyDown[],KeyLeft[],KeyRight[]; private String KPMinus, KPComma, KPPeriod, KPEnter; private String PF1, PF2, PF3, PF4; private String Help, Do, Find, Select; private String KeyHome[], KeyEnd[], Insert[], Remove[], PrevScn[], NextScn[]; private String Escape[], BackSpace[], NUMDot[], NUMPlus[]; private String osc,dcs; /* to memorize OSC & DCS control sequence */ /** vt320 state variable (internal) */ private int term_state = TSTATE_DATA; /** in vms mode, set by Terminal.VMS property */ private boolean vms = false; /** Tabulators */ private byte[] Tabs; /** The list of integers as used by CSI */ private int[] DCEvars = new int[30]; private int DCEvar; /** * Replace escape code characters (backslash + identifier) with their * respective codes. * @param tmp the string to be parsed * @return a unescaped string */ static String unEscape(String tmp) { int idx = 0, oldidx = 0; String cmd; // f.println("unescape("+tmp+")"); cmd = ""; while ((idx = tmp.indexOf('\\', oldidx)) >= 0 && ++idx <= tmp.length()) { cmd += tmp.substring(oldidx, idx - 1); if (idx == tmp.length()) return cmd; switch (tmp.charAt(idx)) { case 'b': cmd += "\b"; break; case 'e': cmd += "\u001b"; break; case 'n': cmd += "\n"; break; case 'r': cmd += "\r"; break; case 't': cmd += "\t"; break; case 'v': cmd += "\u000b"; break; case 'a': cmd += "\u0012"; break; default : if ((tmp.charAt(idx) >= '0') && (tmp.charAt(idx) <= '9')) { int i; for (i = idx; i < tmp.length(); i++) if ((tmp.charAt(i) < '0') || (tmp.charAt(i) > '9')) break; cmd += (char) Integer.parseInt(tmp.substring(idx, i)); idx = i - 1; } else cmd += tmp.substring(idx, ++idx); break; } oldidx = ++idx; } if (oldidx <= tmp.length()) cmd += tmp.substring(oldidx); return cmd; } /** * A small conveniance method thar converts a 7bit string to the 8bit * version depending on VT52/Output8Bit mode. * * @param s the string to be sent */ private boolean writeSpecial(String s) { if (s == null) return true; if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == 'O'))) { if (vt52mode) { if ((s.charAt(2) >= 'P') && (s.charAt(2) <= 'S')) { s = "\u001b" + s.substring(2); /* ESC x */ } else { s = "\u001b?" + s.substring(2); /* ESC ? x */ } } else { if (output8bit) { s = "\u008f" + s.substring(2); /* SS3 x */ } /* else keep string as it is */ } } if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == '['))) { if (output8bit) { s = "\u009b" + s.substring(2); /* CSI ... */ } /* else keep */ } return write(s, false); } /** * main keytyping event handler... */ public void keyPressed(int keyCode, char keyChar, int modifiers) { boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0; boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0; boolean alt = (modifiers & VDUInput.KEY_ALT) != 0; if (debug > 1) { debugStr.append("keyPressed(") .append(keyCode) .append(", ") .append((int)keyChar) .append(", ") .append(modifiers) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); } int xind; String fmap[]; xind = 0; fmap = FunctionKey; if (shift) { fmap = FunctionKeyShift; xind = 1; } if (control) { fmap = FunctionKeyCtrl; xind = 2; } if (alt) { fmap = FunctionKeyAlt; xind = 3; } switch (keyCode) { case KEY_PAUSE: if (shift || control) sendTelnetCommand((byte) 243); // BREAK break; case KEY_F1: writeSpecial(fmap[1]); break; case KEY_F2: writeSpecial(fmap[2]); break; case KEY_F3: writeSpecial(fmap[3]); break; case KEY_F4: writeSpecial(fmap[4]); break; case KEY_F5: writeSpecial(fmap[5]); break; case KEY_F6: writeSpecial(fmap[6]); break; case KEY_F7: writeSpecial(fmap[7]); break; case KEY_F8: writeSpecial(fmap[8]); break; case KEY_F9: writeSpecial(fmap[9]); break; case KEY_F10: writeSpecial(fmap[10]); break; case KEY_F11: writeSpecial(fmap[11]); break; case KEY_F12: writeSpecial(fmap[12]); break; case KEY_UP: writeSpecial(KeyUp[xind]); break; case KEY_DOWN: writeSpecial(KeyDown[xind]); break; case KEY_LEFT: writeSpecial(KeyLeft[xind]); break; case KEY_RIGHT: writeSpecial(KeyRight[xind]); break; case KEY_PAGE_DOWN: writeSpecial(NextScn[xind]); break; case KEY_PAGE_UP: writeSpecial(PrevScn[xind]); break; case KEY_INSERT: writeSpecial(Insert[xind]); break; case KEY_DELETE: writeSpecial(Remove[xind]); break; case KEY_BACK_SPACE: writeSpecial(BackSpace[xind]); if (localecho) { if (BackSpace[xind] == "\b") { putString("\b \b"); // make the last char 'deleted' } else { putString(BackSpace[xind]); // echo it } } break; case KEY_HOME: writeSpecial(KeyHome[xind]); break; case KEY_END: writeSpecial(KeyEnd[xind]); break; case KEY_NUM_LOCK: if (vms && control) { writeSpecial(PF1); } if (!control) numlock = !numlock; break; case KEY_CAPS_LOCK: capslock = !capslock; return; case KEY_SHIFT: case KEY_CONTROL: case KEY_ALT: return; default: break; } } /* public void keyReleased(KeyEvent evt) { if (debug > 1) debug("keyReleased("+evt+")"); // ignore } */ /** * Handle key Typed events for the terminal, this will get * all normal key types, but no shift/alt/control/numlock. */ public void keyTyped(int keyCode, char keyChar, int modifiers) { boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0; boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0; boolean alt = (modifiers & VDUInput.KEY_ALT) != 0; if (debug > 1) debug("keyTyped("+keyCode+", "+(int)keyChar+", "+modifiers+")"); if (keyChar == '\t') { if (shift) { write(TabKey[1], false); } else { if (control) { write(TabKey[2], false); } else { if (alt) { write(TabKey[3], false); } else { write(TabKey[0], false); } } } return; } if (alt) { write(((char) (keyChar | 0x80))); return; } if (((keyCode == KEY_ENTER) || (keyChar == 10)) && !control) { write('\r'); if (localecho) putString("\r\n"); // bad hack return; } if ((keyCode == 10) && !control) { debug("Sending \\r"); write('\r'); return; } // FIXME: on german PC keyboards you have to use Alt-Ctrl-q to get an @, // so we can't just use it here... will probably break some other VMS // codes. -Marcus // if(((!vms && keyChar == '2') || keyChar == '@' || keyChar == ' ') // && control) if (((!vms && keyChar == '2') || keyChar == ' ') && control) write(0); if (vms) { if (keyChar == 127 && !control) { if (shift) writeSpecial(Insert[0]); // VMS shift delete = insert else writeSpecial(Remove[0]); // VMS delete = remove return; } else if (control) switch (keyChar) { case '0': writeSpecial(Numpad[0]); return; case '1': writeSpecial(Numpad[1]); return; case '2': writeSpecial(Numpad[2]); return; case '3': writeSpecial(Numpad[3]); return; case '4': writeSpecial(Numpad[4]); return; case '5': writeSpecial(Numpad[5]); return; case '6': writeSpecial(Numpad[6]); return; case '7': writeSpecial(Numpad[7]); return; case '8': writeSpecial(Numpad[8]); return; case '9': writeSpecial(Numpad[9]); return; case '.': writeSpecial(KPPeriod); return; case '-': case 31: writeSpecial(KPMinus); return; case '+': writeSpecial(KPComma); return; case 10: writeSpecial(KPEnter); return; case '/': writeSpecial(PF2); return; case '*': writeSpecial(PF3); return; /* NUMLOCK handled in keyPressed */ default: break; } /* Now what does this do and how did it get here. -Marcus if (shift && keyChar < 32) { write(PF1+(char)(keyChar + 64)); return; } */ } // FIXME: not used? //String fmap[]; int xind; xind = 0; //fmap = FunctionKey; if (shift) { //fmap = FunctionKeyShift; xind = 1; } if (control) { //fmap = FunctionKeyCtrl; xind = 2; } if (alt) { //fmap = FunctionKeyAlt; xind = 3; } if (keyCode == KEY_ESCAPE) { writeSpecial(Escape[xind]); return; } if ((modifiers & VDUInput.KEY_ACTION) != 0) switch (keyCode) { case KEY_NUMPAD0: writeSpecial(Numpad[0]); return; case KEY_NUMPAD1: writeSpecial(Numpad[1]); return; case KEY_NUMPAD2: writeSpecial(Numpad[2]); return; case KEY_NUMPAD3: writeSpecial(Numpad[3]); return; case KEY_NUMPAD4: writeSpecial(Numpad[4]); return; case KEY_NUMPAD5: writeSpecial(Numpad[5]); return; case KEY_NUMPAD6: writeSpecial(Numpad[6]); return; case KEY_NUMPAD7: writeSpecial(Numpad[7]); return; case KEY_NUMPAD8: writeSpecial(Numpad[8]); return; case KEY_NUMPAD9: writeSpecial(Numpad[9]); return; case KEY_DECIMAL: writeSpecial(NUMDot[xind]); return; case KEY_ADD: writeSpecial(NUMPlus[xind]); return; } if (!((keyChar == 8) || (keyChar == 127) || (keyChar == '\r') || (keyChar == '\n'))) { write(keyChar); return; } } private void handle_dcs(String dcs) { debugStr.append("DCS: ") .append(dcs); debug(debugStr.toString()); debugStr.setLength(0); } private void handle_osc(String osc) { if (osc.length() > 2 && osc.substring(0, 2).equals("4;")) { // Define color palette String[] colorData = osc.split(";"); try { int colorIndex = Integer.parseInt(colorData[1]); if ("rgb:".equals(colorData[2].substring(0, 4))) { String[] rgb = colorData[2].substring(4).split("/"); int red = Integer.parseInt(rgb[0].substring(0, 2), 16) & 0xFF; int green = Integer.parseInt(rgb[1].substring(0, 2), 16) & 0xFF; int blue = Integer.parseInt(rgb[2].substring(0, 2), 16) & 0xFF; display.setColor(colorIndex, red, green, blue); } } catch (Exception e) { debugStr.append("OSC: invalid color sequence encountered: ") .append(osc); debug(debugStr.toString()); debugStr.setLength(0); } } else debug("OSC: " + osc); } private final static char unimap[] = { //# //# Name: cp437_DOSLatinUS to Unicode table //# Unicode version: 1.1 //# Table version: 1.1 //# Table format: Format A //# Date: 03/31/95 //# Authors: Michel Suignard <[email protected]> //# Lori Hoerth <[email protected]> //# General notes: none //# //# Format: Three tab-separated columns //# Column #1 is the cp1255_WinHebrew code (in hex) //# Column #2 is the Unicode (in hex as 0xXXXX) //# Column #3 is the Unicode name (follows a comment sign, '#') //# //# The entries are in cp437_DOSLatinUS order //# 0x0000, // #NULL 0x0001, // #START OF HEADING 0x0002, // #START OF TEXT 0x0003, // #END OF TEXT 0x0004, // #END OF TRANSMISSION 0x0005, // #ENQUIRY 0x0006, // #ACKNOWLEDGE 0x0007, // #BELL 0x0008, // #BACKSPACE 0x0009, // #HORIZONTAL TABULATION 0x000a, // #LINE FEED 0x000b, // #VERTICAL TABULATION 0x000c, // #FORM FEED 0x000d, // #CARRIAGE RETURN 0x000e, // #SHIFT OUT 0x000f, // #SHIFT IN 0x0010, // #DATA LINK ESCAPE 0x0011, // #DEVICE CONTROL ONE 0x0012, // #DEVICE CONTROL TWO 0x0013, // #DEVICE CONTROL THREE 0x0014, // #DEVICE CONTROL FOUR 0x0015, // #NEGATIVE ACKNOWLEDGE 0x0016, // #SYNCHRONOUS IDLE 0x0017, // #END OF TRANSMISSION BLOCK 0x0018, // #CANCEL 0x0019, // #END OF MEDIUM 0x001a, // #SUBSTITUTE 0x001b, // #ESCAPE 0x001c, // #FILE SEPARATOR 0x001d, // #GROUP SEPARATOR 0x001e, // #RECORD SEPARATOR 0x001f, // #UNIT SEPARATOR 0x0020, // #SPACE 0x0021, // #EXCLAMATION MARK 0x0022, // #QUOTATION MARK 0x0023, // #NUMBER SIGN 0x0024, // #DOLLAR SIGN 0x0025, // #PERCENT SIGN 0x0026, // #AMPERSAND 0x0027, // #APOSTROPHE 0x0028, // #LEFT PARENTHESIS 0x0029, // #RIGHT PARENTHESIS 0x002a, // #ASTERISK 0x002b, // #PLUS SIGN 0x002c, // #COMMA 0x002d, // #HYPHEN-MINUS 0x002e, // #FULL STOP 0x002f, // #SOLIDUS 0x0030, // #DIGIT ZERO 0x0031, // #DIGIT ONE 0x0032, // #DIGIT TWO 0x0033, // #DIGIT THREE 0x0034, // #DIGIT FOUR 0x0035, // #DIGIT FIVE 0x0036, // #DIGIT SIX 0x0037, // #DIGIT SEVEN 0x0038, // #DIGIT EIGHT 0x0039, // #DIGIT NINE 0x003a, // #COLON 0x003b, // #SEMICOLON 0x003c, // #LESS-THAN SIGN 0x003d, // #EQUALS SIGN 0x003e, // #GREATER-THAN SIGN 0x003f, // #QUESTION MARK 0x0040, // #COMMERCIAL AT 0x0041, // #LATIN CAPITAL LETTER A 0x0042, // #LATIN CAPITAL LETTER B 0x0043, // #LATIN CAPITAL LETTER C 0x0044, // #LATIN CAPITAL LETTER D 0x0045, // #LATIN CAPITAL LETTER E 0x0046, // #LATIN CAPITAL LETTER F 0x0047, // #LATIN CAPITAL LETTER G 0x0048, // #LATIN CAPITAL LETTER H 0x0049, // #LATIN CAPITAL LETTER I 0x004a, // #LATIN CAPITAL LETTER J 0x004b, // #LATIN CAPITAL LETTER K 0x004c, // #LATIN CAPITAL LETTER L 0x004d, // #LATIN CAPITAL LETTER M 0x004e, // #LATIN CAPITAL LETTER N 0x004f, // #LATIN CAPITAL LETTER O 0x0050, // #LATIN CAPITAL LETTER P 0x0051, // #LATIN CAPITAL LETTER Q 0x0052, // #LATIN CAPITAL LETTER R 0x0053, // #LATIN CAPITAL LETTER S 0x0054, // #LATIN CAPITAL LETTER T 0x0055, // #LATIN CAPITAL LETTER U 0x0056, // #LATIN CAPITAL LETTER V 0x0057, // #LATIN CAPITAL LETTER W 0x0058, // #LATIN CAPITAL LETTER X 0x0059, // #LATIN CAPITAL LETTER Y 0x005a, // #LATIN CAPITAL LETTER Z 0x005b, // #LEFT SQUARE BRACKET 0x005c, // #REVERSE SOLIDUS 0x005d, // #RIGHT SQUARE BRACKET 0x005e, // #CIRCUMFLEX ACCENT 0x005f, // #LOW LINE 0x0060, // #GRAVE ACCENT 0x0061, // #LATIN SMALL LETTER A 0x0062, // #LATIN SMALL LETTER B 0x0063, // #LATIN SMALL LETTER C 0x0064, // #LATIN SMALL LETTER D 0x0065, // #LATIN SMALL LETTER E 0x0066, // #LATIN SMALL LETTER F 0x0067, // #LATIN SMALL LETTER G 0x0068, // #LATIN SMALL LETTER H 0x0069, // #LATIN SMALL LETTER I 0x006a, // #LATIN SMALL LETTER J 0x006b, // #LATIN SMALL LETTER K 0x006c, // #LATIN SMALL LETTER L 0x006d, // #LATIN SMALL LETTER M 0x006e, // #LATIN SMALL LETTER N 0x006f, // #LATIN SMALL LETTER O 0x0070, // #LATIN SMALL LETTER P 0x0071, // #LATIN SMALL LETTER Q 0x0072, // #LATIN SMALL LETTER R 0x0073, // #LATIN SMALL LETTER S 0x0074, // #LATIN SMALL LETTER T 0x0075, // #LATIN SMALL LETTER U 0x0076, // #LATIN SMALL LETTER V 0x0077, // #LATIN SMALL LETTER W 0x0078, // #LATIN SMALL LETTER X 0x0079, // #LATIN SMALL LETTER Y 0x007a, // #LATIN SMALL LETTER Z 0x007b, // #LEFT CURLY BRACKET 0x007c, // #VERTICAL LINE 0x007d, // #RIGHT CURLY BRACKET 0x007e, // #TILDE 0x007f, // #DELETE 0x00c7, // #LATIN CAPITAL LETTER C WITH CEDILLA 0x00fc, // #LATIN SMALL LETTER U WITH DIAERESIS 0x00e9, // #LATIN SMALL LETTER E WITH ACUTE 0x00e2, // #LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4, // #LATIN SMALL LETTER A WITH DIAERESIS 0x00e0, // #LATIN SMALL LETTER A WITH GRAVE 0x00e5, // #LATIN SMALL LETTER A WITH RING ABOVE 0x00e7, // #LATIN SMALL LETTER C WITH CEDILLA 0x00ea, // #LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb, // #LATIN SMALL LETTER E WITH DIAERESIS 0x00e8, // #LATIN SMALL LETTER E WITH GRAVE 0x00ef, // #LATIN SMALL LETTER I WITH DIAERESIS 0x00ee, // #LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ec, // #LATIN SMALL LETTER I WITH GRAVE 0x00c4, // #LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5, // #LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c9, // #LATIN CAPITAL LETTER E WITH ACUTE 0x00e6, // #LATIN SMALL LIGATURE AE 0x00c6, // #LATIN CAPITAL LIGATURE AE 0x00f4, // #LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6, // #LATIN SMALL LETTER O WITH DIAERESIS 0x00f2, // #LATIN SMALL LETTER O WITH GRAVE 0x00fb, // #LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00f9, // #LATIN SMALL LETTER U WITH GRAVE 0x00ff, // #LATIN SMALL LETTER Y WITH DIAERESIS 0x00d6, // #LATIN CAPITAL LETTER O WITH DIAERESIS 0x00dc, // #LATIN CAPITAL LETTER U WITH DIAERESIS 0x00a2, // #CENT SIGN 0x00a3, // #POUND SIGN 0x00a5, // #YEN SIGN 0x20a7, // #PESETA SIGN 0x0192, // #LATIN SMALL LETTER F WITH HOOK 0x00e1, // #LATIN SMALL LETTER A WITH ACUTE 0x00ed, // #LATIN SMALL LETTER I WITH ACUTE 0x00f3, // #LATIN SMALL LETTER O WITH ACUTE 0x00fa, // #LATIN SMALL LETTER U WITH ACUTE 0x00f1, // #LATIN SMALL LETTER N WITH TILDE 0x00d1, // #LATIN CAPITAL LETTER N WITH TILDE 0x00aa, // #FEMININE ORDINAL INDICATOR 0x00ba, // #MASCULINE ORDINAL INDICATOR 0x00bf, // #INVERTED QUESTION MARK 0x2310, // #REVERSED NOT SIGN 0x00ac, // #NOT SIGN 0x00bd, // #VULGAR FRACTION ONE HALF 0x00bc, // #VULGAR FRACTION ONE QUARTER 0x00a1, // #INVERTED EXCLAMATION MARK 0x00ab, // #LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bb, // #RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x2591, // #LIGHT SHADE 0x2592, // #MEDIUM SHADE 0x2593, // #DARK SHADE 0x2502, // #BOX DRAWINGS LIGHT VERTICAL 0x2524, // #BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x2561, // #BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562, // #BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2556, // #BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2555, // #BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2563, // #BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2551, // #BOX DRAWINGS DOUBLE VERTICAL 0x2557, // #BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255d, // #BOX DRAWINGS DOUBLE UP AND LEFT 0x255c, // #BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255b, // #BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x2510, // #BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514, // #BOX DRAWINGS LIGHT UP AND RIGHT 0x2534, // #BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x252c, // #BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x251c, // #BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2500, // #BOX DRAWINGS LIGHT HORIZONTAL 0x253c, // #BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x255e, // #BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255f, // #BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x255a, // #BOX DRAWINGS DOUBLE UP AND RIGHT 0x2554, // #BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2569, // #BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x2566, // #BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2560, // #BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2550, // #BOX DRAWINGS DOUBLE HORIZONTAL 0x256c, // #BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2567, // #BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568, // #BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2564, // #BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565, // #BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2559, // #BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x2558, // #BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2552, // #BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553, // #BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x256b, // #BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256a, // #BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x2518, // #BOX DRAWINGS LIGHT UP AND LEFT 0x250c, // #BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2588, // #FULL BLOCK 0x2584, // #LOWER HALF BLOCK 0x258c, // #LEFT HALF BLOCK 0x2590, // #RIGHT HALF BLOCK 0x2580, // #UPPER HALF BLOCK 0x03b1, // #GREEK SMALL LETTER ALPHA 0x00df, // #LATIN SMALL LETTER SHARP S 0x0393, // #GREEK CAPITAL LETTER GAMMA 0x03c0, // #GREEK SMALL LETTER PI 0x03a3, // #GREEK CAPITAL LETTER SIGMA 0x03c3, // #GREEK SMALL LETTER SIGMA 0x00b5, // #MICRO SIGN 0x03c4, // #GREEK SMALL LETTER TAU 0x03a6, // #GREEK CAPITAL LETTER PHI 0x0398, // #GREEK CAPITAL LETTER THETA 0x03a9, // #GREEK CAPITAL LETTER OMEGA 0x03b4, // #GREEK SMALL LETTER DELTA 0x221e, // #INFINITY 0x03c6, // #GREEK SMALL LETTER PHI 0x03b5, // #GREEK SMALL LETTER EPSILON 0x2229, // #INTERSECTION 0x2261, // #IDENTICAL TO 0x00b1, // #PLUS-MINUS SIGN 0x2265, // #GREATER-THAN OR EQUAL TO 0x2264, // #LESS-THAN OR EQUAL TO 0x2320, // #TOP HALF INTEGRAL 0x2321, // #BOTTOM HALF INTEGRAL 0x00f7, // #DIVISION SIGN 0x2248, // #ALMOST EQUAL TO 0x00b0, // #DEGREE SIGN 0x2219, // #BULLET OPERATOR 0x00b7, // #MIDDLE DOT 0x221a, // #SQUARE ROOT 0x207f, // #SUPERSCRIPT LATIN SMALL LETTER N 0x00b2, // #SUPERSCRIPT TWO 0x25a0, // #BLACK SQUARE 0x00a0, // #NO-BREAK SPACE }; public char map_cp850_unicode(char x) { if (x >= 0x100) return x; return unimap[x]; } private void _SetCursor(int row, int col) { int maxr = height - 1; int tm = getTopMargin(); R = (row < 0)?0: row; C = (col < 0)?0: (col >= width) ? width - 1 : col; if (!moveoutsidemargins) { R += tm; maxr = getBottomMargin(); } if (R > maxr) R = maxr; } private void putChar(char c, boolean isWide, boolean doshowcursor) { int rows = this.height; //statusline int columns = this.width; // byte msg[]; // if (debug > 4) { // debugStr.append("putChar(") // .append(c) // .append(" [") // .append((int) c) // .append("]) at R=") // .append(R) // .append(" , C=") // .append(C) // .append(", columns=") // .append(columns) // .append(", rows=") // .append(rows); // debug(debugStr.toString()); // debugStr.setLength(0); // } // markLine(R, 1); // if (c > 255) { // if (debug > 0) // debug("char > 255:" + (int) c); // //return; // } switch (term_state) { case TSTATE_DATA: /* FIXME: we shouldn't use chars with bit 8 set if ibmcharset. * probably... but some BBS do anyway... */ if (!useibmcharset) { boolean doneflag = true; switch (c) { case OSC: osc = ""; term_state = TSTATE_OSC; break; case RI: if (R > getTopMargin()) R--; else insertLine(R, 1, SCROLL_DOWN); if (debug > 1) debug("RI"); break; case IND: if (debug > 2) { debugStr.append("IND at ") .append(R) .append(", tm is ") .append(getTopMargin()) .append(", bm is ") .append(getBottomMargin()); debug(debugStr.toString()); debugStr.setLength(0); } if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; if (debug > 1) debug("IND (at " + R + " )"); break; case NEL: if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; C = 0; if (debug > 1) debug("NEL (at " + R + " )"); break; case HTS: Tabs[C] = 1; if (debug > 1) debug("HTS"); break; case DCS: dcs = ""; term_state = TSTATE_DCS; break; default: doneflag = false; break; } if (doneflag) break; } switch (c) { case SS3: onegl = 3; break; case SS2: onegl = 2; break; case CSI: // should be in the 8bit section, but some BBS use this DCEvar = 0; DCEvars[0] = 0; DCEvars[1] = 0; DCEvars[2] = 0; DCEvars[3] = 0; term_state = TSTATE_CSI; break; case ESC: term_state = TSTATE_ESC; lastwaslf = 0; break; case 5: /* ENQ */ write(answerBack, false); break; case 12: /* FormFeed, Home for the BBS world */ deleteArea(0, 0, columns, rows, attributes); C = R = 0; break; case '\b': /* 8 */ C--; if (C < 0) C = 0; lastwaslf = 0; break; case '\t': do { // Don't overwrite or insert! TABS are not destructive, but movement! C++; } while (C < columns && (Tabs[C] == 0)); lastwaslf = 0; break; case '\r': // 13 CR C = 0; break; case '\n': // 10 LF if (debug > 3) debug("R= " + R + ", bm " + getBottomMargin() + ", tm=" + getTopMargin() + ", rows=" + rows); if (!vms) { if (lastwaslf != 0 && lastwaslf != c) // Ray: I do not understand this logic. break; lastwaslf = c; /*C = 0;*/ } if (R == getBottomMargin() || R >= rows - 1) insertLine(R, 1, SCROLL_UP); else R++; break; case 7: beep(); break; case '\016': /* SMACS , as */ /* ^N, Shift out - Put G1 into GL */ gl = 1; usedcharsets = true; break; case '\017': /* RMACS , ae */ /* ^O, Shift in - Put G0 into GL */ gl = 0; usedcharsets = true; break; default: { int thisgl = gl; if (onegl >= 0) { thisgl = onegl; onegl = -1; } lastwaslf = 0; if (c < 32) { if (c != 0) if (debug > 0) debug("TSTATE_DATA char: " + ((int) c)); /*break; some BBS really want those characters, like hearst etc. */ if (c == 0) /* print 0 ... you bet */ break; } if (C >= columns) { if (wraparound) { int bot = rows; // If we're in the scroll region, check against the bottom margin if (R <= getBottomMargin() && R >= getTopMargin()) bot = getBottomMargin() + 1; if (R < bot - 1) R++; else { if (debug > 3) debug("scrolling due to wrap at " + R); insertLine(R, 1, SCROLL_UP); } C = 0; } else { // cursor stays on last character. C = columns - 1; } } boolean mapped = false; // Mapping if DEC Special is chosen charset if (usedcharsets) { if (c >= '\u0020' && c <= '\u007f') { switch (gx[thisgl]) { case '0': // Remap SCOANSI line drawing to VT100 line drawing chars // for our SCO using customers. if (terminalID.equals("scoansi") || terminalID.equals("ansi")) { for (int i = 0; i < scoansi_acs.length(); i += 2) { if (c == scoansi_acs.charAt(i)) { c = scoansi_acs.charAt(i + 1); break; } } } if (c >= '\u005f' && c <= '\u007e') { c = DECSPECIAL[(short) c - 0x5f]; mapped = true; } break; case '<': // 'user preferred' is currently 'ISO Latin-1 suppl c = (char) ((c & 0x7f) | 0x80); mapped = true; break; case 'A': case 'B': // Latin-1 , ASCII -> fall through mapped = true; break; default: debug("Unsupported GL mapping: " + gx[thisgl]); break; } } if (!mapped && (c >= '\u0080' && c <= '\u00ff')) { switch (gx[gr]) { case '0': if (c >= '\u00df' && c <= '\u00fe') { c = DECSPECIAL[c - '\u00df']; mapped = true; } break; case '<': case 'A': case 'B': mapped = true; break; default: debug("Unsupported GR mapping: " + gx[gr]); break; } } } if (!mapped && useibmcharset) c = map_cp850_unicode(c); /*if(true || (statusmode == 0)) { */ if (isWide) { if (C >= columns - 1) { if (wraparound) { int bot = rows; // If we're in the scroll region, check against the bottom margin if (R <= getBottomMargin() && R >= getTopMargin()) bot = getBottomMargin() + 1; if (R < bot - 1) R++; else { if (debug > 3) debug("scrolling due to wrap at " + R); insertLine(R, 1, SCROLL_UP); } C = 0; } else { // cursor stays on last wide character. C = columns - 2; } } } if (insertmode == 1) { if (isWide) { insertChar(C++, R, c, attributes | FULLWIDTH); insertChar(C, R, ' ', attributes | FULLWIDTH); } else insertChar(C, R, c, attributes); } else { if (isWide) { putChar(C++, R, c, attributes | FULLWIDTH); putChar(C, R, ' ', attributes | FULLWIDTH); } else putChar(C, R, c, attributes); } /* } else { if (insertmode==1) { insertChar(C, rows, c, attributes); } else { putChar(C, rows, c, attributes); } } */ C++; break; } } /* switch(c) */ break; case TSTATE_OSC: if ((c < 0x20) && (c != ESC)) {// NP - No printing character handle_osc(osc); term_state = TSTATE_DATA; break; } //but check for vt102 ESC \ if (c == '\\' && osc.charAt(osc.length() - 1) == ESC) { handle_osc(osc); term_state = TSTATE_DATA; break; } osc = osc + c; break; case TSTATE_ESCSPACE: term_state = TSTATE_DATA; switch (c) { case 'F': /* S7C1T, Disable output of 8-bit controls, use 7-bit */ output8bit = false; break; case 'G': /* S8C1T, Enable output of 8-bit control codes*/ output8bit = true; break; default: debug("ESC <space> " + c + " unhandled."); } break; case TSTATE_ESC: term_state = TSTATE_DATA; switch (c) { case ' ': term_state = TSTATE_ESCSPACE; break; case '#': term_state = TSTATE_ESCSQUARE; break; case 'c': /* Hard terminal reset */ reset(); break; case '[': DCEvar = 0; DCEvars[0] = 0; DCEvars[1] = 0; DCEvars[2] = 0; DCEvars[3] = 0; term_state = TSTATE_CSI; break; case ']': osc = ""; term_state = TSTATE_OSC; break; case 'P': dcs = ""; term_state = TSTATE_DCS; break; case 'A': /* CUU */ R--; if (R < 0) R = 0; break; case 'B': /* CUD */ R++; if (R >= rows) R = rows - 1; break; case 'C': C++; if (C >= columns) C = columns - 1; break; case 'I': // RI insertLine(R, 1, SCROLL_DOWN); break; case 'E': /* NEL */ if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; C = 0; if (debug > 1) debug("ESC E (at " + R + ")"); break; case 'D': /* IND */ if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; if (debug > 1) debug("ESC D (at " + R + " )"); break; case 'J': /* erase to end of screen */ if (R < rows - 1) deleteArea(0, R + 1, columns, rows - R - 1, attributes); if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 'K': if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 'M': // RI debug("ESC M : R is "+R+", tm is "+getTopMargin()+", bm is "+getBottomMargin()); if (R > getTopMargin()) { // just go up 1 line. R--; } else { // scroll down insertLine(R, 1, SCROLL_DOWN); } /* else do nothing ; */ if (debug > 2) debug("ESC M "); break; case 'H': if (debug > 1) debug("ESC H at " + C); /* right border probably ...*/ if (C >= columns) C = columns - 1; Tabs[C] = 1; break; case 'N': // SS2 onegl = 2; break; case 'O': // SS3 onegl = 3; break; case '=': /*application keypad*/ if (debug > 0) debug("ESC ="); keypadmode = true; break; case '<': /* vt52 mode off */ vt52mode = false; break; case '>': /*normal keypad*/ if (debug > 0) debug("ESC >"); keypadmode = false; break; case '7': /* DECSC: save cursor, attributes */ Sc = C; Sr = R; Sgl = gl; Sgr = gr; Sa = attributes; Sgx = new char[4]; for (int i = 0; i < 4; i++) Sgx[i] = gx[i]; if (debug > 1) debug("ESC 7"); break; case '8': /* DECRC: restore cursor, attributes */ C = Sc; R = Sr; gl = Sgl; gr = Sgr; if (Sgx != null) for (int i = 0; i < 4; i++) gx[i] = Sgx[i]; attributes = Sa; if (debug > 1) debug("ESC 8"); break; case '(': /* Designate G0 Character set (ISO 2022) */ term_state = TSTATE_SETG0; usedcharsets = true; break; case ')': /* Designate G1 character set (ISO 2022) */ term_state = TSTATE_SETG1; usedcharsets = true; break; case '*': /* Designate G2 Character set (ISO 2022) */ term_state = TSTATE_SETG2; usedcharsets = true; break; case '+': /* Designate G3 Character set (ISO 2022) */ term_state = TSTATE_SETG3; usedcharsets = true; break; case '~': /* Locking Shift 1, right */ gr = 1; usedcharsets = true; break; case 'n': /* Locking Shift 2 */ gl = 2; usedcharsets = true; break; case '}': /* Locking Shift 2, right */ gr = 2; usedcharsets = true; break; case 'o': /* Locking Shift 3 */ gl = 3; usedcharsets = true; break; case '|': /* Locking Shift 3, right */ gr = 3; usedcharsets = true; break; case 'Y': /* vt52 cursor address mode , next chars are x,y */ term_state = TSTATE_VT52Y; break; case '_': term_state = TSTATE_TITLE; break; case '\\': // TODO save title term_state = TSTATE_DATA; break; default: debug("ESC unknown letter: " + c + " (" + ((int) c) + ")"); break; } break; case TSTATE_VT52X: C = c - 37; if (C < 0) C = 0; else if (C >= width) C = width - 1; term_state = TSTATE_VT52Y; break; case TSTATE_VT52Y: R = c - 37; if (R < 0) R = 0; else if (R >= height) R = height - 1; term_state = TSTATE_DATA; break; case TSTATE_SETG0: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC ( " + c + ": G0 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC ( : G0 char set (" + c + " " + ((int) c) + ")"); gx[0] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG1: if (c != '0' && c != 'A' && c != 'B' && c != '<') { debug("ESC ) " + c + " (" + ((int) c) + ") :G1 char set?"); } else { if (debug > 2) debug("ESC ) :G1 char set (" + c + " " + ((int) c) + ")"); gx[1] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG2: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC*:G2 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC*:G2 char set (" + c + " " + ((int) c) + ")"); gx[2] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG3: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC+:G3 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC+:G3 char set (" + c + " " + ((int) c) + ")"); gx[3] = c; } term_state = TSTATE_DATA; break; case TSTATE_ESCSQUARE: switch (c) { case '8': for (int i = 0; i < columns; i++) for (int j = 0; j < rows; j++) putChar(i, j, 'E', 0); break; default: debug("ESC # " + c + " not supported."); break; } term_state = TSTATE_DATA; break; case TSTATE_DCS: if (c == '\\' && dcs.charAt(dcs.length() - 1) == ESC) { handle_dcs(dcs); term_state = TSTATE_DATA; break; } dcs = dcs + c; break; case TSTATE_DCEQ: term_state = TSTATE_DATA; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_DCEQ; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_DCEQ; break; case 's': // XTERM_SAVE missing! if (true || debug > 1) debug("ESC [ ? " + DCEvars[0] + " s unimplemented!"); break; case 'r': // XTERM_RESTORE if (true || debug > 1) debug("ESC [ ? " + DCEvars[0] + " r"); /* DEC Mode reset */ for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 3: /* 80 columns*/ setScreenSize(80, height, true); break; case 4: /* scrolling mode, smooth */ break; case 5: /* light background */ break; case 6: /* DECOM (Origin Mode) move inside margins. */ moveoutsidemargins = true; break; case 7: /* DECAWM: Autowrap Mode */ wraparound = false; break; case 12:/* local echo off */ break; case 9: /* X10 mouse */ case 1000: /* xterm style mouse report on */ case 1001: case 1002: case 1003: mouserpt = DCEvars[i]; break; default: debug("ESC [ ? " + DCEvars[0] + " r, unimplemented!"); } } break; case 'h': // DECSET if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " h"); /* DEC Mode set */ for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 1: /* Application cursor keys */ KeyUp[0] = "\u001bOA"; KeyDown[0] = "\u001bOB"; KeyRight[0] = "\u001bOC"; KeyLeft[0] = "\u001bOD"; break; case 2: /* DECANM */ vt52mode = false; break; case 3: /* 132 columns*/ setScreenSize(132, height, true); break; case 6: /* DECOM: move inside margins. */ moveoutsidemargins = false; break; case 7: /* DECAWM: Autowrap Mode */ wraparound = true; break; case 25: /* turn cursor on */ showCursor(true); break; case 9: /* X10 mouse */ case 1000: /* xterm style mouse report on */ case 1001: case 1002: case 1003: mouserpt = DCEvars[i]; break; /* unimplemented stuff, fall through */ /* 4 - scrolling mode, smooth */ /* 5 - light background */ /* 12 - local echo off */ /* 18 - DECPFF - Printer Form Feed Mode -> On */ /* 19 - DECPEX - Printer Extent Mode -> Screen */ default: debug("ESC [ ? " + DCEvars[0] + " h, unsupported."); break; } } break; case 'i': // DEC Printer Control, autoprint, echo screenchars to printer // This is different to CSI i! // Also: "Autoprint prints a final display line only when the // cursor is moved off the line by an autowrap or LF, FF, or // VT (otherwise do not print the line)." switch (DCEvars[0]) { case 1: if (debug > 1) debug("CSI ? 1 i : Print line containing cursor"); break; case 4: if (debug > 1) debug("CSI ? 4 i : Start passthrough printing"); break; case 5: if (debug > 1) debug("CSI ? 4 i : Stop passthrough printing"); break; } break; case 'l': //DECRST /* DEC Mode reset */ if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " l"); for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 1: /* Application cursor keys */ KeyUp[0] = "\u001b[A"; KeyDown[0] = "\u001b[B"; KeyRight[0] = "\u001b[C"; KeyLeft[0] = "\u001b[D"; break; case 2: /* DECANM */ vt52mode = true; break; case 3: /* 80 columns*/ setScreenSize(80, height, true); break; case 6: /* DECOM: move outside margins. */ moveoutsidemargins = true; break; case 7: /* DECAWM: Autowrap Mode OFF */ wraparound = false; break; case 25: /* turn cursor off */ showCursor(false); break; /* Unimplemented stuff: */ /* 4 - scrolling mode, jump */ /* 5 - dark background */ /* 7 - DECAWM - no wrap around mode */ /* 12 - local echo on */ /* 18 - DECPFF - Printer Form Feed Mode -> Off*/ /* 19 - DECPEX - Printer Extent Mode -> Scrolling Region */ case 9: /* X10 mouse */ case 1000: /* xterm style mouse report OFF */ case 1001: case 1002: case 1003: mouserpt = 0; break; default: debug("ESC [ ? " + DCEvars[0] + " l, unsupported."); break; } } break; case 'n': if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " n"); switch (DCEvars[0]) { case 15: /* printer? no printer. */ write((ESC) + "[?13n", false); debug("ESC[5n"); break; default: debug("ESC [ ? " + DCEvars[0] + " n, unsupported."); break; } break; default: debug("ESC [ ? " + DCEvars[0] + " " + c + ", unsupported."); break; } break; case TSTATE_CSI_EX: term_state = TSTATE_DATA; switch (c) { case ESC: term_state = TSTATE_ESC; break; default: debug("Unknown character ESC[! character is " + (int) c); break; } break; case TSTATE_CSI_TICKS: term_state = TSTATE_DATA; switch (c) { case 'p': debug("Conformance level: " + DCEvars[0] + " (unsupported)," + DCEvars[1]); if (DCEvars[0] == 61) { output8bit = false; break; } if (DCEvars[1] == 1) { output8bit = false; } else { output8bit = true; /* 0 or 2 */ } break; default: debug("Unknown ESC [... \"" + c); break; } break; case TSTATE_CSI_EQUAL: term_state = TSTATE_DATA; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_CSI_EQUAL; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_CSI_EQUAL; break; case 'F': /* SCO ANSI foreground */ { int newcolor; debug("ESC [ = "+DCEvars[0]+" F"); attributes &= ~COLOR_FG; newcolor = ((DCEvars[0] & 1) << 2) | (DCEvars[0] & 2) | ((DCEvars[0] & 4) >> 2) ; attributes |= (newcolor+1) << COLOR_FG_SHIFT; break; } case 'G': /* SCO ANSI background */ { int newcolor; debug("ESC [ = "+DCEvars[0]+" G"); attributes &= ~COLOR_BG; newcolor = ((DCEvars[0] & 1) << 2) | (DCEvars[0] & 2) | ((DCEvars[0] & 4) >> 2) ; attributes |= (newcolor+1) << COLOR_BG_SHIFT; break; } default: debugStr.append("Unknown ESC [ = "); for (int i=0;i<=DCEvar;i++) { debugStr.append(DCEvars[i]) .append(','); } debugStr.append(c); debug(debugStr.toString()); debugStr.setLength(0); break; } break; case TSTATE_CSI_DOLLAR: term_state = TSTATE_DATA; switch (c) { case '}': debug("Active Status Display now " + DCEvars[0]); statusmode = DCEvars[0]; break; /* bad documentation? case '-': debug("Set Status Display now "+DCEvars[0]); break; */ case '~': debug("Status Line mode now " + DCEvars[0]); break; default: debug("UNKNOWN Status Display code " + c + ", with Pn=" + DCEvars[0]); break; } break; case TSTATE_CSI: term_state = TSTATE_DATA; switch (c) { case '"': term_state = TSTATE_CSI_TICKS; break; case '$': term_state = TSTATE_CSI_DOLLAR; break; case '=': term_state = TSTATE_CSI_EQUAL; break; case '!': term_state = TSTATE_CSI_EX; break; case '?': DCEvar = 0; DCEvars[0] = 0; term_state = TSTATE_DCEQ; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_CSI; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_CSI; break; case 'c':/* send primary device attributes */ /* send (ESC[?61c) */ String subcode = ""; if (terminalID.equals("vt320")) subcode = "63;"; if (terminalID.equals("vt220")) subcode = "62;"; if (terminalID.equals("vt100")) subcode = "61;"; write((ESC) + "[?" + subcode + "1;2c", false); if (debug > 1) debug("ESC [ " + DCEvars[0] + " c"); break; case 'q': if (debug > 1) debug("ESC [ " + DCEvars[0] + " q"); break; case 'g': /* used for tabsets */ switch (DCEvars[0]) { case 3:/* clear them */ Tabs = new byte[width]; break; case 0: Tabs[C] = 0; break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " g"); break; case 'h': switch (DCEvars[0]) { case 4: insertmode = 1; break; case 20: debug("Setting CRLF to TRUE"); sendcrlf = true; break; default: debug("unsupported: ESC [ " + DCEvars[0] + " h"); break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " h"); break; case 'i': // Printer Controller mode. // "Transparent printing sends all output, except the CSI 4 i // termination string, to the printer and not the screen, // uses an 8-bit channel if no parity so NUL and DEL will be // seen by the printer and by the termination recognizer code, // and all translation and character set selections are // bypassed." switch (DCEvars[0]) { case 0: if (debug > 1) debug("CSI 0 i: Print Screen, not implemented."); break; case 4: if (debug > 1) debug("CSI 4 i: Enable Transparent Printing, not implemented."); break; case 5: if (debug > 1) debug("CSI 4/5 i: Disable Transparent Printing, not implemented."); break; default: debug("ESC [ " + DCEvars[0] + " i, unimplemented!"); } break; case 'l': switch (DCEvars[0]) { case 4: insertmode = 0; break; case 20: debug("Setting CRLF to FALSE"); sendcrlf = false; break; default: debug("ESC [ " + DCEvars[0] + " l, unimplemented!"); break; } break; case 'A': // CUU { int limit; /* FIXME: xterm only cares about 0 and topmargin */ if (R >= getTopMargin()) { limit = getTopMargin(); } else limit = 0; if (DCEvars[0] == 0) R--; else R -= DCEvars[0]; if (R < limit) R = limit; if (debug > 1) debug("ESC [ " + DCEvars[0] + " A"); break; } case 'B': // CUD /* cursor down n (1) times */ { int limit; if (R <= getBottomMargin()) { limit = getBottomMargin(); } else limit = rows - 1; if (DCEvars[0] == 0) R++; else R += DCEvars[0]; if (R > limit) R = limit; else { if (debug > 2) debug("Not limited."); } if (debug > 2) debug("to: " + R); if (debug > 1) debug("ESC [ " + DCEvars[0] + " B (at C=" + C + ")"); break; } case 'C': if (DCEvars[0] == 0) DCEvars[0] = 1; while (DCEvars[0]-- > 0) { C++; } if (C >= columns) C = columns - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " C"); break; case 'd': // CVA R = DCEvars[0]; if (R < 0) R = 0; else if (R >= height) R = height - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " d"); break; case 'D': if (DCEvars[0] == 0) DCEvars[0] = 1; while (DCEvars[0]-- > 0) { C--; } if (C < 0) C = 0; if (debug > 1) debug("ESC [ " + DCEvars[0] + " D"); break; case 'r': // DECSTBM if (DCEvar > 0) // Ray: Any argument is optional { R = DCEvars[1] - 1; if (R < 0) R = rows - 1; else if (R >= rows) { R = rows - 1; } } else R = rows - 1; int bot = R; if (R >= DCEvars[0]) { R = DCEvars[0] - 1; if (R < 0) R = 0; } setMargins(R, bot); _SetCursor(0, 0); if (debug > 1) debug("ESC [" + DCEvars[0] + " ; " + DCEvars[1] + " r"); break; case 'G': /* CUP / cursor absolute column */ C = DCEvars[0]; if (C < 0) C = 0; else if (C >= width) C = width - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " G"); break; case 'H': /* CUP / cursor position */ /* gets 2 arguments */ _SetCursor(DCEvars[0] - 1, DCEvars[1] - 1); if (debug > 2) { debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " H, moveoutsidemargins " + moveoutsidemargins); debug(" -> R now " + R + ", C now " + C); } break; case 'f': /* move cursor 2 */ /* gets 2 arguments */ R = DCEvars[0] - 1; C = DCEvars[1] - 1; if (C < 0) C = 0; else if (C >= width) C = width - 1; if (R < 0) R = 0; else if (R >= height) R = height - 1; if (debug > 2) debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " f"); break; case 'S': /* ind aka 'scroll forward' */ if (DCEvars[0] == 0) insertLine(getBottomMargin(), SCROLL_UP); else insertLine(getBottomMargin(), DCEvars[0], SCROLL_UP); break; case 'L': /* insert n lines */ if (DCEvars[0] == 0) insertLine(R, SCROLL_DOWN); else insertLine(R, DCEvars[0], SCROLL_DOWN); if (debug > 1) debug("ESC [ " + DCEvars[0] + "" + (c) + " (at R " + R + ")"); break; case 'T': /* 'ri' aka scroll backward */ if (DCEvars[0] == 0) insertLine(getTopMargin(), SCROLL_DOWN); else insertLine(getTopMargin(), DCEvars[0], SCROLL_DOWN); break; case 'M': if (debug > 1) debug("ESC [ " + DCEvars[0] + "" + (c) + " at R=" + R); if (DCEvars[0] == 0) deleteLine(R); else for (int i = 0; i < DCEvars[0]; i++) deleteLine(R); break; case 'K': if (debug > 1) debug("ESC [ " + DCEvars[0] + " K"); /* clear in line */ switch (DCEvars[0]) { case 6: /* 97801 uses ESC[6K for delete to end of line */ case 0:/*clear to right*/ if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 1:/*clear to the left, including this */ if (C > 0) deleteArea(0, R, C + 1, 1, attributes); break; case 2:/*clear whole line */ deleteArea(0, R, columns, 1, attributes); break; } break; case 'J': /* clear below current line */ switch (DCEvars[0]) { case 0: if (R < rows - 1) deleteArea(0, R + 1, columns, rows - R - 1, attributes); if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 1: if (R > 0) deleteArea(0, 0, columns, R, attributes); if (C > 0) deleteArea(0, R, C + 1, 1, attributes);// include up to and including current break; case 2: deleteArea(0, 0, columns, rows, attributes); break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " J"); break; case '@': if (DCEvars[0] == 0) DCEvars[0] = 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " @"); for (int i = 0; i < DCEvars[0]; i++) insertChar(C, R, ' ', attributes); break; case 'X': { int toerase = DCEvars[0]; if (debug > 1) debug("ESC [ " + DCEvars[0] + " X, C=" + C + ",R=" + R); if (toerase == 0) toerase = 1; if (toerase + C > columns) toerase = columns - C; deleteArea(C, R, toerase, 1, attributes); // does not change cursor position break; } case 'P': if (debug > 1) debug("ESC [ " + DCEvars[0] + " P, C=" + C + ",R=" + R); if (DCEvars[0] == 0) DCEvars[0] = 1; for (int i = 0; i < DCEvars[0]; i++) deleteChar(C, R); break; case 'n': switch (DCEvars[0]) { case 5: /* malfunction? No malfunction. */ writeSpecial((ESC) + "[0n"); if (debug > 1) debug("ESC[5n"); break; case 6: // DO NOT offset R and C by 1! (checked against /usr/X11R6/bin/resize // FIXME check again. // FIXME: but vttest thinks different??? writeSpecial((ESC) + "[" + R + ";" + C + "R"); if (debug > 1) debug("ESC[6n"); break; default: if (debug > 0) debug("ESC [ " + DCEvars[0] + " n??"); break; } break; case 's': /* DECSC - save cursor */ Sc = C; Sr = R; Sa = attributes; if (debug > 3) debug("ESC[s"); break; case 'u': /* DECRC - restore cursor */ C = Sc; R = Sr; attributes = Sa; if (debug > 3) debug("ESC[u"); break; case 'm': /* attributes as color, bold , blink,*/ if (debug > 3) debug("ESC [ "); if (DCEvar == 0 && DCEvars[0] == 0) attributes = 0; for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 0: if (DCEvar > 0) { if (terminalID.equals("scoansi")) { attributes &= COLOR; /* Keeps color. Strange but true. */ } else { attributes = 0; } } break; case 1: attributes |= BOLD; attributes &= ~LOW; break; case 2: /* SCO color hack mode */ if (terminalID.equals("scoansi") && ((DCEvar - i) >= 2)) { int ncolor; attributes &= ~(COLOR | BOLD); ncolor = DCEvars[i + 1]; if ((ncolor & 8) == 8) attributes |= BOLD; ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2); attributes |= ((ncolor) + 1) << COLOR_FG_SHIFT; ncolor = DCEvars[i + 2]; ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2); attributes |= ((ncolor) + 1) << COLOR_BG_SHIFT; i += 2; } else { attributes |= LOW; } break; case 3: /* italics */ attributes |= INVERT; break; case 4: attributes |= UNDERLINE; break; case 7: attributes |= INVERT; break; case 8: attributes |= INVISIBLE; break; case 5: /* blink on */ break; /* 10 - ANSI X3.64-1979, select primary font, don't display control * chars, don't set bit 8 on output */ case 10: gl = 0; usedcharsets = true; break; /* 11 - ANSI X3.64-1979, select second alt. font, display control * chars, set bit 8 on output */ case 11: /* SMACS , as */ case 12: gl = 1; usedcharsets = true; break; case 21: /* normal intensity */ attributes &= ~(LOW | BOLD); break; case 23: /* italics off */ attributes &= ~INVERT; break; case 25: /* blinking off */ break; case 27: attributes &= ~INVERT; break; case 28: attributes &= ~INVISIBLE; break; case 24: attributes &= ~UNDERLINE; break; case 22: attributes &= ~BOLD; break; case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: attributes &= ~COLOR_FG; attributes |= ((DCEvars[i] - 30) + 1)<< COLOR_FG_SHIFT; break; case 38: if (DCEvars[i+1] == 5) { attributes &= ~COLOR_FG; attributes |= ((DCEvars[i + 2]) + 1) << COLOR_FG_SHIFT; i += 2; } break; case 39: attributes &= ~COLOR_FG; break; case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: attributes &= ~COLOR_BG; attributes |= ((DCEvars[i] - 40) + 1) << COLOR_BG_SHIFT; break; case 48: if (DCEvars[i+1] == 5) { attributes &= ~COLOR_BG; attributes |= (DCEvars[i + 2] + 1) << COLOR_BG_SHIFT; i += 2; } break; case 49: attributes &= ~COLOR_BG; break; case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: attributes &= ~COLOR_FG; attributes |= ((DCEvars[i] - 82) + 1) << COLOR_FG_SHIFT; break; case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: attributes &= ~COLOR_BG; attributes |= ((DCEvars[i] - 92) + 1) << COLOR_BG_SHIFT; break; default: debugStr.append("ESC [ ") .append(DCEvars[i]) .append(" m unknown..."); debug(debugStr.toString()); debugStr.setLength(0); break; } if (debug > 3) { debugStr.append(DCEvars[i]) .append(';'); debug(debugStr.toString()); debugStr.setLength(0); } } if (debug > 3) { debugStr.append(" (attributes = ") .append(attributes) .append(")m"); debug(debugStr.toString()); debugStr.setLength(0); } break; default: debugStr.append("ESC [ unknown letter: ") .append(c) .append(" (") .append((int)c) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); break; } break; case TSTATE_TITLE: switch (c) { case ESC: term_state = TSTATE_ESC; break; default: // TODO save title break; } break; default: term_state = TSTATE_DATA; break; } setCursorPosition(C, R); } /* hard reset the terminal */ public void reset() { gx[0] = 'B'; gx[1] = 'B'; gx[2] = 'B'; gx[3] = 'B'; gl = 0; // default GL to G0 gr = 2; // default GR to G2 onegl = -1; // Single shift override /* reset tabs */ int nw = width; if (nw < 132) nw = 132; Tabs = new byte[nw]; for (int i = 0; i < nw; i += 8) { Tabs[i] = 1; } deleteArea(0, 0, width, height, attributes); setMargins(0, height); C = R = 0; _SetCursor(0, 0); if (display != null) display.resetColors(); showCursor(true); /*FIXME:*/ term_state = TSTATE_DATA; } }
src/de/mud/terminal/vt320.java
/* * This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform". * * (c) Matthias L. Jugel, Marcus Meissner 1996-2005. All Rights Reserved. * * Please visit http://javatelnet.org/ for updates and contact. * * --LICENSE NOTICE-- * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * --LICENSE NOTICE-- * */ package de.mud.terminal; import android.text.AndroidCharacter; import java.util.Properties; /** * Implementation of a VT terminal emulation plus ANSI compatible. * <P> * <B>Maintainer:</B> Marcus Meissner * * @version $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $ * @author Matthias L. Jugel, Marcus Meissner */ public abstract class vt320 extends VDUBuffer implements VDUInput { /** The current version id tag.<P> * $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $ * */ public final static String ID = "$Id: vt320.java 507 2005-10-25 10:14:52Z marcus $"; /** the debug level */ private final static int debug = 0; private StringBuilder debugStr; public abstract void debug(String notice); /** * Write an answer back to the remote host. This is needed to be able to * send terminal answers requests like status and type information. * @param b the array of bytes to be sent */ public abstract void write(byte[] b); /** * Write an answer back to the remote host. This is needed to be able to * send terminal answers requests like status and type information. * @param b the array of bytes to be sent */ public abstract void write(int b); /** * Play the beep sound ... */ public void beep() { /* do nothing by default */ } /** * Convenience function for putString(char[], int, int) */ public void putString(String s) { int len = s.length(); char[] tmp = new char[len]; s.getChars(0, len, tmp, 0); putString(tmp, null, 0, len); } /** * Put string at current cursor position. Moves cursor * according to the String. Does NOT wrap. * @param s character array * @param start place to start in array * @param len number of characters to process */ public void putString(char[] s, byte[] fullwidths, int start, int len) { if (len > 0) { //markLine(R, 1); int lastChar = -1; char c; boolean isWide = false; for (int i = 0; i < len; i++) { c = s[start + i]; // Shortcut for my favorite ASCII if (c <= 0x7F) { if (lastChar != -1) putChar((char) lastChar, isWide, false); lastChar = c; isWide = false; } else if (!Character.isLowSurrogate(c) && !Character.isHighSurrogate(c)) { if (Character.getType(c) == Character.NON_SPACING_MARK) { if (lastChar != -1) { char nc = Precomposer.precompose((char) lastChar, c); putChar(nc, isWide, false); lastChar = -1; } } else { if (lastChar != -1) putChar((char) lastChar, isWide, false); lastChar = c; if (fullwidths != null) { final byte width = fullwidths[i]; isWide = (width == AndroidCharacter.EAST_ASIAN_WIDTH_WIDE) || (width == AndroidCharacter.EAST_ASIAN_WIDTH_FULL_WIDTH); } } } } if (lastChar != -1) putChar((char) lastChar, isWide, false); setCursorPosition(C, R); redraw(); } } protected void sendTelnetCommand(byte cmd) { } /** * Sent the changed window size from the terminal to all listeners. */ protected void setWindowSize(int c, int r) { /* To be overridden by Terminal.java */ } @Override public void setScreenSize(int c, int r, boolean broadcast) { int oldrows = height; if (debug>2) { if (debugStr == null) debugStr = new StringBuilder(); debugStr.append("setscreensize (") .append(c) .append(',') .append(r) .append(',') .append(broadcast) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); } super.setScreenSize(c,r,false); boolean cursorChanged = false; // Don't let the cursor go off the screen. if (C >= c) { C = c - 1; cursorChanged = true; } if (R >= r) { R = r - 1; cursorChanged = true; } if (cursorChanged) { setCursorPosition(C, R); redraw(); } if (broadcast) { setWindowSize(c, r); /* broadcast up */ } } /** * Create a new vt320 terminal and intialize it with useful settings. */ public vt320(int width, int height) { super(width, height); debugStr = new StringBuilder(); setVMS(false); setIBMCharset(false); setTerminalID("vt320"); setBufferSize(100); //setBorder(2, false); gx = new char[4]; reset(); /* top row of numpad */ PF1 = "\u001bOP"; PF2 = "\u001bOQ"; PF3 = "\u001bOR"; PF4 = "\u001bOS"; /* the 3x2 keyblock on PC keyboards */ Insert = new String[4]; Remove = new String[4]; KeyHome = new String[4]; KeyEnd = new String[4]; NextScn = new String[4]; PrevScn = new String[4]; Escape = new String[4]; BackSpace = new String[4]; TabKey = new String[4]; Insert[0] = Insert[1] = Insert[2] = Insert[3] = "\u001b[2~"; Remove[0] = Remove[1] = Remove[2] = Remove[3] = "\u001b[3~"; PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[5~"; NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[6~"; KeyHome[0] = KeyHome[1] = KeyHome[2] = KeyHome[3] = "\u001b[H"; KeyEnd[0] = KeyEnd[1] = KeyEnd[2] = KeyEnd[3] = "\u001b[F"; Escape[0] = Escape[1] = Escape[2] = Escape[3] = "\u001b"; if (vms) { BackSpace[1] = "" + (char) 10; // VMS shift deletes word back BackSpace[2] = "\u0018"; // VMS control deletes line back BackSpace[0] = BackSpace[3] = "\u007f"; // VMS other is delete } else { //BackSpace[0] = BackSpace[1] = BackSpace[2] = BackSpace[3] = "\b"; // ConnectBot modifications. BackSpace[0] = "\b"; BackSpace[1] = "\u007f"; BackSpace[2] = "\u001b[3~"; BackSpace[3] = "\u001b[2~"; } /* some more VT100 keys */ Find = "\u001b[1~"; Select = "\u001b[4~"; Help = "\u001b[28~"; Do = "\u001b[29~"; FunctionKey = new String[21]; FunctionKey[0] = ""; FunctionKey[1] = PF1; FunctionKey[2] = PF2; FunctionKey[3] = PF3; FunctionKey[4] = PF4; /* following are defined differently for vt220 / vt132 ... */ FunctionKey[5] = "\u001b[15~"; FunctionKey[6] = "\u001b[17~"; FunctionKey[7] = "\u001b[18~"; FunctionKey[8] = "\u001b[19~"; FunctionKey[9] = "\u001b[20~"; FunctionKey[10] = "\u001b[21~"; FunctionKey[11] = "\u001b[23~"; FunctionKey[12] = "\u001b[24~"; FunctionKey[13] = "\u001b[25~"; FunctionKey[14] = "\u001b[26~"; FunctionKey[15] = Help; FunctionKey[16] = Do; FunctionKey[17] = "\u001b[31~"; FunctionKey[18] = "\u001b[32~"; FunctionKey[19] = "\u001b[33~"; FunctionKey[20] = "\u001b[34~"; FunctionKeyShift = new String[21]; FunctionKeyAlt = new String[21]; FunctionKeyCtrl = new String[21]; for (int i = 0; i < 20; i++) { FunctionKeyShift[i] = ""; FunctionKeyAlt[i] = ""; FunctionKeyCtrl[i] = ""; } FunctionKeyShift[15] = Find; FunctionKeyShift[16] = Select; TabKey[0] = "\u0009"; TabKey[1] = "\u001bOP\u0009"; TabKey[2] = TabKey[3] = ""; KeyUp = new String[4]; KeyUp[0] = "\u001b[A"; KeyDown = new String[4]; KeyDown[0] = "\u001b[B"; KeyRight = new String[4]; KeyRight[0] = "\u001b[C"; KeyLeft = new String[4]; KeyLeft[0] = "\u001b[D"; Numpad = new String[10]; Numpad[0] = "\u001bOp"; Numpad[1] = "\u001bOq"; Numpad[2] = "\u001bOr"; Numpad[3] = "\u001bOs"; Numpad[4] = "\u001bOt"; Numpad[5] = "\u001bOu"; Numpad[6] = "\u001bOv"; Numpad[7] = "\u001bOw"; Numpad[8] = "\u001bOx"; Numpad[9] = "\u001bOy"; KPMinus = PF4; KPComma = "\u001bOl"; KPPeriod = "\u001bOn"; KPEnter = "\u001bOM"; NUMPlus = new String[4]; NUMPlus[0] = "+"; NUMDot = new String[4]; NUMDot[0] = "."; } public void setBackspace(int type) { switch (type) { case DELETE_IS_DEL: BackSpace[0] = "\u007f"; BackSpace[1] = "\b"; break; case DELETE_IS_BACKSPACE: BackSpace[0] = "\b"; BackSpace[1] = "\u007f"; break; } } /** * Create a default vt320 terminal with 80 columns and 24 lines. */ public vt320() { this(80, 24); } /** * Terminal is mouse-aware and requires (x,y) coordinates of * on the terminal (character coordinates) and the button clicked. * @param x * @param y * @param modifiers */ public void mousePressed(int x, int y, int modifiers) { if (mouserpt == 0) return; int mods = modifiers; mousebut = 3; if ((mods & 16) == 16) mousebut = 0; if ((mods & 8) == 8) mousebut = 1; if ((mods & 4) == 4) mousebut = 2; int mousecode; if (mouserpt == 9) /* X10 Mouse */ mousecode = 0x20 | mousebut; else /* normal xterm mouse reporting */ mousecode = mousebut | 0x20 | ((mods & 7) << 2); byte b[] = new byte[6]; b[0] = 27; b[1] = (byte) '['; b[2] = (byte) 'M'; b[3] = (byte) mousecode; b[4] = (byte) (0x20 + x + 1); b[5] = (byte) (0x20 + y + 1); write(b); // FIXME: writeSpecial here } /** * Terminal is mouse-aware and requires the coordinates and button * of the release. * @param x * @param y * @param modifiers */ public void mouseReleased(int x, int y, int modifiers) { if (mouserpt == 0) return; /* problem is tht modifiers still have the released button set in them. int mods = modifiers; mousebut = 3; if ((mods & 16)==16) mousebut=0; if ((mods & 8)==8 ) mousebut=1; if ((mods & 4)==4 ) mousebut=2; */ int mousecode; if (mouserpt == 9) mousecode = 0x20 + mousebut; /* same as press? appears so. */ else mousecode = '#'; byte b[] = new byte[6]; b[0] = 27; b[1] = (byte) '['; b[2] = (byte) 'M'; b[3] = (byte) mousecode; b[4] = (byte) (0x20 + x + 1); b[5] = (byte) (0x20 + y + 1); write(b); // FIXME: writeSpecial here mousebut = 0; } /** we should do localecho (passed from other modules). false is default */ private boolean localecho = false; /** * Enable or disable the local echo property of the terminal. * @param echo true if the terminal should echo locally */ public void setLocalEcho(boolean echo) { localecho = echo; } /** * Enable the VMS mode of the terminal to handle some things differently * for VMS hosts. * @param vms true for vms mode, false for normal mode */ public void setVMS(boolean vms) { this.vms = vms; } /** * Enable the usage of the IBM character set used by some BBS's. Special * graphical character are available in this mode. * @param ibm true to use the ibm character set */ public void setIBMCharset(boolean ibm) { useibmcharset = ibm; } /** * Override the standard key codes used by the terminal emulation. * @param codes a properties object containing key code definitions */ public void setKeyCodes(Properties codes) { String res, prefixes[] = {"", "S", "C", "A"}; int i; for (i = 0; i < 10; i++) { res = codes.getProperty("NUMPAD" + i); if (res != null) Numpad[i] = unEscape(res); } for (i = 1; i < 20; i++) { res = codes.getProperty("F" + i); if (res != null) FunctionKey[i] = unEscape(res); res = codes.getProperty("SF" + i); if (res != null) FunctionKeyShift[i] = unEscape(res); res = codes.getProperty("CF" + i); if (res != null) FunctionKeyCtrl[i] = unEscape(res); res = codes.getProperty("AF" + i); if (res != null) FunctionKeyAlt[i] = unEscape(res); } for (i = 0; i < 4; i++) { res = codes.getProperty(prefixes[i] + "PGUP"); if (res != null) PrevScn[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "PGDOWN"); if (res != null) NextScn[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "END"); if (res != null) KeyEnd[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "HOME"); if (res != null) KeyHome[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "INSERT"); if (res != null) Insert[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "REMOVE"); if (res != null) Remove[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "UP"); if (res != null) KeyUp[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "DOWN"); if (res != null) KeyDown[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "LEFT"); if (res != null) KeyLeft[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "RIGHT"); if (res != null) KeyRight[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "ESCAPE"); if (res != null) Escape[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "BACKSPACE"); if (res != null) BackSpace[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "TAB"); if (res != null) TabKey[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "NUMPLUS"); if (res != null) NUMPlus[i] = unEscape(res); res = codes.getProperty(prefixes[i] + "NUMDECIMAL"); if (res != null) NUMDot[i] = unEscape(res); } } /** * Set the terminal id used to identify this terminal. * @param terminalID the id string */ public void setTerminalID(String terminalID) { this.terminalID = terminalID; if (terminalID.equals("scoansi")) { FunctionKey[1] = "\u001b[M"; FunctionKey[2] = "\u001b[N"; FunctionKey[3] = "\u001b[O"; FunctionKey[4] = "\u001b[P"; FunctionKey[5] = "\u001b[Q"; FunctionKey[6] = "\u001b[R"; FunctionKey[7] = "\u001b[S"; FunctionKey[8] = "\u001b[T"; FunctionKey[9] = "\u001b[U"; FunctionKey[10] = "\u001b[V"; FunctionKey[11] = "\u001b[W"; FunctionKey[12] = "\u001b[X"; FunctionKey[13] = "\u001b[Y"; FunctionKey[14] = "?"; FunctionKey[15] = "\u001b[a"; FunctionKey[16] = "\u001b[b"; FunctionKey[17] = "\u001b[c"; FunctionKey[18] = "\u001b[d"; FunctionKey[19] = "\u001b[e"; FunctionKey[20] = "\u001b[f"; PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[I"; NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[G"; // more theoretically. } } public void setAnswerBack(String ab) { this.answerBack = unEscape(ab); } /** * Get the terminal id used to identify this terminal. */ public String getTerminalID() { return terminalID; } /** * A small conveniance method thar converts the string to a byte array * for sending. * @param s the string to be sent */ private boolean write(String s, boolean doecho) { if (debug > 2) { debugStr.append("write(|") .append(s) .append("|,") .append(doecho); debug(debugStr.toString()); debugStr.setLength(0); } if (s == null) // aka the empty string. return true; /* NOTE: getBytes() honours some locale, it *CONVERTS* the string. * However, we output only 7bit stuff towards the target, and *some* * 8 bit control codes. We must not mess up the latter, so we do hand * by hand copy. */ byte arr[] = new byte[s.length()]; for (int i = 0; i < s.length(); i++) { arr[i] = (byte) s.charAt(i); } write(arr); if (doecho) putString(s); return true; } private boolean write(int s, boolean doecho) { if (debug > 2) { debugStr.append("write(|") .append(s) .append("|,") .append(doecho); debug(debugStr.toString()); debugStr.setLength(0); } write(s); // TODO check if character is wide if (doecho) putChar((char)s, false, false); return true; } private boolean write(String s) { return write(s, localecho); } // =================================================================== // the actual terminal emulation code comes here: // =================================================================== private String terminalID = "vt320"; private String answerBack = "Use Terminal.answerback to set ...\n"; // X - COLUMNS, Y - ROWS int R,C; int attributes = 0; int Sc,Sr,Sa,Stm,Sbm; char Sgr,Sgl; char Sgx[]; int insertmode = 0; int statusmode = 0; boolean vt52mode = false; boolean keypadmode = false; /* false - numeric, true - application */ boolean output8bit = false; int normalcursor = 0; boolean moveoutsidemargins = true; boolean wraparound = true; boolean sendcrlf = true; boolean capslock = false; boolean numlock = false; int mouserpt = 0; byte mousebut = 0; boolean useibmcharset = false; int lastwaslf = 0; boolean usedcharsets = false; private final static char ESC = 27; private final static char IND = 132; private final static char NEL = 133; private final static char RI = 141; private final static char SS2 = 142; private final static char SS3 = 143; private final static char DCS = 144; private final static char HTS = 136; private final static char CSI = 155; private final static char OSC = 157; private final static int TSTATE_DATA = 0; private final static int TSTATE_ESC = 1; /* ESC */ private final static int TSTATE_CSI = 2; /* ESC [ */ private final static int TSTATE_DCS = 3; /* ESC P */ private final static int TSTATE_DCEQ = 4; /* ESC [? */ private final static int TSTATE_ESCSQUARE = 5; /* ESC # */ private final static int TSTATE_OSC = 6; /* ESC ] */ private final static int TSTATE_SETG0 = 7; /* ESC (? */ private final static int TSTATE_SETG1 = 8; /* ESC )? */ private final static int TSTATE_SETG2 = 9; /* ESC *? */ private final static int TSTATE_SETG3 = 10; /* ESC +? */ private final static int TSTATE_CSI_DOLLAR = 11; /* ESC [ Pn $ */ private final static int TSTATE_CSI_EX = 12; /* ESC [ ! */ private final static int TSTATE_ESCSPACE = 13; /* ESC <space> */ private final static int TSTATE_VT52X = 14; private final static int TSTATE_VT52Y = 15; private final static int TSTATE_CSI_TICKS = 16; private final static int TSTATE_CSI_EQUAL = 17; /* ESC [ = */ private final static int TSTATE_TITLE = 18; /* xterm title */ /* Keys we support */ public final static int KEY_PAUSE = 1; public final static int KEY_F1 = 2; public final static int KEY_F2 = 3; public final static int KEY_F3 = 4; public final static int KEY_F4 = 5; public final static int KEY_F5 = 6; public final static int KEY_F6 = 7; public final static int KEY_F7 = 8; public final static int KEY_F8 = 9; public final static int KEY_F9 = 10; public final static int KEY_F10 = 11; public final static int KEY_F11 = 12; public final static int KEY_F12 = 13; public final static int KEY_UP = 14; public final static int KEY_DOWN =15 ; public final static int KEY_LEFT = 16; public final static int KEY_RIGHT = 17; public final static int KEY_PAGE_DOWN = 18; public final static int KEY_PAGE_UP = 19; public final static int KEY_INSERT = 20; public final static int KEY_DELETE = 21; public final static int KEY_BACK_SPACE = 22; public final static int KEY_HOME = 23; public final static int KEY_END = 24; public final static int KEY_NUM_LOCK = 25; public final static int KEY_CAPS_LOCK = 26; public final static int KEY_SHIFT = 27; public final static int KEY_CONTROL = 28; public final static int KEY_ALT = 29; public final static int KEY_ENTER = 30; public final static int KEY_NUMPAD0 = 31; public final static int KEY_NUMPAD1 = 32; public final static int KEY_NUMPAD2 = 33; public final static int KEY_NUMPAD3 = 34; public final static int KEY_NUMPAD4 = 35; public final static int KEY_NUMPAD5 = 36; public final static int KEY_NUMPAD6 = 37; public final static int KEY_NUMPAD7 = 38; public final static int KEY_NUMPAD8 = 39; public final static int KEY_NUMPAD9 = 40; public final static int KEY_DECIMAL = 41; public final static int KEY_ADD = 42; public final static int KEY_ESCAPE = 43; public final static int DELETE_IS_DEL = 0; public final static int DELETE_IS_BACKSPACE = 1; /* The graphics charsets * B - default ASCII * A - ISO Latin 1 * 0 - DEC SPECIAL * < - User defined * .... */ char gx[]; char gl; // GL (left charset) char gr; // GR (right charset) int onegl; // single shift override for GL. // Map from scoansi linedrawing to DEC _and_ unicode (for the stuff which // is not in linedrawing). Got from experimenting with scoadmin. private final static String scoansi_acs = "Tm7k3x4u?kZl@mYjEnB\u2566DqCtAvM\u2550:\u2551N\u2557I\u2554;\u2557H\u255a0a<\u255d"; // array to store DEC Special -> Unicode mapping // Unicode DEC Unicode name (DEC name) private static char DECSPECIAL[] = { '\u0040', //5f blank '\u2666', //60 black diamond '\u2592', //61 grey square '\u2409', //62 Horizontal tab (ht) pict. for control '\u240c', //63 Form Feed (ff) pict. for control '\u240d', //64 Carriage Return (cr) pict. for control '\u240a', //65 Line Feed (lf) pict. for control '\u00ba', //66 Masculine ordinal indicator '\u00b1', //67 Plus or minus sign '\u2424', //68 New Line (nl) pict. for control '\u240b', //69 Vertical Tab (vt) pict. for control '\u2518', //6a Forms light up and left '\u2510', //6b Forms light down and left '\u250c', //6c Forms light down and right '\u2514', //6d Forms light up and right '\u253c', //6e Forms light vertical and horizontal '\u2594', //6f Upper 1/8 block (Scan 1) '\u2580', //70 Upper 1/2 block (Scan 3) '\u2500', //71 Forms light horizontal or ?em dash? (Scan 5) '\u25ac', //72 \u25ac black rect. or \u2582 lower 1/4 (Scan 7) '\u005f', //73 \u005f underscore or \u2581 lower 1/8 (Scan 9) '\u251c', //74 Forms light vertical and right '\u2524', //75 Forms light vertical and left '\u2534', //76 Forms light up and horizontal '\u252c', //77 Forms light down and horizontal '\u2502', //78 vertical bar '\u2264', //79 less than or equal '\u2265', //7a greater than or equal '\u00b6', //7b paragraph '\u2260', //7c not equal '\u00a3', //7d Pound Sign (british) '\u00b7' //7e Middle Dot }; /** Strings to send on function key pressing */ private String Numpad[]; private String FunctionKey[]; private String FunctionKeyShift[]; private String FunctionKeyCtrl[]; private String FunctionKeyAlt[]; private String TabKey[]; private String KeyUp[],KeyDown[],KeyLeft[],KeyRight[]; private String KPMinus, KPComma, KPPeriod, KPEnter; private String PF1, PF2, PF3, PF4; private String Help, Do, Find, Select; private String KeyHome[], KeyEnd[], Insert[], Remove[], PrevScn[], NextScn[]; private String Escape[], BackSpace[], NUMDot[], NUMPlus[]; private String osc,dcs; /* to memorize OSC & DCS control sequence */ /** vt320 state variable (internal) */ private int term_state = TSTATE_DATA; /** in vms mode, set by Terminal.VMS property */ private boolean vms = false; /** Tabulators */ private byte[] Tabs; /** The list of integers as used by CSI */ private int[] DCEvars = new int[30]; private int DCEvar; /** * Replace escape code characters (backslash + identifier) with their * respective codes. * @param tmp the string to be parsed * @return a unescaped string */ static String unEscape(String tmp) { int idx = 0, oldidx = 0; String cmd; // f.println("unescape("+tmp+")"); cmd = ""; while ((idx = tmp.indexOf('\\', oldidx)) >= 0 && ++idx <= tmp.length()) { cmd += tmp.substring(oldidx, idx - 1); if (idx == tmp.length()) return cmd; switch (tmp.charAt(idx)) { case 'b': cmd += "\b"; break; case 'e': cmd += "\u001b"; break; case 'n': cmd += "\n"; break; case 'r': cmd += "\r"; break; case 't': cmd += "\t"; break; case 'v': cmd += "\u000b"; break; case 'a': cmd += "\u0012"; break; default : if ((tmp.charAt(idx) >= '0') && (tmp.charAt(idx) <= '9')) { int i; for (i = idx; i < tmp.length(); i++) if ((tmp.charAt(i) < '0') || (tmp.charAt(i) > '9')) break; cmd += (char) Integer.parseInt(tmp.substring(idx, i)); idx = i - 1; } else cmd += tmp.substring(idx, ++idx); break; } oldidx = ++idx; } if (oldidx <= tmp.length()) cmd += tmp.substring(oldidx); return cmd; } /** * A small conveniance method thar converts a 7bit string to the 8bit * version depending on VT52/Output8Bit mode. * * @param s the string to be sent */ private boolean writeSpecial(String s) { if (s == null) return true; if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == 'O'))) { if (vt52mode) { if ((s.charAt(2) >= 'P') && (s.charAt(2) <= 'S')) { s = "\u001b" + s.substring(2); /* ESC x */ } else { s = "\u001b?" + s.substring(2); /* ESC ? x */ } } else { if (output8bit) { s = "\u008f" + s.substring(2); /* SS3 x */ } /* else keep string as it is */ } } if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == '['))) { if (output8bit) { s = "\u009b" + s.substring(2); /* CSI ... */ } /* else keep */ } return write(s, false); } /** * main keytyping event handler... */ public void keyPressed(int keyCode, char keyChar, int modifiers) { boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0; boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0; boolean alt = (modifiers & VDUInput.KEY_ALT) != 0; if (debug > 1) { debugStr.append("keyPressed(") .append(keyCode) .append(", ") .append((int)keyChar) .append(", ") .append(modifiers) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); } int xind; String fmap[]; xind = 0; fmap = FunctionKey; if (shift) { fmap = FunctionKeyShift; xind = 1; } if (control) { fmap = FunctionKeyCtrl; xind = 2; } if (alt) { fmap = FunctionKeyAlt; xind = 3; } switch (keyCode) { case KEY_PAUSE: if (shift || control) sendTelnetCommand((byte) 243); // BREAK break; case KEY_F1: writeSpecial(fmap[1]); break; case KEY_F2: writeSpecial(fmap[2]); break; case KEY_F3: writeSpecial(fmap[3]); break; case KEY_F4: writeSpecial(fmap[4]); break; case KEY_F5: writeSpecial(fmap[5]); break; case KEY_F6: writeSpecial(fmap[6]); break; case KEY_F7: writeSpecial(fmap[7]); break; case KEY_F8: writeSpecial(fmap[8]); break; case KEY_F9: writeSpecial(fmap[9]); break; case KEY_F10: writeSpecial(fmap[10]); break; case KEY_F11: writeSpecial(fmap[11]); break; case KEY_F12: writeSpecial(fmap[12]); break; case KEY_UP: writeSpecial(KeyUp[xind]); break; case KEY_DOWN: writeSpecial(KeyDown[xind]); break; case KEY_LEFT: writeSpecial(KeyLeft[xind]); break; case KEY_RIGHT: writeSpecial(KeyRight[xind]); break; case KEY_PAGE_DOWN: writeSpecial(NextScn[xind]); break; case KEY_PAGE_UP: writeSpecial(PrevScn[xind]); break; case KEY_INSERT: writeSpecial(Insert[xind]); break; case KEY_DELETE: writeSpecial(Remove[xind]); break; case KEY_BACK_SPACE: writeSpecial(BackSpace[xind]); if (localecho) { if (BackSpace[xind] == "\b") { putString("\b \b"); // make the last char 'deleted' } else { putString(BackSpace[xind]); // echo it } } break; case KEY_HOME: writeSpecial(KeyHome[xind]); break; case KEY_END: writeSpecial(KeyEnd[xind]); break; case KEY_NUM_LOCK: if (vms && control) { writeSpecial(PF1); } if (!control) numlock = !numlock; break; case KEY_CAPS_LOCK: capslock = !capslock; return; case KEY_SHIFT: case KEY_CONTROL: case KEY_ALT: return; default: break; } } /* public void keyReleased(KeyEvent evt) { if (debug > 1) debug("keyReleased("+evt+")"); // ignore } */ /** * Handle key Typed events for the terminal, this will get * all normal key types, but no shift/alt/control/numlock. */ public void keyTyped(int keyCode, char keyChar, int modifiers) { boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0; boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0; boolean alt = (modifiers & VDUInput.KEY_ALT) != 0; if (debug > 1) debug("keyTyped("+keyCode+", "+(int)keyChar+", "+modifiers+")"); if (keyChar == '\t') { if (shift) { write(TabKey[1], false); } else { if (control) { write(TabKey[2], false); } else { if (alt) { write(TabKey[3], false); } else { write(TabKey[0], false); } } } return; } if (alt) { write(((char) (keyChar | 0x80))); return; } if (((keyCode == KEY_ENTER) || (keyChar == 10)) && !control) { write('\r'); if (localecho) putString("\r\n"); // bad hack return; } if ((keyCode == 10) && !control) { debug("Sending \\r"); write('\r'); return; } // FIXME: on german PC keyboards you have to use Alt-Ctrl-q to get an @, // so we can't just use it here... will probably break some other VMS // codes. -Marcus // if(((!vms && keyChar == '2') || keyChar == '@' || keyChar == ' ') // && control) if (((!vms && keyChar == '2') || keyChar == ' ') && control) write(0); if (vms) { if (keyChar == 127 && !control) { if (shift) writeSpecial(Insert[0]); // VMS shift delete = insert else writeSpecial(Remove[0]); // VMS delete = remove return; } else if (control) switch (keyChar) { case '0': writeSpecial(Numpad[0]); return; case '1': writeSpecial(Numpad[1]); return; case '2': writeSpecial(Numpad[2]); return; case '3': writeSpecial(Numpad[3]); return; case '4': writeSpecial(Numpad[4]); return; case '5': writeSpecial(Numpad[5]); return; case '6': writeSpecial(Numpad[6]); return; case '7': writeSpecial(Numpad[7]); return; case '8': writeSpecial(Numpad[8]); return; case '9': writeSpecial(Numpad[9]); return; case '.': writeSpecial(KPPeriod); return; case '-': case 31: writeSpecial(KPMinus); return; case '+': writeSpecial(KPComma); return; case 10: writeSpecial(KPEnter); return; case '/': writeSpecial(PF2); return; case '*': writeSpecial(PF3); return; /* NUMLOCK handled in keyPressed */ default: break; } /* Now what does this do and how did it get here. -Marcus if (shift && keyChar < 32) { write(PF1+(char)(keyChar + 64)); return; } */ } // FIXME: not used? //String fmap[]; int xind; xind = 0; //fmap = FunctionKey; if (shift) { //fmap = FunctionKeyShift; xind = 1; } if (control) { //fmap = FunctionKeyCtrl; xind = 2; } if (alt) { //fmap = FunctionKeyAlt; xind = 3; } if (keyCode == KEY_ESCAPE) { writeSpecial(Escape[xind]); return; } if ((modifiers & VDUInput.KEY_ACTION) != 0) switch (keyCode) { case KEY_NUMPAD0: writeSpecial(Numpad[0]); return; case KEY_NUMPAD1: writeSpecial(Numpad[1]); return; case KEY_NUMPAD2: writeSpecial(Numpad[2]); return; case KEY_NUMPAD3: writeSpecial(Numpad[3]); return; case KEY_NUMPAD4: writeSpecial(Numpad[4]); return; case KEY_NUMPAD5: writeSpecial(Numpad[5]); return; case KEY_NUMPAD6: writeSpecial(Numpad[6]); return; case KEY_NUMPAD7: writeSpecial(Numpad[7]); return; case KEY_NUMPAD8: writeSpecial(Numpad[8]); return; case KEY_NUMPAD9: writeSpecial(Numpad[9]); return; case KEY_DECIMAL: writeSpecial(NUMDot[xind]); return; case KEY_ADD: writeSpecial(NUMPlus[xind]); return; } if (!((keyChar == 8) || (keyChar == 127) || (keyChar == '\r') || (keyChar == '\n'))) { write(keyChar); return; } } private void handle_dcs(String dcs) { debugStr.append("DCS: ") .append(dcs); debug(debugStr.toString()); debugStr.setLength(0); } private void handle_osc(String osc) { if (osc.length() > 2 && osc.substring(0, 2).equals("4;")) { // Define color palette String[] colorData = osc.split(";"); try { int colorIndex = Integer.parseInt(colorData[1]); if ("rgb:".equals(colorData[2].substring(0, 4))) { String[] rgb = colorData[2].substring(4).split("/"); int red = Integer.parseInt(rgb[0].substring(0, 2), 16) & 0xFF; int green = Integer.parseInt(rgb[1].substring(0, 2), 16) & 0xFF; int blue = Integer.parseInt(rgb[2].substring(0, 2), 16) & 0xFF; display.setColor(colorIndex, red, green, blue); } } catch (Exception e) { debugStr.append("OSC: invalid color sequence encountered: ") .append(osc); debug(debugStr.toString()); debugStr.setLength(0); } } else debug("OSC: " + osc); } private final static char unimap[] = { //# //# Name: cp437_DOSLatinUS to Unicode table //# Unicode version: 1.1 //# Table version: 1.1 //# Table format: Format A //# Date: 03/31/95 //# Authors: Michel Suignard <[email protected]> //# Lori Hoerth <[email protected]> //# General notes: none //# //# Format: Three tab-separated columns //# Column #1 is the cp1255_WinHebrew code (in hex) //# Column #2 is the Unicode (in hex as 0xXXXX) //# Column #3 is the Unicode name (follows a comment sign, '#') //# //# The entries are in cp437_DOSLatinUS order //# 0x0000, // #NULL 0x0001, // #START OF HEADING 0x0002, // #START OF TEXT 0x0003, // #END OF TEXT 0x0004, // #END OF TRANSMISSION 0x0005, // #ENQUIRY 0x0006, // #ACKNOWLEDGE 0x0007, // #BELL 0x0008, // #BACKSPACE 0x0009, // #HORIZONTAL TABULATION 0x000a, // #LINE FEED 0x000b, // #VERTICAL TABULATION 0x000c, // #FORM FEED 0x000d, // #CARRIAGE RETURN 0x000e, // #SHIFT OUT 0x000f, // #SHIFT IN 0x0010, // #DATA LINK ESCAPE 0x0011, // #DEVICE CONTROL ONE 0x0012, // #DEVICE CONTROL TWO 0x0013, // #DEVICE CONTROL THREE 0x0014, // #DEVICE CONTROL FOUR 0x0015, // #NEGATIVE ACKNOWLEDGE 0x0016, // #SYNCHRONOUS IDLE 0x0017, // #END OF TRANSMISSION BLOCK 0x0018, // #CANCEL 0x0019, // #END OF MEDIUM 0x001a, // #SUBSTITUTE 0x001b, // #ESCAPE 0x001c, // #FILE SEPARATOR 0x001d, // #GROUP SEPARATOR 0x001e, // #RECORD SEPARATOR 0x001f, // #UNIT SEPARATOR 0x0020, // #SPACE 0x0021, // #EXCLAMATION MARK 0x0022, // #QUOTATION MARK 0x0023, // #NUMBER SIGN 0x0024, // #DOLLAR SIGN 0x0025, // #PERCENT SIGN 0x0026, // #AMPERSAND 0x0027, // #APOSTROPHE 0x0028, // #LEFT PARENTHESIS 0x0029, // #RIGHT PARENTHESIS 0x002a, // #ASTERISK 0x002b, // #PLUS SIGN 0x002c, // #COMMA 0x002d, // #HYPHEN-MINUS 0x002e, // #FULL STOP 0x002f, // #SOLIDUS 0x0030, // #DIGIT ZERO 0x0031, // #DIGIT ONE 0x0032, // #DIGIT TWO 0x0033, // #DIGIT THREE 0x0034, // #DIGIT FOUR 0x0035, // #DIGIT FIVE 0x0036, // #DIGIT SIX 0x0037, // #DIGIT SEVEN 0x0038, // #DIGIT EIGHT 0x0039, // #DIGIT NINE 0x003a, // #COLON 0x003b, // #SEMICOLON 0x003c, // #LESS-THAN SIGN 0x003d, // #EQUALS SIGN 0x003e, // #GREATER-THAN SIGN 0x003f, // #QUESTION MARK 0x0040, // #COMMERCIAL AT 0x0041, // #LATIN CAPITAL LETTER A 0x0042, // #LATIN CAPITAL LETTER B 0x0043, // #LATIN CAPITAL LETTER C 0x0044, // #LATIN CAPITAL LETTER D 0x0045, // #LATIN CAPITAL LETTER E 0x0046, // #LATIN CAPITAL LETTER F 0x0047, // #LATIN CAPITAL LETTER G 0x0048, // #LATIN CAPITAL LETTER H 0x0049, // #LATIN CAPITAL LETTER I 0x004a, // #LATIN CAPITAL LETTER J 0x004b, // #LATIN CAPITAL LETTER K 0x004c, // #LATIN CAPITAL LETTER L 0x004d, // #LATIN CAPITAL LETTER M 0x004e, // #LATIN CAPITAL LETTER N 0x004f, // #LATIN CAPITAL LETTER O 0x0050, // #LATIN CAPITAL LETTER P 0x0051, // #LATIN CAPITAL LETTER Q 0x0052, // #LATIN CAPITAL LETTER R 0x0053, // #LATIN CAPITAL LETTER S 0x0054, // #LATIN CAPITAL LETTER T 0x0055, // #LATIN CAPITAL LETTER U 0x0056, // #LATIN CAPITAL LETTER V 0x0057, // #LATIN CAPITAL LETTER W 0x0058, // #LATIN CAPITAL LETTER X 0x0059, // #LATIN CAPITAL LETTER Y 0x005a, // #LATIN CAPITAL LETTER Z 0x005b, // #LEFT SQUARE BRACKET 0x005c, // #REVERSE SOLIDUS 0x005d, // #RIGHT SQUARE BRACKET 0x005e, // #CIRCUMFLEX ACCENT 0x005f, // #LOW LINE 0x0060, // #GRAVE ACCENT 0x0061, // #LATIN SMALL LETTER A 0x0062, // #LATIN SMALL LETTER B 0x0063, // #LATIN SMALL LETTER C 0x0064, // #LATIN SMALL LETTER D 0x0065, // #LATIN SMALL LETTER E 0x0066, // #LATIN SMALL LETTER F 0x0067, // #LATIN SMALL LETTER G 0x0068, // #LATIN SMALL LETTER H 0x0069, // #LATIN SMALL LETTER I 0x006a, // #LATIN SMALL LETTER J 0x006b, // #LATIN SMALL LETTER K 0x006c, // #LATIN SMALL LETTER L 0x006d, // #LATIN SMALL LETTER M 0x006e, // #LATIN SMALL LETTER N 0x006f, // #LATIN SMALL LETTER O 0x0070, // #LATIN SMALL LETTER P 0x0071, // #LATIN SMALL LETTER Q 0x0072, // #LATIN SMALL LETTER R 0x0073, // #LATIN SMALL LETTER S 0x0074, // #LATIN SMALL LETTER T 0x0075, // #LATIN SMALL LETTER U 0x0076, // #LATIN SMALL LETTER V 0x0077, // #LATIN SMALL LETTER W 0x0078, // #LATIN SMALL LETTER X 0x0079, // #LATIN SMALL LETTER Y 0x007a, // #LATIN SMALL LETTER Z 0x007b, // #LEFT CURLY BRACKET 0x007c, // #VERTICAL LINE 0x007d, // #RIGHT CURLY BRACKET 0x007e, // #TILDE 0x007f, // #DELETE 0x00c7, // #LATIN CAPITAL LETTER C WITH CEDILLA 0x00fc, // #LATIN SMALL LETTER U WITH DIAERESIS 0x00e9, // #LATIN SMALL LETTER E WITH ACUTE 0x00e2, // #LATIN SMALL LETTER A WITH CIRCUMFLEX 0x00e4, // #LATIN SMALL LETTER A WITH DIAERESIS 0x00e0, // #LATIN SMALL LETTER A WITH GRAVE 0x00e5, // #LATIN SMALL LETTER A WITH RING ABOVE 0x00e7, // #LATIN SMALL LETTER C WITH CEDILLA 0x00ea, // #LATIN SMALL LETTER E WITH CIRCUMFLEX 0x00eb, // #LATIN SMALL LETTER E WITH DIAERESIS 0x00e8, // #LATIN SMALL LETTER E WITH GRAVE 0x00ef, // #LATIN SMALL LETTER I WITH DIAERESIS 0x00ee, // #LATIN SMALL LETTER I WITH CIRCUMFLEX 0x00ec, // #LATIN SMALL LETTER I WITH GRAVE 0x00c4, // #LATIN CAPITAL LETTER A WITH DIAERESIS 0x00c5, // #LATIN CAPITAL LETTER A WITH RING ABOVE 0x00c9, // #LATIN CAPITAL LETTER E WITH ACUTE 0x00e6, // #LATIN SMALL LIGATURE AE 0x00c6, // #LATIN CAPITAL LIGATURE AE 0x00f4, // #LATIN SMALL LETTER O WITH CIRCUMFLEX 0x00f6, // #LATIN SMALL LETTER O WITH DIAERESIS 0x00f2, // #LATIN SMALL LETTER O WITH GRAVE 0x00fb, // #LATIN SMALL LETTER U WITH CIRCUMFLEX 0x00f9, // #LATIN SMALL LETTER U WITH GRAVE 0x00ff, // #LATIN SMALL LETTER Y WITH DIAERESIS 0x00d6, // #LATIN CAPITAL LETTER O WITH DIAERESIS 0x00dc, // #LATIN CAPITAL LETTER U WITH DIAERESIS 0x00a2, // #CENT SIGN 0x00a3, // #POUND SIGN 0x00a5, // #YEN SIGN 0x20a7, // #PESETA SIGN 0x0192, // #LATIN SMALL LETTER F WITH HOOK 0x00e1, // #LATIN SMALL LETTER A WITH ACUTE 0x00ed, // #LATIN SMALL LETTER I WITH ACUTE 0x00f3, // #LATIN SMALL LETTER O WITH ACUTE 0x00fa, // #LATIN SMALL LETTER U WITH ACUTE 0x00f1, // #LATIN SMALL LETTER N WITH TILDE 0x00d1, // #LATIN CAPITAL LETTER N WITH TILDE 0x00aa, // #FEMININE ORDINAL INDICATOR 0x00ba, // #MASCULINE ORDINAL INDICATOR 0x00bf, // #INVERTED QUESTION MARK 0x2310, // #REVERSED NOT SIGN 0x00ac, // #NOT SIGN 0x00bd, // #VULGAR FRACTION ONE HALF 0x00bc, // #VULGAR FRACTION ONE QUARTER 0x00a1, // #INVERTED EXCLAMATION MARK 0x00ab, // #LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00bb, // #RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x2591, // #LIGHT SHADE 0x2592, // #MEDIUM SHADE 0x2593, // #DARK SHADE 0x2502, // #BOX DRAWINGS LIGHT VERTICAL 0x2524, // #BOX DRAWINGS LIGHT VERTICAL AND LEFT 0x2561, // #BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE 0x2562, // #BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE 0x2556, // #BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE 0x2555, // #BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE 0x2563, // #BOX DRAWINGS DOUBLE VERTICAL AND LEFT 0x2551, // #BOX DRAWINGS DOUBLE VERTICAL 0x2557, // #BOX DRAWINGS DOUBLE DOWN AND LEFT 0x255d, // #BOX DRAWINGS DOUBLE UP AND LEFT 0x255c, // #BOX DRAWINGS UP DOUBLE AND LEFT SINGLE 0x255b, // #BOX DRAWINGS UP SINGLE AND LEFT DOUBLE 0x2510, // #BOX DRAWINGS LIGHT DOWN AND LEFT 0x2514, // #BOX DRAWINGS LIGHT UP AND RIGHT 0x2534, // #BOX DRAWINGS LIGHT UP AND HORIZONTAL 0x252c, // #BOX DRAWINGS LIGHT DOWN AND HORIZONTAL 0x251c, // #BOX DRAWINGS LIGHT VERTICAL AND RIGHT 0x2500, // #BOX DRAWINGS LIGHT HORIZONTAL 0x253c, // #BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL 0x255e, // #BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE 0x255f, // #BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE 0x255a, // #BOX DRAWINGS DOUBLE UP AND RIGHT 0x2554, // #BOX DRAWINGS DOUBLE DOWN AND RIGHT 0x2569, // #BOX DRAWINGS DOUBLE UP AND HORIZONTAL 0x2566, // #BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL 0x2560, // #BOX DRAWINGS DOUBLE VERTICAL AND RIGHT 0x2550, // #BOX DRAWINGS DOUBLE HORIZONTAL 0x256c, // #BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL 0x2567, // #BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE 0x2568, // #BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE 0x2564, // #BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE 0x2565, // #BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE 0x2559, // #BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE 0x2558, // #BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE 0x2552, // #BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE 0x2553, // #BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE 0x256b, // #BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE 0x256a, // #BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE 0x2518, // #BOX DRAWINGS LIGHT UP AND LEFT 0x250c, // #BOX DRAWINGS LIGHT DOWN AND RIGHT 0x2588, // #FULL BLOCK 0x2584, // #LOWER HALF BLOCK 0x258c, // #LEFT HALF BLOCK 0x2590, // #RIGHT HALF BLOCK 0x2580, // #UPPER HALF BLOCK 0x03b1, // #GREEK SMALL LETTER ALPHA 0x00df, // #LATIN SMALL LETTER SHARP S 0x0393, // #GREEK CAPITAL LETTER GAMMA 0x03c0, // #GREEK SMALL LETTER PI 0x03a3, // #GREEK CAPITAL LETTER SIGMA 0x03c3, // #GREEK SMALL LETTER SIGMA 0x00b5, // #MICRO SIGN 0x03c4, // #GREEK SMALL LETTER TAU 0x03a6, // #GREEK CAPITAL LETTER PHI 0x0398, // #GREEK CAPITAL LETTER THETA 0x03a9, // #GREEK CAPITAL LETTER OMEGA 0x03b4, // #GREEK SMALL LETTER DELTA 0x221e, // #INFINITY 0x03c6, // #GREEK SMALL LETTER PHI 0x03b5, // #GREEK SMALL LETTER EPSILON 0x2229, // #INTERSECTION 0x2261, // #IDENTICAL TO 0x00b1, // #PLUS-MINUS SIGN 0x2265, // #GREATER-THAN OR EQUAL TO 0x2264, // #LESS-THAN OR EQUAL TO 0x2320, // #TOP HALF INTEGRAL 0x2321, // #BOTTOM HALF INTEGRAL 0x00f7, // #DIVISION SIGN 0x2248, // #ALMOST EQUAL TO 0x00b0, // #DEGREE SIGN 0x2219, // #BULLET OPERATOR 0x00b7, // #MIDDLE DOT 0x221a, // #SQUARE ROOT 0x207f, // #SUPERSCRIPT LATIN SMALL LETTER N 0x00b2, // #SUPERSCRIPT TWO 0x25a0, // #BLACK SQUARE 0x00a0, // #NO-BREAK SPACE }; public char map_cp850_unicode(char x) { if (x >= 0x100) return x; return unimap[x]; } private void _SetCursor(int row, int col) { int maxr = height - 1; int tm = getTopMargin(); R = (row < 0)?0: row; C = (col < 0)?0: (col >= width) ? width - 1 : col; if (!moveoutsidemargins) { R += tm; maxr = getBottomMargin(); } if (R > maxr) R = maxr; } private void putChar(char c, boolean isWide, boolean doshowcursor) { int rows = this.height; //statusline int columns = this.width; // byte msg[]; // if (debug > 4) { // debugStr.append("putChar(") // .append(c) // .append(" [") // .append((int) c) // .append("]) at R=") // .append(R) // .append(" , C=") // .append(C) // .append(", columns=") // .append(columns) // .append(", rows=") // .append(rows); // debug(debugStr.toString()); // debugStr.setLength(0); // } // markLine(R, 1); // if (c > 255) { // if (debug > 0) // debug("char > 255:" + (int) c); // //return; // } switch (term_state) { case TSTATE_DATA: /* FIXME: we shouldn't use chars with bit 8 set if ibmcharset. * probably... but some BBS do anyway... */ if (!useibmcharset) { boolean doneflag = true; switch (c) { case OSC: osc = ""; term_state = TSTATE_OSC; break; case RI: if (R > getTopMargin()) R--; else insertLine(R, 1, SCROLL_DOWN); if (debug > 1) debug("RI"); break; case IND: if (debug > 2) { debugStr.append("IND at ") .append(R) .append(", tm is ") .append(getTopMargin()) .append(", bm is ") .append(getBottomMargin()); debug(debugStr.toString()); debugStr.setLength(0); } if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; if (debug > 1) debug("IND (at " + R + " )"); break; case NEL: if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; C = 0; if (debug > 1) debug("NEL (at " + R + " )"); break; case HTS: Tabs[C] = 1; if (debug > 1) debug("HTS"); break; case DCS: dcs = ""; term_state = TSTATE_DCS; break; default: doneflag = false; break; } if (doneflag) break; } switch (c) { case SS3: onegl = 3; break; case SS2: onegl = 2; break; case CSI: // should be in the 8bit section, but some BBS use this DCEvar = 0; DCEvars[0] = 0; DCEvars[1] = 0; DCEvars[2] = 0; DCEvars[3] = 0; term_state = TSTATE_CSI; break; case ESC: term_state = TSTATE_ESC; lastwaslf = 0; break; case 5: /* ENQ */ write(answerBack, false); break; case 12: /* FormFeed, Home for the BBS world */ deleteArea(0, 0, columns, rows, attributes); C = R = 0; break; case '\b': /* 8 */ C--; if (C < 0) C = 0; lastwaslf = 0; break; case '\t': do { // Don't overwrite or insert! TABS are not destructive, but movement! C++; } while (C < columns && (Tabs[C] == 0)); lastwaslf = 0; break; case '\r': // 13 CR C = 0; break; case '\n': // 10 LF if (debug > 3) debug("R= " + R + ", bm " + getBottomMargin() + ", tm=" + getTopMargin() + ", rows=" + rows); if (!vms) { if (lastwaslf != 0 && lastwaslf != c) // Ray: I do not understand this logic. break; lastwaslf = c; /*C = 0;*/ } if (R == getBottomMargin() || R >= rows - 1) insertLine(R, 1, SCROLL_UP); else R++; break; case 7: beep(); break; case '\016': /* SMACS , as */ /* ^N, Shift out - Put G1 into GL */ gl = 1; usedcharsets = true; break; case '\017': /* RMACS , ae */ /* ^O, Shift in - Put G0 into GL */ gl = 0; usedcharsets = true; break; default: { int thisgl = gl; if (onegl >= 0) { thisgl = onegl; onegl = -1; } lastwaslf = 0; if (c < 32) { if (c != 0) if (debug > 0) debug("TSTATE_DATA char: " + ((int) c)); /*break; some BBS really want those characters, like hearst etc. */ if (c == 0) /* print 0 ... you bet */ break; } if (C >= columns) { if (wraparound) { int bot = rows; // If we're in the scroll region, check against the bottom margin if (R <= getBottomMargin() && R >= getTopMargin()) bot = getBottomMargin() + 1; if (R < bot - 1) R++; else { if (debug > 3) debug("scrolling due to wrap at " + R); insertLine(R, 1, SCROLL_UP); } C = 0; } else { // cursor stays on last character. C = columns - 1; } } boolean mapped = false; // Mapping if DEC Special is chosen charset if (usedcharsets) { if (c >= '\u0020' && c <= '\u007f') { switch (gx[thisgl]) { case '0': // Remap SCOANSI line drawing to VT100 line drawing chars // for our SCO using customers. if (terminalID.equals("scoansi") || terminalID.equals("ansi")) { for (int i = 0; i < scoansi_acs.length(); i += 2) { if (c == scoansi_acs.charAt(i)) { c = scoansi_acs.charAt(i + 1); break; } } } if (c >= '\u005f' && c <= '\u007e') { c = DECSPECIAL[(short) c - 0x5f]; mapped = true; } break; case '<': // 'user preferred' is currently 'ISO Latin-1 suppl c = (char) ((c & 0x7f) | 0x80); mapped = true; break; case 'A': case 'B': // Latin-1 , ASCII -> fall through mapped = true; break; default: debug("Unsupported GL mapping: " + gx[thisgl]); break; } } if (!mapped && (c >= '\u0080' && c <= '\u00ff')) { switch (gx[gr]) { case '0': if (c >= '\u00df' && c <= '\u00fe') { c = DECSPECIAL[c - '\u00df']; mapped = true; } break; case '<': case 'A': case 'B': mapped = true; break; default: debug("Unsupported GR mapping: " + gx[gr]); break; } } } if (!mapped && useibmcharset) c = map_cp850_unicode(c); /*if(true || (statusmode == 0)) { */ if (isWide) { if (C >= columns - 1) { if (wraparound) { int bot = rows; // If we're in the scroll region, check against the bottom margin if (R <= getBottomMargin() && R >= getTopMargin()) bot = getBottomMargin() + 1; if (R < bot - 1) R++; else { if (debug > 3) debug("scrolling due to wrap at " + R); insertLine(R, 1, SCROLL_UP); } C = 0; } else { // cursor stays on last wide character. C = columns - 2; } } } if (insertmode == 1) { if (isWide) { insertChar(C++, R, c, attributes | FULLWIDTH); insertChar(C, R, ' ', attributes | FULLWIDTH); } else insertChar(C, R, c, attributes); } else { if (isWide) { putChar(C++, R, c, attributes | FULLWIDTH); putChar(C, R, ' ', attributes | FULLWIDTH); } else putChar(C, R, c, attributes); } /* } else { if (insertmode==1) { insertChar(C, rows, c, attributes); } else { putChar(C, rows, c, attributes); } } */ C++; break; } } /* switch(c) */ break; case TSTATE_OSC: if ((c < 0x20) && (c != ESC)) {// NP - No printing character handle_osc(osc); term_state = TSTATE_DATA; break; } //but check for vt102 ESC \ if (c == '\\' && osc.charAt(osc.length() - 1) == ESC) { handle_osc(osc); term_state = TSTATE_DATA; break; } osc = osc + c; break; case TSTATE_ESCSPACE: term_state = TSTATE_DATA; switch (c) { case 'F': /* S7C1T, Disable output of 8-bit controls, use 7-bit */ output8bit = false; break; case 'G': /* S8C1T, Enable output of 8-bit control codes*/ output8bit = true; break; default: debug("ESC <space> " + c + " unhandled."); } break; case TSTATE_ESC: term_state = TSTATE_DATA; switch (c) { case ' ': term_state = TSTATE_ESCSPACE; break; case '#': term_state = TSTATE_ESCSQUARE; break; case 'c': /* Hard terminal reset */ reset(); break; case '[': DCEvar = 0; DCEvars[0] = 0; DCEvars[1] = 0; DCEvars[2] = 0; DCEvars[3] = 0; term_state = TSTATE_CSI; break; case ']': osc = ""; term_state = TSTATE_OSC; break; case 'P': dcs = ""; term_state = TSTATE_DCS; break; case 'A': /* CUU */ R--; if (R < 0) R = 0; break; case 'B': /* CUD */ R++; if (R >= rows) R = rows - 1; break; case 'C': C++; if (C >= columns) C = columns - 1; break; case 'I': // RI insertLine(R, 1, SCROLL_DOWN); break; case 'E': /* NEL */ if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; C = 0; if (debug > 1) debug("ESC E (at " + R + ")"); break; case 'D': /* IND */ if (R == getBottomMargin() || R == rows - 1) insertLine(R, 1, SCROLL_UP); else R++; if (debug > 1) debug("ESC D (at " + R + " )"); break; case 'J': /* erase to end of screen */ if (R < rows - 1) deleteArea(0, R + 1, columns, rows - R - 1, attributes); if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 'K': if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 'M': // RI debug("ESC M : R is "+R+", tm is "+getTopMargin()+", bm is "+getBottomMargin()); if (R > getTopMargin()) { // just go up 1 line. R--; } else { // scroll down insertLine(R, 1, SCROLL_DOWN); } /* else do nothing ; */ if (debug > 2) debug("ESC M "); break; case 'H': if (debug > 1) debug("ESC H at " + C); /* right border probably ...*/ if (C >= columns) C = columns - 1; Tabs[C] = 1; break; case 'N': // SS2 onegl = 2; break; case 'O': // SS3 onegl = 3; break; case '=': /*application keypad*/ if (debug > 0) debug("ESC ="); keypadmode = true; break; case '<': /* vt52 mode off */ vt52mode = false; break; case '>': /*normal keypad*/ if (debug > 0) debug("ESC >"); keypadmode = false; break; case '7': /* DECSC: save cursor, attributes */ Sc = C; Sr = R; Sgl = gl; Sgr = gr; Sa = attributes; Sgx = new char[4]; for (int i = 0; i < 4; i++) Sgx[i] = gx[i]; if (debug > 1) debug("ESC 7"); break; case '8': /* DECRC: restore cursor, attributes */ C = Sc; R = Sr; gl = Sgl; gr = Sgr; if (Sgx != null) for (int i = 0; i < 4; i++) gx[i] = Sgx[i]; attributes = Sa; if (debug > 1) debug("ESC 8"); break; case '(': /* Designate G0 Character set (ISO 2022) */ term_state = TSTATE_SETG0; usedcharsets = true; break; case ')': /* Designate G1 character set (ISO 2022) */ term_state = TSTATE_SETG1; usedcharsets = true; break; case '*': /* Designate G2 Character set (ISO 2022) */ term_state = TSTATE_SETG2; usedcharsets = true; break; case '+': /* Designate G3 Character set (ISO 2022) */ term_state = TSTATE_SETG3; usedcharsets = true; break; case '~': /* Locking Shift 1, right */ gr = 1; usedcharsets = true; break; case 'n': /* Locking Shift 2 */ gl = 2; usedcharsets = true; break; case '}': /* Locking Shift 2, right */ gr = 2; usedcharsets = true; break; case 'o': /* Locking Shift 3 */ gl = 3; usedcharsets = true; break; case '|': /* Locking Shift 3, right */ gr = 3; usedcharsets = true; break; case 'Y': /* vt52 cursor address mode , next chars are x,y */ term_state = TSTATE_VT52Y; break; case '_': term_state = TSTATE_TITLE; break; case '\\': // TODO save title term_state = TSTATE_DATA; break; default: debug("ESC unknown letter: " + c + " (" + ((int) c) + ")"); break; } break; case TSTATE_VT52X: C = c - 37; if (C < 0) C = 0; else if (C >= width) C = width - 1; term_state = TSTATE_VT52Y; break; case TSTATE_VT52Y: R = c - 37; if (R < 0) R = 0; else if (R >= height) R = height - 1; term_state = TSTATE_DATA; break; case TSTATE_SETG0: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC ( " + c + ": G0 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC ( : G0 char set (" + c + " " + ((int) c) + ")"); gx[0] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG1: if (c != '0' && c != 'A' && c != 'B' && c != '<') { debug("ESC ) " + c + " (" + ((int) c) + ") :G1 char set?"); } else { if (debug > 2) debug("ESC ) :G1 char set (" + c + " " + ((int) c) + ")"); gx[1] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG2: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC*:G2 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC*:G2 char set (" + c + " " + ((int) c) + ")"); gx[2] = c; } term_state = TSTATE_DATA; break; case TSTATE_SETG3: if (c != '0' && c != 'A' && c != 'B' && c != '<') debug("ESC+:G3 char set? (" + ((int) c) + ")"); else { if (debug > 2) debug("ESC+:G3 char set (" + c + " " + ((int) c) + ")"); gx[3] = c; } term_state = TSTATE_DATA; break; case TSTATE_ESCSQUARE: switch (c) { case '8': for (int i = 0; i < columns; i++) for (int j = 0; j < rows; j++) putChar(i, j, 'E', 0); break; default: debug("ESC # " + c + " not supported."); break; } term_state = TSTATE_DATA; break; case TSTATE_DCS: if (c == '\\' && dcs.charAt(dcs.length() - 1) == ESC) { handle_dcs(dcs); term_state = TSTATE_DATA; break; } dcs = dcs + c; break; case TSTATE_DCEQ: term_state = TSTATE_DATA; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_DCEQ; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_DCEQ; break; case 's': // XTERM_SAVE missing! if (true || debug > 1) debug("ESC [ ? " + DCEvars[0] + " s unimplemented!"); break; case 'r': // XTERM_RESTORE if (true || debug > 1) debug("ESC [ ? " + DCEvars[0] + " r"); /* DEC Mode reset */ for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 3: /* 80 columns*/ setScreenSize(80, height, true); break; case 4: /* scrolling mode, smooth */ break; case 5: /* light background */ break; case 6: /* DECOM (Origin Mode) move inside margins. */ moveoutsidemargins = true; break; case 7: /* DECAWM: Autowrap Mode */ wraparound = false; break; case 12:/* local echo off */ break; case 9: /* X10 mouse */ case 1000: /* xterm style mouse report on */ case 1001: case 1002: case 1003: mouserpt = DCEvars[i]; break; default: debug("ESC [ ? " + DCEvars[0] + " r, unimplemented!"); } } break; case 'h': // DECSET if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " h"); /* DEC Mode set */ for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 1: /* Application cursor keys */ KeyUp[0] = "\u001bOA"; KeyDown[0] = "\u001bOB"; KeyRight[0] = "\u001bOC"; KeyLeft[0] = "\u001bOD"; break; case 2: /* DECANM */ vt52mode = false; break; case 3: /* 132 columns*/ setScreenSize(132, height, true); break; case 6: /* DECOM: move inside margins. */ moveoutsidemargins = false; break; case 7: /* DECAWM: Autowrap Mode */ wraparound = true; break; case 25: /* turn cursor on */ showCursor(true); break; case 9: /* X10 mouse */ case 1000: /* xterm style mouse report on */ case 1001: case 1002: case 1003: mouserpt = DCEvars[i]; break; /* unimplemented stuff, fall through */ /* 4 - scrolling mode, smooth */ /* 5 - light background */ /* 12 - local echo off */ /* 18 - DECPFF - Printer Form Feed Mode -> On */ /* 19 - DECPEX - Printer Extent Mode -> Screen */ default: debug("ESC [ ? " + DCEvars[0] + " h, unsupported."); break; } } break; case 'i': // DEC Printer Control, autoprint, echo screenchars to printer // This is different to CSI i! // Also: "Autoprint prints a final display line only when the // cursor is moved off the line by an autowrap or LF, FF, or // VT (otherwise do not print the line)." switch (DCEvars[0]) { case 1: if (debug > 1) debug("CSI ? 1 i : Print line containing cursor"); break; case 4: if (debug > 1) debug("CSI ? 4 i : Start passthrough printing"); break; case 5: if (debug > 1) debug("CSI ? 4 i : Stop passthrough printing"); break; } break; case 'l': //DECRST /* DEC Mode reset */ if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " l"); for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 1: /* Application cursor keys */ KeyUp[0] = "\u001b[A"; KeyDown[0] = "\u001b[B"; KeyRight[0] = "\u001b[C"; KeyLeft[0] = "\u001b[D"; break; case 2: /* DECANM */ vt52mode = true; break; case 3: /* 80 columns*/ setScreenSize(80, height, true); break; case 6: /* DECOM: move outside margins. */ moveoutsidemargins = true; break; case 7: /* DECAWM: Autowrap Mode OFF */ wraparound = false; break; case 25: /* turn cursor off */ showCursor(false); break; /* Unimplemented stuff: */ /* 4 - scrolling mode, jump */ /* 5 - dark background */ /* 7 - DECAWM - no wrap around mode */ /* 12 - local echo on */ /* 18 - DECPFF - Printer Form Feed Mode -> Off*/ /* 19 - DECPEX - Printer Extent Mode -> Scrolling Region */ case 9: /* X10 mouse */ case 1000: /* xterm style mouse report OFF */ case 1001: case 1002: case 1003: mouserpt = 0; break; default: debug("ESC [ ? " + DCEvars[0] + " l, unsupported."); break; } } break; case 'n': if (debug > 0) debug("ESC [ ? " + DCEvars[0] + " n"); switch (DCEvars[0]) { case 15: /* printer? no printer. */ write((ESC) + "[?13n", false); debug("ESC[5n"); break; default: debug("ESC [ ? " + DCEvars[0] + " n, unsupported."); break; } break; default: debug("ESC [ ? " + DCEvars[0] + " " + c + ", unsupported."); break; } break; case TSTATE_CSI_EX: term_state = TSTATE_DATA; switch (c) { case ESC: term_state = TSTATE_ESC; break; default: debug("Unknown character ESC[! character is " + (int) c); break; } break; case TSTATE_CSI_TICKS: term_state = TSTATE_DATA; switch (c) { case 'p': debug("Conformance level: " + DCEvars[0] + " (unsupported)," + DCEvars[1]); if (DCEvars[0] == 61) { output8bit = false; break; } if (DCEvars[1] == 1) { output8bit = false; } else { output8bit = true; /* 0 or 2 */ } break; default: debug("Unknown ESC [... \"" + c); break; } break; case TSTATE_CSI_EQUAL: term_state = TSTATE_DATA; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_CSI_EQUAL; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_CSI_EQUAL; break; case 'F': /* SCO ANSI foreground */ { int newcolor; debug("ESC [ = "+DCEvars[0]+" F"); attributes &= ~COLOR_FG; newcolor = ((DCEvars[0] & 1) << 2) | (DCEvars[0] & 2) | ((DCEvars[0] & 4) >> 2) ; attributes |= (newcolor+1) << COLOR_FG_SHIFT; break; } case 'G': /* SCO ANSI background */ { int newcolor; debug("ESC [ = "+DCEvars[0]+" G"); attributes &= ~COLOR_BG; newcolor = ((DCEvars[0] & 1) << 2) | (DCEvars[0] & 2) | ((DCEvars[0] & 4) >> 2) ; attributes |= (newcolor+1) << COLOR_BG_SHIFT; break; } default: debugStr.append("Unknown ESC [ = "); for (int i=0;i<=DCEvar;i++) { debugStr.append(DCEvars[i]) .append(','); } debugStr.append(c); debug(debugStr.toString()); debugStr.setLength(0); break; } break; case TSTATE_CSI_DOLLAR: term_state = TSTATE_DATA; switch (c) { case '}': debug("Active Status Display now " + DCEvars[0]); statusmode = DCEvars[0]; break; /* bad documentation? case '-': debug("Set Status Display now "+DCEvars[0]); break; */ case '~': debug("Status Line mode now " + DCEvars[0]); break; default: debug("UNKNOWN Status Display code " + c + ", with Pn=" + DCEvars[0]); break; } break; case TSTATE_CSI: term_state = TSTATE_DATA; switch (c) { case '"': term_state = TSTATE_CSI_TICKS; break; case '$': term_state = TSTATE_CSI_DOLLAR; break; case '=': term_state = TSTATE_CSI_EQUAL; break; case '!': term_state = TSTATE_CSI_EX; break; case '?': DCEvar = 0; DCEvars[0] = 0; term_state = TSTATE_DCEQ; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48; term_state = TSTATE_CSI; break; case ';': DCEvar++; DCEvars[DCEvar] = 0; term_state = TSTATE_CSI; break; case 'c':/* send primary device attributes */ /* send (ESC[?61c) */ String subcode = ""; if (terminalID.equals("vt320")) subcode = "63;"; if (terminalID.equals("vt220")) subcode = "62;"; if (terminalID.equals("vt100")) subcode = "61;"; write((ESC) + "[?" + subcode + "1;2c", false); if (debug > 1) debug("ESC [ " + DCEvars[0] + " c"); break; case 'q': if (debug > 1) debug("ESC [ " + DCEvars[0] + " q"); break; case 'g': /* used for tabsets */ switch (DCEvars[0]) { case 3:/* clear them */ Tabs = new byte[width]; break; case 0: Tabs[C] = 0; break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " g"); break; case 'h': switch (DCEvars[0]) { case 4: insertmode = 1; break; case 20: debug("Setting CRLF to TRUE"); sendcrlf = true; break; default: debug("unsupported: ESC [ " + DCEvars[0] + " h"); break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " h"); break; case 'i': // Printer Controller mode. // "Transparent printing sends all output, except the CSI 4 i // termination string, to the printer and not the screen, // uses an 8-bit channel if no parity so NUL and DEL will be // seen by the printer and by the termination recognizer code, // and all translation and character set selections are // bypassed." switch (DCEvars[0]) { case 0: if (debug > 1) debug("CSI 0 i: Print Screen, not implemented."); break; case 4: if (debug > 1) debug("CSI 4 i: Enable Transparent Printing, not implemented."); break; case 5: if (debug > 1) debug("CSI 4/5 i: Disable Transparent Printing, not implemented."); break; default: debug("ESC [ " + DCEvars[0] + " i, unimplemented!"); } break; case 'l': switch (DCEvars[0]) { case 4: insertmode = 0; break; case 20: debug("Setting CRLF to FALSE"); sendcrlf = false; break; default: debug("ESC [ " + DCEvars[0] + " l, unimplemented!"); break; } break; case 'A': // CUU { int limit; /* FIXME: xterm only cares about 0 and topmargin */ if (R >= getTopMargin()) { limit = getTopMargin(); } else limit = 0; if (DCEvars[0] == 0) R--; else R -= DCEvars[0]; if (R < limit) R = limit; if (debug > 1) debug("ESC [ " + DCEvars[0] + " A"); break; } case 'B': // CUD /* cursor down n (1) times */ { int limit; if (R <= getBottomMargin()) { limit = getBottomMargin(); } else limit = rows - 1; if (DCEvars[0] == 0) R++; else R += DCEvars[0]; if (R > limit) R = limit; else { if (debug > 2) debug("Not limited."); } if (debug > 2) debug("to: " + R); if (debug > 1) debug("ESC [ " + DCEvars[0] + " B (at C=" + C + ")"); break; } case 'C': if (DCEvars[0] == 0) DCEvars[0] = 1; while (DCEvars[0]-- > 0) { C++; } if (C >= columns) C = columns - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " C"); break; case 'd': // CVA R = DCEvars[0]; if (R < 0) R = 0; else if (R >= height) R = height - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " d"); break; case 'D': if (DCEvars[0] == 0) DCEvars[0] = 1; while (DCEvars[0]-- > 0) { C--; } if (C < 0) C = 0; if (debug > 1) debug("ESC [ " + DCEvars[0] + " D"); break; case 'r': // DECSTBM if (DCEvar > 0) // Ray: Any argument is optional { R = DCEvars[1] - 1; if (R < 0) R = rows - 1; else if (R >= rows) { R = rows - 1; } } else R = rows - 1; int bot = R; if (R >= DCEvars[0]) { R = DCEvars[0] - 1; if (R < 0) R = 0; } setMargins(R, bot); _SetCursor(0, 0); if (debug > 1) debug("ESC [" + DCEvars[0] + " ; " + DCEvars[1] + " r"); break; case 'G': /* CUP / cursor absolute column */ C = DCEvars[0]; if (C < 0) C = 0; else if (C >= width) C = width - 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " G"); break; case 'H': /* CUP / cursor position */ /* gets 2 arguments */ _SetCursor(DCEvars[0] - 1, DCEvars[1] - 1); if (debug > 2) { debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " H, moveoutsidemargins " + moveoutsidemargins); debug(" -> R now " + R + ", C now " + C); } break; case 'f': /* move cursor 2 */ /* gets 2 arguments */ R = DCEvars[0] - 1; C = DCEvars[1] - 1; if (C < 0) C = 0; else if (C >= width) C = width - 1; if (R < 0) R = 0; else if (R >= height) R = height - 1; if (debug > 2) debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " f"); break; case 'S': /* ind aka 'scroll forward' */ if (DCEvars[0] == 0) insertLine(getBottomMargin(), SCROLL_UP); else insertLine(getBottomMargin(), DCEvars[0], SCROLL_UP); break; case 'L': /* insert n lines */ if (DCEvars[0] == 0) insertLine(R, SCROLL_DOWN); else insertLine(R, DCEvars[0], SCROLL_DOWN); if (debug > 1) debug("ESC [ " + DCEvars[0] + "" + (c) + " (at R " + R + ")"); break; case 'T': /* 'ri' aka scroll backward */ if (DCEvars[0] == 0) insertLine(getTopMargin(), SCROLL_DOWN); else insertLine(getTopMargin(), DCEvars[0], SCROLL_DOWN); break; case 'M': if (debug > 1) debug("ESC [ " + DCEvars[0] + "" + (c) + " at R=" + R); if (DCEvars[0] == 0) deleteLine(R); else for (int i = 0; i < DCEvars[0]; i++) deleteLine(R); break; case 'K': if (debug > 1) debug("ESC [ " + DCEvars[0] + " K"); /* clear in line */ switch (DCEvars[0]) { case 6: /* 97801 uses ESC[6K for delete to end of line */ case 0:/*clear to right*/ if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 1:/*clear to the left, including this */ if (C > 0) deleteArea(0, R, C + 1, 1, attributes); break; case 2:/*clear whole line */ deleteArea(0, R, columns, 1, attributes); break; } break; case 'J': /* clear below current line */ switch (DCEvars[0]) { case 0: if (R < rows - 1) deleteArea(0, R + 1, columns, rows - R - 1, attributes); if (C < columns - 1) deleteArea(C, R, columns - C, 1, attributes); break; case 1: if (R > 0) deleteArea(0, 0, columns, R, attributes); if (C > 0) deleteArea(0, R, C + 1, 1, attributes);// include up to and including current break; case 2: deleteArea(0, 0, columns, rows, attributes); break; } if (debug > 1) debug("ESC [ " + DCEvars[0] + " J"); break; case '@': if (DCEvars[0] == 0) DCEvars[0] = 1; if (debug > 1) debug("ESC [ " + DCEvars[0] + " @"); for (int i = 0; i < DCEvars[0]; i++) insertChar(C, R, ' ', attributes); break; case 'X': { int toerase = DCEvars[0]; if (debug > 1) debug("ESC [ " + DCEvars[0] + " X, C=" + C + ",R=" + R); if (toerase == 0) toerase = 1; if (toerase + C > columns) toerase = columns - C; deleteArea(C, R, toerase, 1, attributes); // does not change cursor position break; } case 'P': if (debug > 1) debug("ESC [ " + DCEvars[0] + " P, C=" + C + ",R=" + R); if (DCEvars[0] == 0) DCEvars[0] = 1; for (int i = 0; i < DCEvars[0]; i++) deleteChar(C, R); break; case 'n': switch (DCEvars[0]) { case 5: /* malfunction? No malfunction. */ writeSpecial((ESC) + "[0n"); if (debug > 1) debug("ESC[5n"); break; case 6: // DO NOT offset R and C by 1! (checked against /usr/X11R6/bin/resize // FIXME check again. // FIXME: but vttest thinks different??? writeSpecial((ESC) + "[" + R + ";" + C + "R"); if (debug > 1) debug("ESC[6n"); break; default: if (debug > 0) debug("ESC [ " + DCEvars[0] + " n??"); break; } break; case 's': /* DECSC - save cursor */ Sc = C; Sr = R; Sa = attributes; if (debug > 3) debug("ESC[s"); break; case 'u': /* DECRC - restore cursor */ C = Sc; R = Sr; attributes = Sa; if (debug > 3) debug("ESC[u"); break; case 'm': /* attributes as color, bold , blink,*/ if (debug > 3) debug("ESC [ "); if (DCEvar == 0 && DCEvars[0] == 0) attributes = 0; for (int i = 0; i <= DCEvar; i++) { switch (DCEvars[i]) { case 0: if (DCEvar > 0) { if (terminalID.equals("scoansi")) { attributes &= COLOR; /* Keeps color. Strange but true. */ } else { attributes = 0; } } break; case 1: attributes |= BOLD; attributes &= ~LOW; break; case 2: /* SCO color hack mode */ if (terminalID.equals("scoansi") && ((DCEvar - i) >= 2)) { int ncolor; attributes &= ~(COLOR | BOLD); ncolor = DCEvars[i + 1]; if ((ncolor & 8) == 8) attributes |= BOLD; ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2); attributes |= ((ncolor) + 1) << COLOR_FG_SHIFT; ncolor = DCEvars[i + 2]; ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2); attributes |= ((ncolor) + 1) << COLOR_BG_SHIFT; i += 2; } else { attributes |= LOW; } break; case 3: /* italics */ attributes |= INVERT; break; case 4: attributes |= UNDERLINE; break; case 7: attributes |= INVERT; break; case 8: attributes |= INVISIBLE; break; case 5: /* blink on */ break; /* 10 - ANSI X3.64-1979, select primary font, don't display control * chars, don't set bit 8 on output */ case 10: gl = 0; usedcharsets = true; break; /* 11 - ANSI X3.64-1979, select second alt. font, display control * chars, set bit 8 on output */ case 11: /* SMACS , as */ case 12: gl = 1; usedcharsets = true; break; case 21: /* normal intensity */ attributes &= ~(LOW | BOLD); break; case 23: /* italics off */ attributes &= ~INVERT; break; case 25: /* blinking off */ break; case 27: attributes &= ~INVERT; break; case 28: attributes &= ~INVISIBLE; break; case 24: attributes &= ~UNDERLINE; break; case 22: attributes &= ~BOLD; break; case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: attributes &= ~COLOR_FG; attributes |= ((DCEvars[i] - 30) + 1)<< COLOR_FG_SHIFT; break; case 38: if (DCEvars[i+1] == 5) { attributes &= ~COLOR_FG; attributes |= ((DCEvars[i + 2]) + 1) << COLOR_FG_SHIFT; i += 2; } break; case 39: attributes &= ~COLOR_FG; break; case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: attributes &= ~COLOR_BG; attributes |= ((DCEvars[i] - 40) + 1) << COLOR_BG_SHIFT; break; case 48: if (DCEvars[i+1] == 5) { attributes &= ~COLOR_BG; attributes |= (DCEvars[i + 2] + 1) << COLOR_BG_SHIFT; i += 2; } break; case 49: attributes &= ~COLOR_BG; break; case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: attributes &= ~COLOR_FG; attributes |= ((DCEvars[i] - 82) + 1) << COLOR_FG_SHIFT; break; case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: attributes &= ~COLOR_BG; attributes |= ((DCEvars[i] - 92) + 1) << COLOR_BG_SHIFT; break; default: debugStr.append("ESC [ ") .append(DCEvars[i]) .append(" m unknown..."); debug(debugStr.toString()); debugStr.setLength(0); break; } if (debug > 3) { debugStr.append(DCEvars[i]) .append(';'); debug(debugStr.toString()); debugStr.setLength(0); } } if (debug > 3) { debugStr.append(" (attributes = ") .append(attributes) .append(")m"); debug(debugStr.toString()); debugStr.setLength(0); } break; default: debugStr.append("ESC [ unknown letter: ") .append(c) .append(" (") .append((int)c) .append(')'); debug(debugStr.toString()); debugStr.setLength(0); break; } break; case TSTATE_TITLE: switch (c) { case ESC: term_state = TSTATE_ESC; break; default: // TODO save title break; } break; default: term_state = TSTATE_DATA; break; } setCursorPosition(C, R); } /* hard reset the terminal */ public void reset() { gx[0] = 'B'; gx[1] = 'B'; gx[2] = 'B'; gx[3] = 'B'; gl = 0; // default GL to G0 gr = 2; // default GR to G2 onegl = -1; // Single shift override /* reset tabs */ int nw = width; if (nw < 132) nw = 132; Tabs = new byte[nw]; for (int i = 0; i < nw; i += 8) { Tabs[i] = 1; } deleteArea(0, 0, width, height, attributes); setMargins(0, height); C = R = 0; _SetCursor(0, 0); if (display != null) display.resetColors(); showCursor(true); /*FIXME:*/ term_state = TSTATE_DATA; } }
vt320: Fix broken home / end keys According to vt320 terminfo (as well as screen and xterm, which connectbot uses to identify itself by default) khome=\E[1~ and kend=\E[4~ The vt320.java however used \E[H for khome and \E[F for kend. But \E[H is used as a sequence to "move cursor to home", and not as a key escape code and \E[F isn't mapped at all. The FunctionKeyShift[15] = Find and FunctionKeyShift[16] = Select which were mapped to \E[1~ and \E[4~ have been removed from vt320.java. They have never been used anyways. for more info see man terminfo(5) infocmp xterm infocmp screen infocmp vt320
src/de/mud/terminal/vt320.java
vt320: Fix broken home / end keys
Java
apache-2.0
62d3ba12284eaf7dcc2affd099f2367033c3c14a
0
max3163/jmeter,kschroeder/jmeter,thomsonreuters/jmeter,d0k1/jmeter,hemikak/jmeter,thomsonreuters/jmeter,DoctorQ/jmeter,liwangbest/jmeter,kyroskoh/jmeter,vherilier/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,etnetera/jmeter,d0k1/jmeter,d0k1/jmeter,ra0077/jmeter,ubikfsabbe/jmeter,hizhangqi/jmeter-1,thomsonreuters/jmeter,ra0077/jmeter,kyroskoh/jmeter,ubikloadpack/jmeter,tuanhq/jmeter,etnetera/jmeter,max3163/jmeter,kschroeder/jmeter,ubikfsabbe/jmeter,etnetera/jmeter,irfanah/jmeter,tuanhq/jmeter,kschroeder/jmeter,fj11/jmeter,liwangbest/jmeter,etnetera/jmeter,ThiagoGarciaAlves/jmeter,hemikak/jmeter,d0k1/jmeter,liwangbest/jmeter,vherilier/jmeter,vherilier/jmeter,tuanhq/jmeter,max3163/jmeter,ThiagoGarciaAlves/jmeter,ra0077/jmeter,irfanah/jmeter,max3163/jmeter,hemikak/jmeter,ThiagoGarciaAlves/jmeter,vherilier/jmeter,kyroskoh/jmeter,hizhangqi/jmeter-1,hemikak/jmeter,DoctorQ/jmeter,irfanah/jmeter,ra0077/jmeter,hizhangqi/jmeter-1,fj11/jmeter,ubikloadpack/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,fj11/jmeter,etnetera/jmeter,DoctorQ/jmeter
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Created on Feb 8, 2005 * */ package org.apache.jorphan.collections; import java.io.IOException; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.apache.jorphan.util.JOrphanUtils; /** * @author mike * TODO does not appear to be used anywhere (except by the test class) */ public class ConfigurationTree implements Serializable, Cloneable { private static final long serialVersionUID = 1; private static final String VALUE = "!!VALUE_][!!"; private static final String BLOCK = "[[!"; private static final String END_BLOCK = "!]]"; ListedHashTree propTree; public ConfigurationTree() { propTree = new ListedHashTree(); } public ConfigurationTree(Reader r) throws IOException { propTree = fromXML(r).propTree; } public ConfigurationTree(String value) { propTree = new ListedHashTree(); setValue(value); } public ConfigurationTree(ListedHashTree data) { propTree = data; } public ConfigurationTree(ListedHashTree data, String value) { propTree = data; setValue(value); } /** * @param keys */ public void add(Collection keys) { propTree.add(keys); } /** * @param treePath * @param values */ public void add(Collection treePath, Collection values) { propTree.add(treePath, values); } /** * @param treePath * @param value * @return */ public ConfigurationTree add(Collection treePath, String value) { return makeSubtree((ListedHashTree) propTree.add(treePath, value)); } /** * @param treePath * @param values */ public void add(Collection treePath, String[] values) { propTree.add(treePath, values); } /** * @param newTree */ public void add(ConfigurationTree newTree) { propTree.add(newTree.propTree); } /** * @param key * @return */ public ConfigurationTree add(String key) { String[] keys = getPath(key); ListedHashTree tree = propTree; for (int i = 0; i < keys.length; i++) { tree = (ListedHashTree) tree.add(keys[i]); } return makeSubtree(tree); } public ConfigurationTree addRaw(String key, String value) { ListedHashTree tree = (ListedHashTree) propTree.add(key, value); return makeSubtree(tree); } public ConfigurationTree addRaw(String key) { ListedHashTree tree = (ListedHashTree) propTree.add(key); return makeSubtree(tree); } /** * @param key * @param values */ public void add(String key, Collection values) { propTree.add(getPath(key), values); } /** * @param key * @param subTree */ public void add(String key, ConfigurationTree subTree) { propTree.getTree(getPath(key)).add(subTree.propTree); } /** * @param key * @param value * @return */ public ConfigurationTree add(String key, String value) { return makeSubtree((ListedHashTree) propTree.add(getPath(key), value)); } public Properties getAsProperties(String key) { return getAsProperties(getTree(key)); } public Properties getAsProperties() { return getAsProperties(this); } protected Properties getAsProperties(ConfigurationTree tree) { Properties props = new Properties(); if (tree == null) return props; String[] propNames = tree.getPropertyNames(); if (propNames == null) return props; for (int i = 0; i < propNames.length; i++) { if (tree.getProperty(propNames[i]) != null) props.setProperty(propNames[i], tree.getProperty(propNames[i])); } return props; } /** * @param key * @param values */ public void add(String key, String[] values) { propTree.add(getPath(key), values); } /** * @param keys */ public void add(String[] keys) { propTree.add(keys); } /** * @param treePath * @param values */ public void add(String[] treePath, Collection values) { propTree.add(treePath, values); } /** * @param treePath * @param value * @return */ public ConfigurationTree add(String[] treePath, String value) { return makeSubtree((ListedHashTree) propTree.add(treePath, value)); } /** * @param treePath * @param values */ public void add(String[] treePath, String[] values) { propTree.add(treePath, values); } public void add(Properties props) { Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); add(key, props.getProperty(key)); } } /** * @param treePath * @return */ protected ConfigurationTree addTreePath(Collection treePath) { return makeSubtree((ListedHashTree) propTree.addTreePath(treePath)); } /** * */ public void clear() { propTree.clear(); } /** * @param o * @return */ public boolean containsKey(String o) { return propTree.getTree(getPath(o)) != null; } /** * @param value * @return */ public boolean containsValue(String value) { return propTree.getTree(getPath(value)) != null; } protected String[] getPath(String key) { if (key != null) { //JDK 1.4 String[] keys = key.split("/"); String[] keys = JOrphanUtils.split(key,"/"); return keys; } return new String[0]; } public String getProperty(String key, String def) { return getProperty(getPath(key), def); } /** * @param key * @return */ public String getProperty(String key) { return getProperty(getPath(key), null); } public String getProperty(String[] keys, String def) { HashTree subTree = propTree.getTree(keys); if (subTree != null) { if (subTree.list() == null || subTree.list().size() == 0) { return def; } else if (subTree.list().size() == 1) { return (String) subTree.getArray()[0]; } else { return def; } } else { return def; } } public String getProperty(String[] keys) { return getProperty(keys, null); } /** * @return */ public String[] getPropertyNames() { return convertArray(propTree.getArray()); } /** * @param vals * @return */ private String[] convertArray(Object[] vals) { if (vals != null) { String[] props = new String[vals.length]; for (int i = 0; i < vals.length; i++) props[i] = (String) vals[i]; return props; } return null; } /** * @param treePath * @return */ public String[] getPropertyNames(Collection treePath) { return convertArray(propTree.getArray(treePath)); } /** * @param key * @return */ public String[] getPropertyNames(String key) { return convertArray(propTree.getArray(getPath(key))); } /** * @param treePath * @return */ public String[] getPropertyNames(String[] treePath) { return convertArray(propTree.getArray(treePath)); } /** * @param treePath * @return */ public ConfigurationTree getTree(Collection treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @param key * @return */ public ConfigurationTree getTree(String key) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(getPath(key)); return makeSubtree(subTree); } /** * @param treePath * @return */ public ConfigurationTree getTree(String[] treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @param subTree * @return */ private ConfigurationTree makeSubtree(ListedHashTree subTree) { if (subTree != null) return new ConfigurationTree(subTree); else return null; } /** * @param treePath * @return */ protected ConfigurationTree getTreePath(Collection treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @return */ public boolean isEmpty() { return propTree.isEmpty(); } /** * @return */ public Collection listPropertyNames() { return propTree.list(); } /** * @param treePath * @return */ public Collection listPropertyNames(Collection treePath) { return propTree.list(treePath); } /** * @param key * @return */ public Collection listPropertyNames(String key) { return propTree.list(getPath(key)); } /** * @param treePath * @return */ public Collection listPropertyNames(String[] treePath) { return propTree.list(treePath); } /** * @param key * @param value * @return */ public String put(String key, String value) { propTree.add(getPath(key), value); return value; } /** * @param map */ public void putAll(Map map) { propTree.putAll(map); } /** * @param key * @return */ public String remove(String key) { //JDK 1.4 String[] keys = key.split("/"); String[] keys = JOrphanUtils.split(key,"/"); String prop = null; HashTree tree = propTree; for (int i = 0; i < keys.length && tree != null; i++) { if ((i + 1) == keys.length) { tree = (HashTree) tree.remove(keys[i]); if (tree.list() != null && tree.list().size() == 1) { prop = (String) tree.getArray()[0]; } } else { tree = tree.getTree(keys[i]); } } return prop; } /** * @param currentKey * @param newKey */ public void replace(String currentKey, String newKey) { String[] currentKeys = getPath(currentKey); String[] newKeys = getPath(newKey); ListedHashTree tree = propTree; if (currentKeys.length == newKeys.length) { for (int i = 0; i < currentKeys.length; i++) { tree.replace(currentKeys[i], newKeys[i]); tree = (ListedHashTree) tree.getTree(newKeys[i]); } } } /** * @param key * @return */ public ConfigurationTree search(String key) { return makeSubtree((ListedHashTree) propTree.search(key)); } /** * @param values */ public void setProperty(Collection values) { propTree.set(values); } /** * @param treePath * @param values */ public void setProperty(Collection treePath, Collection values) { propTree.set(treePath, values); } /** * @param treePath * @param values */ public void setProperty(Collection treePath, String[] values) { propTree.set(treePath, values); } /** * @param key * @param values */ public void setProperty(String key, Collection values) { propTree.set(getPath(key), values); } /** * @param key * @param t */ public void setProperty(String key, ConfigurationTree t) { String[] keys = getPath(key); ListedHashTree tree = (ListedHashTree) propTree.getTree(keys); if (tree != null) { tree.clear(); tree.add(t.propTree); } else { propTree.add(keys); propTree.getTree(keys).add(t.propTree); } } /** * @param key * @param value */ public void setProperty(String key, String value) { ListedHashTree tree = (ListedHashTree) propTree.getTree(getPath(key)); if (tree != null) { tree.clear(); tree.add(value); } else { propTree.add(getPath(key), value); } } /** * @param key * @param values */ public void setProperty(String key, String[] values) { propTree.set(getPath(key), values); } /** * @param treePath * @param values */ public void setProperty(String[] treePath, Collection values) { propTree.set(treePath, values); } /** * @param treePath * @param values */ public void setProperty(String[] treePath, String[] values) { propTree.set(treePath, values); } /** * @return */ public int size() { return propTree.size(); } /** * @param visitor */ public void traverse(HashTreeTraverser visitor) { propTree.traverse(visitor); } /* * (non-Javadoc) * * @see java.lang.Object#clone() */ protected Object clone() throws CloneNotSupportedException { ConfigurationTree config = new ConfigurationTree(); config.propTree = (ListedHashTree) propTree.clone(); return config; } protected void getSpaces(int level, Writer buf) throws IOException { for (int i = 0; i < level; i++) buf.write(" "); } public String toString() { StringWriter buf = new StringWriter(); try { toXML(buf); } catch (IOException e) { // this can't happen } return buf.toString(); } public static ConfigurationTree fromXML(Reader buf) throws IOException { String[] line = readLine(buf, null); ConfigurationTree tree = null; int nameIndex = line[0].indexOf("{"); if (nameIndex > 0) { tree = new ConfigurationTree(line[0].substring(0, nameIndex).trim()); } else { tree = new ConfigurationTree(); } fromXML(buf, tree, line); return tree; } /** * @param buf * @param tree * @throws IOException */ protected static boolean fromXML(Reader buf, ConfigurationTree tree, String[] line) throws IOException { boolean done = false; try { //TODO BUG: readLine returns a String array - which one should be compared? while (!done && !(line = readLine(buf, line)).equals("}")) { int equals = line[0].indexOf("="); if (line[0].endsWith("{")) { line[0] = line[0].substring(0, line[0].length() - 1).trim(); equals = line[0].indexOf("="); if (equals > -1) { ConfigurationTree newTree = tree.add(line[0].substring(0, equals)); newTree.setValue(line[0].substring(equals + 1)); done = fromXML(buf, newTree, line); } else { done = fromXML(buf, tree.add(line[0]), line); } } else if (equals > -1) { String key = line[0].substring(0, equals); if ((equals + 1) < line[0].length()) tree.addRaw(key, line[0].substring(equals + 1)); else tree.addRaw(key); } else if (line[0].equals("}")) { return false; } else if (line[0].length() > 0) { tree.addRaw(line[0]); } } } catch (IOException e) { if (e.getMessage().equals("End of File")) { return true; } else throw e; } return false; } /** * @param buf * @throws IOException */ protected static String[] readLine(Reader buf, String[] extra) throws IOException { if (extra == null) { extra = new String[2]; } if (extra[1] != null && extra[1].length() > 0) { extra[0] = extra[1]; extra[1] = null; return extra; } StringBuffer line = new StringBuffer(); int c = buf.read(); while ((c != -1) && ((char) c != '\n') && ((char) c != '\r') && ((char) c != '}') && ((char) c != '{')) { line.append((char) c); c = buf.read(); } if (c == -1) throw new IOException("End of File"); if (((char) c == '}')) extra[1] = String.valueOf((char) c); else if (((char) c) == '{') { line.append('{'); } extra[0] = line.toString().trim(); if (extra[0].endsWith(BLOCK)) { extra[0] = extra[0].substring(0, extra[0].length() - BLOCK.length()) + readBlock(buf); } return extra; } protected static String readBlock(Reader buf) throws IOException { StringBuffer line = new StringBuffer(); int c = buf.read(); line.append((char) c); while (!line.toString().endsWith(END_BLOCK)) { c = buf.read(); line.append((char) c); } return line.toString().substring(0, line.length() - END_BLOCK.length()).trim(); } public void toXML(Writer buf) throws IOException { if (getValue() != null) { buf.write(getValue()); buf.write(" {\n"); } else buf.write("{\n"); int level = 1; toXML(this, level, buf); buf.write("}"); } protected boolean isLeaf(String key) { ConfigurationTree tree = getTree(key); String[] vals = tree.getPropertyNames(); if (vals == null || vals.length == 0 || (vals.length == 1 && (tree.listPropertyNames(vals[0]) == null || tree.listPropertyNames(vals[0]) .size() == 0))) { return true; } return false; } protected void toXML(ConfigurationTree tree, int level, Writer buf) throws IOException { String[] entries = tree.getPropertyNames(); for (int i = 0; i < entries.length; i++) { if (!VALUE.equals(entries[i])) { if (tree.listPropertyNames(entries[i]) == null || tree.listPropertyNames(entries[i]).size() == 0) { getSpaces(level, buf); writeLeafValue(buf, entries[i], level); buf.write("\n"); } else if (tree.isLeaf(entries[i])) { getSpaces(level, buf); buf.write(entries[i]); buf.write("="); writeLeafValue(buf, tree.getPropertyNames(entries[i])[0], level); buf.write("\n"); } else { getSpaces(level, buf); buf.write(entries[i]); if (tree.getTree(entries[i]).getValue() != null) { buf.write("="); buf.write(tree.getTree(entries[i]).getValue()); } buf.write(" {\n"); toXML(tree.getTree(entries[i]), (level + 1), buf); getSpaces(level, buf); buf.write("}\n"); } } } } protected void writeLeafValue(Writer buf, String entry, int level) throws IOException { if (entry.indexOf('\n') > -1 || entry.indexOf('\r') > -1) { buf.write(BLOCK); buf.write("\n"); buf.write(entry.trim()); buf.write("\n"); getSpaces(level, buf); buf.write(END_BLOCK); } else { buf.write(entry); } } /** * @return Returns the value. */ public String getValue() { return getProperty(VALUE); } /** * Get the value or return the given default value if null * * @param def * @return */ public String getValueOr(String def) { String v = getValue(); if (v == null) { return def; } return v; } public String getValue(String name) { ConfigurationTree tree = getTree(getPath(name)); if (tree != null) { return tree.getValue(); } return null; } public String getValue(String key, String def) { String v = getValue(key); if (v == null) { return def; } return v; } /** * @param value * The value to set. */ public void setValue(String value) { setProperty(VALUE, value); } public void setValue(String name, String value) { ConfigurationTree tree = getTree(getPath(name)); if (tree != null) { tree.setValue(value); } else { add(name).setValue(value); } } }
src/jorphan/org/apache/jorphan/collections/ConfigurationTree.java
/* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * Created on Feb 8, 2005 * */ package org.apache.jorphan.collections; import java.io.IOException; import java.io.Reader; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Properties; import org.apache.jorphan.util.JOrphanUtils; /** * @author mike * */ public class ConfigurationTree implements Serializable, Cloneable { private static final long serialVersionUID = 1; private static final String VALUE = "!!VALUE_][!!"; private static final String BLOCK = "[[!"; private static final String END_BLOCK = "!]]"; ListedHashTree propTree; public ConfigurationTree() { propTree = new ListedHashTree(); } public ConfigurationTree(Reader r) throws IOException { propTree = fromXML(r).propTree; } public ConfigurationTree(String value) { propTree = new ListedHashTree(); setValue(value); } public ConfigurationTree(ListedHashTree data) { propTree = data; } public ConfigurationTree(ListedHashTree data, String value) { propTree = data; setValue(value); } /** * @param keys */ public void add(Collection keys) { propTree.add(keys); } /** * @param treePath * @param values */ public void add(Collection treePath, Collection values) { propTree.add(treePath, values); } /** * @param treePath * @param value * @return */ public ConfigurationTree add(Collection treePath, String value) { return makeSubtree((ListedHashTree) propTree.add(treePath, value)); } /** * @param treePath * @param values */ public void add(Collection treePath, String[] values) { propTree.add(treePath, values); } /** * @param newTree */ public void add(ConfigurationTree newTree) { propTree.add(newTree.propTree); } /** * @param key * @return */ public ConfigurationTree add(String key) { String[] keys = getPath(key); ListedHashTree tree = propTree; for (int i = 0; i < keys.length; i++) { tree = (ListedHashTree) tree.add(keys[i]); } return makeSubtree(tree); } public ConfigurationTree addRaw(String key, String value) { ListedHashTree tree = (ListedHashTree) propTree.add(key, value); return makeSubtree(tree); } public ConfigurationTree addRaw(String key) { ListedHashTree tree = (ListedHashTree) propTree.add(key); return makeSubtree(tree); } /** * @param key * @param values */ public void add(String key, Collection values) { propTree.add(getPath(key), values); } /** * @param key * @param subTree */ public void add(String key, ConfigurationTree subTree) { propTree.getTree(getPath(key)).add(subTree.propTree); } /** * @param key * @param value * @return */ public ConfigurationTree add(String key, String value) { return makeSubtree((ListedHashTree) propTree.add(getPath(key), value)); } public Properties getAsProperties(String key) { return getAsProperties(getTree(key)); } public Properties getAsProperties() { return getAsProperties(this); } protected Properties getAsProperties(ConfigurationTree tree) { Properties props = new Properties(); if (tree == null) return props; String[] propNames = tree.getPropertyNames(); if (propNames == null) return props; for (int i = 0; i < propNames.length; i++) { if (tree.getProperty(propNames[i]) != null) props.setProperty(propNames[i], tree.getProperty(propNames[i])); } return props; } /** * @param key * @param values */ public void add(String key, String[] values) { propTree.add(getPath(key), values); } /** * @param keys */ public void add(String[] keys) { propTree.add(keys); } /** * @param treePath * @param values */ public void add(String[] treePath, Collection values) { propTree.add(treePath, values); } /** * @param treePath * @param value * @return */ public ConfigurationTree add(String[] treePath, String value) { return makeSubtree((ListedHashTree) propTree.add(treePath, value)); } /** * @param treePath * @param values */ public void add(String[] treePath, String[] values) { propTree.add(treePath, values); } public void add(Properties props) { Iterator iter = props.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); add(key, props.getProperty(key)); } } /** * @param treePath * @return */ protected ConfigurationTree addTreePath(Collection treePath) { return makeSubtree((ListedHashTree) propTree.addTreePath(treePath)); } /** * */ public void clear() { propTree.clear(); } /** * @param o * @return */ public boolean containsKey(String o) { return propTree.getTree(getPath(o)) != null; } /** * @param value * @return */ public boolean containsValue(String value) { return propTree.getTree(getPath(value)) != null; } protected String[] getPath(String key) { if (key != null) { //JDK 1.4 String[] keys = key.split("/"); String[] keys = JOrphanUtils.split(key,"/"); return keys; } return new String[0]; } public String getProperty(String key, String def) { return getProperty(getPath(key), def); } /** * @param key * @return */ public String getProperty(String key) { return getProperty(getPath(key), null); } public String getProperty(String[] keys, String def) { HashTree subTree = propTree.getTree(keys); if (subTree != null) { if (subTree.list() == null || subTree.list().size() == 0) { return def; } else if (subTree.list().size() == 1) { return (String) subTree.getArray()[0]; } else { return def; } } else { return def; } } public String getProperty(String[] keys) { return getProperty(keys, null); } /** * @return */ public String[] getPropertyNames() { return convertArray(propTree.getArray()); } /** * @param vals * @return */ private String[] convertArray(Object[] vals) { if (vals != null) { String[] props = new String[vals.length]; for (int i = 0; i < vals.length; i++) props[i] = (String) vals[i]; return props; } return null; } /** * @param treePath * @return */ public String[] getPropertyNames(Collection treePath) { return convertArray(propTree.getArray(treePath)); } /** * @param key * @return */ public String[] getPropertyNames(String key) { return convertArray(propTree.getArray(getPath(key))); } /** * @param treePath * @return */ public String[] getPropertyNames(String[] treePath) { return convertArray(propTree.getArray(treePath)); } /** * @param treePath * @return */ public ConfigurationTree getTree(Collection treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @param key * @return */ public ConfigurationTree getTree(String key) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(getPath(key)); return makeSubtree(subTree); } /** * @param treePath * @return */ public ConfigurationTree getTree(String[] treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @param subTree * @return */ private ConfigurationTree makeSubtree(ListedHashTree subTree) { if (subTree != null) return new ConfigurationTree(subTree); else return null; } /** * @param treePath * @return */ protected ConfigurationTree getTreePath(Collection treePath) { ListedHashTree subTree = (ListedHashTree) propTree.getTree(treePath); return makeSubtree(subTree); } /** * @return */ public boolean isEmpty() { return propTree.isEmpty(); } /** * @return */ public Collection listPropertyNames() { return propTree.list(); } /** * @param treePath * @return */ public Collection listPropertyNames(Collection treePath) { return propTree.list(treePath); } /** * @param key * @return */ public Collection listPropertyNames(String key) { return propTree.list(getPath(key)); } /** * @param treePath * @return */ public Collection listPropertyNames(String[] treePath) { return propTree.list(treePath); } /** * @param key * @param value * @return */ public String put(String key, String value) { propTree.add(getPath(key), value); return value; } /** * @param map */ public void putAll(Map map) { propTree.putAll(map); } /** * @param key * @return */ public String remove(String key) { //JDK 1.4 String[] keys = key.split("/"); String[] keys = JOrphanUtils.split(key,"/"); String prop = null; HashTree tree = propTree; for (int i = 0; i < keys.length && tree != null; i++) { if ((i + 1) == keys.length) { tree = (HashTree) tree.remove(keys[i]); if (tree.list() != null && tree.list().size() == 1) { prop = (String) tree.getArray()[0]; } } else { tree = tree.getTree(keys[i]); } } return prop; } /** * @param currentKey * @param newKey */ public void replace(String currentKey, String newKey) { String[] currentKeys = getPath(currentKey); String[] newKeys = getPath(newKey); ListedHashTree tree = propTree; if (currentKeys.length == newKeys.length) { for (int i = 0; i < currentKeys.length; i++) { tree.replace(currentKeys[i], newKeys[i]); tree = (ListedHashTree) tree.getTree(newKeys[i]); } } } /** * @param key * @return */ public ConfigurationTree search(String key) { return makeSubtree((ListedHashTree) propTree.search(key)); } /** * @param values */ public void setProperty(Collection values) { propTree.set(values); } /** * @param treePath * @param values */ public void setProperty(Collection treePath, Collection values) { propTree.set(treePath, values); } /** * @param treePath * @param values */ public void setProperty(Collection treePath, String[] values) { propTree.set(treePath, values); } /** * @param key * @param values */ public void setProperty(String key, Collection values) { propTree.set(getPath(key), values); } /** * @param key * @param t */ public void setProperty(String key, ConfigurationTree t) { String[] keys = getPath(key); ListedHashTree tree = (ListedHashTree) propTree.getTree(keys); if (tree != null) { tree.clear(); tree.add(t.propTree); } else { propTree.add(keys); propTree.getTree(keys).add(t.propTree); } } /** * @param key * @param value */ public void setProperty(String key, String value) { ListedHashTree tree = (ListedHashTree) propTree.getTree(getPath(key)); if (tree != null) { tree.clear(); tree.add(value); } else { propTree.add(getPath(key), value); } } /** * @param key * @param values */ public void setProperty(String key, String[] values) { propTree.set(getPath(key), values); } /** * @param treePath * @param values */ public void setProperty(String[] treePath, Collection values) { propTree.set(treePath, values); } /** * @param treePath * @param values */ public void setProperty(String[] treePath, String[] values) { propTree.set(treePath, values); } /** * @return */ public int size() { return propTree.size(); } /** * @param visitor */ public void traverse(HashTreeTraverser visitor) { propTree.traverse(visitor); } /* * (non-Javadoc) * * @see java.lang.Object#clone() */ protected Object clone() throws CloneNotSupportedException { ConfigurationTree config = new ConfigurationTree(); config.propTree = (ListedHashTree) propTree.clone(); return config; } protected void getSpaces(int level, Writer buf) throws IOException { for (int i = 0; i < level; i++) buf.write(" "); } public String toString() { StringWriter buf = new StringWriter(); try { toXML(buf); } catch (IOException e) { // this can't happen } return buf.toString(); } public static ConfigurationTree fromXML(Reader buf) throws IOException { String[] line = readLine(buf, null); ConfigurationTree tree = null; int nameIndex = line[0].indexOf("{"); if (nameIndex > 0) { tree = new ConfigurationTree(line[0].substring(0, nameIndex).trim()); } else { tree = new ConfigurationTree(); } fromXML(buf, tree, line); return tree; } /** * @param buf * @param tree * @throws IOException */ protected static boolean fromXML(Reader buf, ConfigurationTree tree, String[] line) throws IOException { boolean done = false; try { while (!done && !(line = readLine(buf, line)).equals("}")) { int equals = line[0].indexOf("="); if (line[0].endsWith("{")) { line[0] = line[0].substring(0, line[0].length() - 1).trim(); equals = line[0].indexOf("="); if (equals > -1) { ConfigurationTree newTree = tree.add(line[0].substring(0, equals)); newTree.setValue(line[0].substring(equals + 1)); done = fromXML(buf, newTree, line); } else { done = fromXML(buf, tree.add(line[0]), line); } } else if (equals > -1) { String key = line[0].substring(0, equals); if ((equals + 1) < line[0].length()) tree.addRaw(key, line[0].substring(equals + 1)); else tree.addRaw(key); } else if (line[0].equals("}")) { return false; } else if (line[0].length() > 0) { tree.addRaw(line[0]); } } } catch (IOException e) { if (e.getMessage().equals("End of File")) { return true; } else throw e; } return false; } /** * @param buf * @throws IOException */ protected static String[] readLine(Reader buf, String[] extra) throws IOException { if (extra == null) { extra = new String[2]; } if (extra[1] != null && extra[1].length() > 0) { extra[0] = extra[1]; extra[1] = null; return extra; } StringBuffer line = new StringBuffer(); int c = buf.read(); while ((c != -1) && ((char) c != '\n') && ((char) c != '\r') && ((char) c != '}') && ((char) c != '{')) { line.append((char) c); c = buf.read(); } if (c == -1) throw new IOException("End of File"); if (((char) c == '}')) extra[1] = String.valueOf((char) c); else if (((char) c) == '{') { line.append('{'); } extra[0] = line.toString().trim(); if (extra[0].endsWith(BLOCK)) { extra[0] = extra[0].substring(0, extra[0].length() - BLOCK.length()) + readBlock(buf); } return extra; } protected static String readBlock(Reader buf) throws IOException { StringBuffer line = new StringBuffer(); int c = buf.read(); line.append((char) c); while (!line.toString().endsWith(END_BLOCK)) { c = buf.read(); line.append((char) c); } return line.toString().substring(0, line.length() - END_BLOCK.length()).trim(); } public void toXML(Writer buf) throws IOException { if (getValue() != null) { buf.write(getValue()); buf.write(" {\n"); } else buf.write("{\n"); int level = 1; toXML(this, level, buf); buf.write("}"); } protected boolean isLeaf(String key) { ConfigurationTree tree = getTree(key); String[] vals = tree.getPropertyNames(); if (vals == null || vals.length == 0 || (vals.length == 1 && (tree.listPropertyNames(vals[0]) == null || tree.listPropertyNames(vals[0]) .size() == 0))) { return true; } return false; } protected void toXML(ConfigurationTree tree, int level, Writer buf) throws IOException { String[] entries = tree.getPropertyNames(); for (int i = 0; i < entries.length; i++) { if (!VALUE.equals(entries[i])) { if (tree.listPropertyNames(entries[i]) == null || tree.listPropertyNames(entries[i]).size() == 0) { getSpaces(level, buf); writeLeafValue(buf, entries[i], level); buf.write("\n"); } else if (tree.isLeaf(entries[i])) { getSpaces(level, buf); buf.write(entries[i]); buf.write("="); writeLeafValue(buf, tree.getPropertyNames(entries[i])[0], level); buf.write("\n"); } else { getSpaces(level, buf); buf.write(entries[i]); if (tree.getTree(entries[i]).getValue() != null) { buf.write("="); buf.write(tree.getTree(entries[i]).getValue()); } buf.write(" {\n"); toXML(tree.getTree(entries[i]), (level + 1), buf); getSpaces(level, buf); buf.write("}\n"); } } } } protected void writeLeafValue(Writer buf, String entry, int level) throws IOException { if (entry.indexOf('\n') > -1 || entry.indexOf('\r') > -1) { buf.write(BLOCK); buf.write("\n"); buf.write(entry.trim()); buf.write("\n"); getSpaces(level, buf); buf.write(END_BLOCK); } else { buf.write(entry); } } /** * @return Returns the value. */ public String getValue() { return getProperty(VALUE); } /** * Get the value or return the given default value if null * * @param def * @return */ public String getValueOr(String def) { String v = getValue(); if (v == null) { return def; } return v; } public String getValue(String name) { ConfigurationTree tree = getTree(getPath(name)); if (tree != null) { return tree.getValue(); } return null; } public String getValue(String key, String def) { String v = getValue(key); if (v == null) { return def; } return v; } /** * @param value * The value to set. */ public void setValue(String value) { setProperty(VALUE, value); } public void setValue(String name, String value) { ConfigurationTree tree = getTree(getPath(name)); if (tree != null) { tree.setValue(value); } else { add(name).setValue(value); } } }
Flag bug git-svn-id: 52ad764cdf1b64a6e804f4e5ad13917d3c4b2253@408547 13f79535-47bb-0310-9956-ffa450edef68
src/jorphan/org/apache/jorphan/collections/ConfigurationTree.java
Flag bug
Java
apache-2.0
8e007773c9f2ab1102bf02400eedea11aaace7c8
0
TheNephilim88/andlytics,AndyScherzinger/andlytics,AndyScherzinger/andlytics,willlunniss/andlytics,TheNephilim88/andlytics,willlunniss/andlytics
package com.github.andlyticsproject.adsense; import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.util.Log; import com.github.andlyticsproject.AndlyticsApp; import com.github.andlyticsproject.ContentAdapter; import com.github.andlyticsproject.Preferences.Timeframe; import com.github.andlyticsproject.model.AdmobStats; import com.github.andlyticsproject.util.Utils; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.adsense.AdSense; import com.google.api.services.adsense.AdSense.Accounts.Reports.Generate; import com.google.api.services.adsense.AdSenseScopes; import com.google.api.services.adsense.model.Account; import com.google.api.services.adsense.model.Accounts; import com.google.api.services.adsense.model.AdClients; import com.google.api.services.adsense.model.AdUnit; import com.google.api.services.adsense.model.AdUnits; import com.google.api.services.adsense.model.AdsenseReportsGenerateResponse; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @SuppressLint("SimpleDateFormat") public class AdSenseClient { private static final String TAG = AdSenseClient.class.getSimpleName(); private static final boolean DEBUG = false; private static final DateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); private static final String APPLICATION_NAME = "Andlytics/2.6.0"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final int MAX_LIST_PAGE_SIZE = 50; private static final long MILLIES_IN_DAY = 60 * 60 * 24 * 1000L; private AdSenseClient() { } public static void foregroundSyncStats(Context context, String admobAccount, List<String> adUnits) throws Exception { try { AdSense adsense = createForegroundSyncClient(context, admobAccount); syncStats(context, adsense, adUnits); } catch (GoogleJsonResponseException e) { List<ErrorInfo> errors = e.getDetails().getErrors(); for (ErrorInfo err : errors) { if ("dailyLimitExceeded".equals(err.getReason())) { // ignore Log.w(TAG, "Quota exeeded: " + e.toString()); return; } } throw e; } } private static AdSense createForegroundSyncClient(Context context, String admobAccount) { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(AdSenseScopes.ADSENSE_READONLY)); credential.setSelectedAccountName(admobAccount); AdSense adsense = new AdSense.Builder(AndroidHttp.newCompatibleTransport(), JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); return adsense; } public static void backgroundSyncStats(Context context, String admobAccount, List<String> adUnits, Bundle extras, String authority, Bundle syncBundle) throws Exception { try { AdSense adsense = createBackgroundSyncClient(context, admobAccount, extras, authority, syncBundle); syncStats(context, adsense, adUnits); } catch (GoogleJsonResponseException e) { List<ErrorInfo> errors = e.getDetails().getErrors(); for (ErrorInfo err : errors) { if ("dailyLimitExceeded".equals(err.getReason())) { // ignore Log.w(TAG, "Quota exeeded: " + e.toString()); return; } } throw e; } } private static void syncStats(Context context, AdSense adsense, List<String> adUnits) throws Exception { Calendar[] syncPeriod = getSyncPeriod(adUnits); boolean bulkInsert = false; Date startDate = syncPeriod[0].getTime(); Date endDate = syncPeriod[1].getTime(); if ((endDate.getTime() - startDate.getTime()) > 7 * MILLIES_IN_DAY) { bulkInsert = true; } Account account = getFirstAccount(adsense); if (account == null) { return; } // we assume there is only one(?) String adClientId = getClientId(adsense, account); if (adClientId == null) { // XXX throw? return; } List<AdmobStats> result = generateReport(adsense, account, adClientId, startDate, endDate); updateStats(context, bulkInsert, result); } private static Calendar[] getSyncPeriod(List<String> adUnits) { Calendar startDateCal = null; Calendar endDateCal = Calendar.getInstance(); endDateCal.add(Calendar.DAY_OF_YEAR, 1); for (String adUnit : adUnits) { // read db for required sync period ContentAdapter contentAdapter = ContentAdapter.getInstance(AndlyticsApp.getInstance()); List<AdmobStats> admobStats = contentAdapter.getAdmobStats(adUnit, Timeframe.LATEST_VALUE).getStats(); if (admobStats.size() > 0) { // found previous sync, no bulk import Date startDate = admobStats.get(0).getDate(); startDateCal = Calendar.getInstance(); startDateCal.setTime(startDate); startDateCal.add(Calendar.DAY_OF_YEAR, -4); } else { startDateCal = Calendar.getInstance(); startDateCal.setTime(endDateCal.getTime()); startDateCal.add(Calendar.MONTH, -6); } } return new Calendar[] { startDateCal, endDateCal }; } private static String getClientId(AdSense adsense, Account account) throws IOException { AdClients adClients = adsense.accounts().adclients().list(account.getId()) .setMaxResults(MAX_LIST_PAGE_SIZE).setPageToken(null).execute(); if (adClients.getItems() == null || adClients.getItems().isEmpty()) { return null; } // we assume there is only one(?) return adClients.getItems().get(0).getId(); } private static Account getFirstAccount(AdSense adsense) throws IOException { Accounts accounts = adsense.accounts().list().execute(); if (accounts.isEmpty()) { return null; } return accounts.getItems().get(0); } private static void updateStats(Context context, boolean bulkInsert, List<AdmobStats> result) { ContentAdapter contentAdapter = ContentAdapter.getInstance((Application) context .getApplicationContext()); if (bulkInsert) { if (result.size() > 6) { // insert first results single to avoid manual triggered doubles List<AdmobStats> subList1 = result.subList(0, 5); for (AdmobStats admob : subList1) { contentAdapter.insertOrUpdateAdmobStats(admob); } List<AdmobStats> subList2 = result.subList(5, result.size()); contentAdapter.bulkInsertAdmobStats(subList2); } else { contentAdapter.bulkInsertAdmobStats(result); } } else { for (AdmobStats admob : result) { contentAdapter.insertOrUpdateAdmobStats(admob); } } } private static AdSense createBackgroundSyncClient(Context context, String admobAccount, Bundle extras, String authority, Bundle syncBundle) { BackgroundGoogleAccountCredential credential = BackgroundGoogleAccountCredential .usingOAuth2(context, Collections.singleton(AdSenseScopes.ADSENSE_READONLY), extras, authority, syncBundle); credential.setSelectedAccountName(admobAccount); AdSense adsense = new AdSense.Builder(AndroidHttp.newCompatibleTransport(), JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); return adsense; } private static List<AdmobStats> generateReport(AdSense adsense, Account account, String adClientId, Date startDate, Date endDate) throws IOException, ParseException { String startDateStr = DATE_FORMATTER.format(startDate); String endDateStr = DATE_FORMATTER.format(endDate); Generate request = adsense.accounts().reports() .generate(account.getId(), startDateStr, endDateStr); // Specify the desired ad client using a filter. request.setFilter(Arrays.asList("AD_CLIENT_ID==" + escapeFilterParameter(adClientId))); request.setDimension(Arrays.asList("DATE", "AD_UNIT_ID", "AD_UNIT_CODE", "AD_UNIT_NAME")); request.setMetric(Arrays.asList("PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "CLICKS", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS", "INDIVIDUAL_AD_IMPRESSIONS")); // Sort by ascending date. request.setSort(Arrays.asList("+DATE")); request.setUseTimezoneReporting(true); AdsenseReportsGenerateResponse response = request.execute(); List<AdmobStats> result = new ArrayList<AdmobStats>(); if (response.getRows() == null || response.getRows().isEmpty()) { Log.d(TAG, "AdSense API returned no rows."); } if (DEBUG) { StringBuilder buff = new StringBuilder(); for (AdsenseReportsGenerateResponse.Headers header : response.getHeaders()) { buff.append(String.format("%25s", header.getName())); if (header.getCurrency() != null) { buff.append(" " + header.getCurrency()); } } Log.d(TAG, ""); } String currencyCode = null; AdsenseReportsGenerateResponse.Headers revenueHeader = response.getHeaders().get(11); if (revenueHeader != null && revenueHeader.getCurrency() != null) { currencyCode = revenueHeader.getCurrency(); } for (List<String> row : response.getRows()) { if (DEBUG) { StringBuilder buff = new StringBuilder(); for (String column : row) { buff.append(String.format("%25s", column)); } Log.d(TAG, buff.toString()); } AdmobStats admob = new AdmobStats(); admob.setDate(DATE_FORMATTER.parse(row.get(0))); admob.setSiteId(row.get(1)); admob.setRequests(Utils.tryParseInt(row.get(5))); admob.setFillRate(Utils.tryParseFloat(row.get(6))); admob.setClicks(Utils.tryParseInt(row.get(7))); admob.setCtr(Utils.tryParseFloat(row.get(8))); admob.setCpcRevenue(Utils.tryParseFloat(row.get(9))); admob.setEcpm(Utils.tryParseFloat(row.get(10))); admob.setRevenue(Utils.tryParseFloat(row.get(11))); admob.setImpressions(Utils.tryParseInt(row.get(12))); admob.setCurrencyCode(currencyCode); result.add(admob); } return result; } public static String escapeFilterParameter(String parameter) { return parameter.replace("\\", "\\\\").replace(",", "\\,"); } public static Map<String, String> getAdUnits(Context context, String admobAccount) throws IOException { AdSense adsense = createForegroundSyncClient(context, admobAccount); Account account = getFirstAccount(adsense); if (account == null) { return new HashMap<String, String>(); } String adClientId = getClientId(adsense, account); if (adClientId == null) { // XXX throw? return new HashMap<String, String>(); } AdUnits units = adsense.accounts().adunits().list(account.getId(), adClientId) .setMaxResults(MAX_LIST_PAGE_SIZE).setPageToken(null).execute(); List<AdUnit> items = units.getItems(); // preserver order Map<String, String> result = new LinkedHashMap<String, String>(); for (AdUnit unit : items) { result.put(unit.getId(), unit.getName()); } return result; } }
src/com/github/andlyticsproject/adsense/AdSenseClient.java
package com.github.andlyticsproject.adsense; import android.annotation.SuppressLint; import android.app.Application; import android.content.Context; import android.os.Bundle; import android.util.Log; import com.github.andlyticsproject.AndlyticsApp; import com.github.andlyticsproject.ContentAdapter; import com.github.andlyticsproject.Preferences.Timeframe; import com.github.andlyticsproject.model.AdmobStats; import com.github.andlyticsproject.util.Utils; import com.google.api.client.extensions.android.http.AndroidHttp; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo; import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.adsense.AdSense; import com.google.api.services.adsense.AdSense.Accounts.Reports.Generate; import com.google.api.services.adsense.AdSenseScopes; import com.google.api.services.adsense.model.Account; import com.google.api.services.adsense.model.Accounts; import com.google.api.services.adsense.model.AdClients; import com.google.api.services.adsense.model.AdUnit; import com.google.api.services.adsense.model.AdUnits; import com.google.api.services.adsense.model.AdsenseReportsGenerateResponse; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @SuppressLint("SimpleDateFormat") public class AdSenseClient { private static final String TAG = AdSenseClient.class.getSimpleName(); private static final boolean DEBUG = false; private static final DateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd"); private static final String APPLICATION_NAME = "Andlytics/2.6.0"; private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private static final int MAX_LIST_PAGE_SIZE = 50; private static final long MILLIES_IN_DAY = 60 * 60 * 24 * 1000L; private AdSenseClient() { } public static void foregroundSyncStats(Context context, String admobAccount, List<String> adUnits) throws Exception { try { AdSense adsense = createForegroundSyncClient(context, admobAccount); syncStats(context, adsense, adUnits); } catch (GoogleJsonResponseException e) { List<ErrorInfo> errors = e.getDetails().getErrors(); for (ErrorInfo err : errors) { if ("dailyLimitExceeded".equals(err.getReason())) { // ignore Log.w(TAG, "Quota exeeded: " + e.toString()); return; } } throw e; } } private static AdSense createForegroundSyncClient(Context context, String admobAccount) { GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(context, Collections.singleton(AdSenseScopes.ADSENSE_READONLY)); credential.setSelectedAccountName(admobAccount); AdSense adsense = new AdSense.Builder(AndroidHttp.newCompatibleTransport(), JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); return adsense; } public static void backgroundSyncStats(Context context, String admobAccount, List<String> adUnits, Bundle extras, String authority, Bundle syncBundle) throws Exception { try { AdSense adsense = createBackgroundSyncClient(context, admobAccount, extras, authority, syncBundle); syncStats(context, adsense, adUnits); } catch (GoogleJsonResponseException e) { List<ErrorInfo> errors = e.getDetails().getErrors(); for (ErrorInfo err : errors) { if ("dailyLimitExceeded".equals(err.getReason())) { // ignore Log.w(TAG, "Quota exeeded: " + e.toString()); return; } } throw e; } } private static void syncStats(Context context, AdSense adsense, List<String> adUnits) throws Exception { Calendar[] syncPeriod = getSyncPeriod(adUnits); boolean bulkInsert = false; Date startDate = syncPeriod[0].getTime(); Date endDate = syncPeriod[1].getTime(); if ((endDate.getTime() - startDate.getTime()) > 7 * MILLIES_IN_DAY) { bulkInsert = true; } // we assume there is only one(?) String adClientId = getClientId(adsense); if (adClientId == null) { // XXX throw? return; } List<AdmobStats> result = generateReport(adsense, adClientId, startDate, endDate); updateStats(context, bulkInsert, result); } private static Calendar[] getSyncPeriod(List<String> adUnits) { Calendar startDateCal = null; Calendar endDateCal = Calendar.getInstance(); endDateCal.add(Calendar.DAY_OF_YEAR, 1); for (String adUnit : adUnits) { // read db for required sync period ContentAdapter contentAdapter = ContentAdapter.getInstance(AndlyticsApp.getInstance()); List<AdmobStats> admobStats = contentAdapter.getAdmobStats(adUnit, Timeframe.LATEST_VALUE).getStats(); if (admobStats.size() > 0) { // found previous sync, no bulk import Date startDate = admobStats.get(0).getDate(); startDateCal = Calendar.getInstance(); startDateCal.setTime(startDate); startDateCal.add(Calendar.DAY_OF_YEAR, -4); } else { startDateCal = Calendar.getInstance(); startDateCal.setTime(endDateCal.getTime()); startDateCal.add(Calendar.MONTH, -6); } } return new Calendar[] { startDateCal, endDateCal }; } private static String getClientId(AdSense adsense) throws IOException { Account account = getFirstAccount(adsense); AdClients adClients = adsense.accounts().adclients().list(account.getId()) .setMaxResults(MAX_LIST_PAGE_SIZE).setPageToken(null).execute(); if (adClients.getItems() == null || adClients.getItems().isEmpty()) { return null; } // we assume there is only one(?) return adClients.getItems().get(0).getId(); } private static Account getFirstAccount(AdSense adsense) throws IOException { Accounts accounts = adsense.accounts().list().execute(); return accounts.getItems().get(0); } private static void updateStats(Context context, boolean bulkInsert, List<AdmobStats> result) { ContentAdapter contentAdapter = ContentAdapter.getInstance((Application) context .getApplicationContext()); if (bulkInsert) { if (result.size() > 6) { // insert first results single to avoid manual triggered doubles List<AdmobStats> subList1 = result.subList(0, 5); for (AdmobStats admob : subList1) { contentAdapter.insertOrUpdateAdmobStats(admob); } List<AdmobStats> subList2 = result.subList(5, result.size()); contentAdapter.bulkInsertAdmobStats(subList2); } else { contentAdapter.bulkInsertAdmobStats(result); } } else { for (AdmobStats admob : result) { contentAdapter.insertOrUpdateAdmobStats(admob); } } } private static AdSense createBackgroundSyncClient(Context context, String admobAccount, Bundle extras, String authority, Bundle syncBundle) { BackgroundGoogleAccountCredential credential = BackgroundGoogleAccountCredential .usingOAuth2(context, Collections.singleton(AdSenseScopes.ADSENSE_READONLY), extras, authority, syncBundle); credential.setSelectedAccountName(admobAccount); AdSense adsense = new AdSense.Builder(AndroidHttp.newCompatibleTransport(), JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build(); return adsense; } private static List<AdmobStats> generateReport(AdSense adsense, String adClientId, Date startDate, Date endDate) throws IOException, ParseException { String startDateStr = DATE_FORMATTER.format(startDate); String endDateStr = DATE_FORMATTER.format(endDate); Account account = getFirstAccount(adsense); Generate request = adsense.accounts().reports() .generate(account.getId(), startDateStr, endDateStr); // Specify the desired ad client using a filter. request.setFilter(Arrays.asList("AD_CLIENT_ID==" + escapeFilterParameter(adClientId))); request.setDimension(Arrays.asList("DATE", "AD_UNIT_ID", "AD_UNIT_CODE", "AD_UNIT_NAME")); request.setMetric(Arrays.asList("PAGE_VIEWS", "AD_REQUESTS", "AD_REQUESTS_COVERAGE", "CLICKS", "AD_REQUESTS_CTR", "COST_PER_CLICK", "AD_REQUESTS_RPM", "EARNINGS", "INDIVIDUAL_AD_IMPRESSIONS")); // Sort by ascending date. request.setSort(Arrays.asList("+DATE")); request.setUseTimezoneReporting(true); AdsenseReportsGenerateResponse response = request.execute(); List<AdmobStats> result = new ArrayList<AdmobStats>(); if (response.getRows() == null || response.getRows().isEmpty()) { Log.d(TAG, "AdSense API returned no rows."); } if (DEBUG) { StringBuilder buff = new StringBuilder(); for (AdsenseReportsGenerateResponse.Headers header : response.getHeaders()) { buff.append(String.format("%25s", header.getName())); if (header.getCurrency() != null) { buff.append(" " + header.getCurrency()); } } Log.d(TAG, ""); } String currencyCode = null; AdsenseReportsGenerateResponse.Headers revenueHeader = response.getHeaders().get(11); if (revenueHeader != null && revenueHeader.getCurrency() != null) { currencyCode = revenueHeader.getCurrency(); } for (List<String> row : response.getRows()) { if (DEBUG) { StringBuilder buff = new StringBuilder(); for (String column : row) { buff.append(String.format("%25s", column)); } Log.d(TAG, buff.toString()); } AdmobStats admob = new AdmobStats(); admob.setDate(DATE_FORMATTER.parse(row.get(0))); admob.setSiteId(row.get(1)); admob.setRequests(Utils.tryParseInt(row.get(5))); admob.setFillRate(Utils.tryParseFloat(row.get(6))); admob.setClicks(Utils.tryParseInt(row.get(7))); admob.setCtr(Utils.tryParseFloat(row.get(8))); admob.setCpcRevenue(Utils.tryParseFloat(row.get(9))); admob.setEcpm(Utils.tryParseFloat(row.get(10))); admob.setRevenue(Utils.tryParseFloat(row.get(11))); admob.setImpressions(Utils.tryParseInt(row.get(12))); admob.setCurrencyCode(currencyCode); result.add(admob); } return result; } public static String escapeFilterParameter(String parameter) { return parameter.replace("\\", "\\\\").replace(",", "\\,"); } public static Map<String, String> getAdUnits(Context context, String admobAccount) throws IOException { AdSense adsense = createForegroundSyncClient(context, admobAccount); String adClientId = getClientId(adsense); if (adClientId == null) { // XXX throw? return new HashMap<String, String>(); } Account account = getFirstAccount(adsense); AdUnits units = adsense.accounts().adunits().list(account.getId(), adClientId) .setMaxResults(MAX_LIST_PAGE_SIZE).setPageToken(null).execute(); List<AdUnit> items = units.getItems(); // preserver order Map<String, String> result = new LinkedHashMap<String, String>(); for (AdUnit unit : items) { result.put(unit.getId(), unit.getName()); } return result; } }
try to send less AdSense API requests
src/com/github/andlyticsproject/adsense/AdSenseClient.java
try to send less AdSense API requests
Java
apache-2.0
679902808cdf3a62b683a4642e72065f9fe2173d
0
irccloud/android,irccloud/android,irccloud/android,irccloud/android,irccloud/android
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android.fragment; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ListFragment; import android.support.v4.widget.DrawerLayout; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ImageSpan; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.fasterxml.jackson.databind.JsonNode; import com.irccloud.android.AsyncTaskEx; import com.irccloud.android.CollapsedEventsList; import com.irccloud.android.ColorFormatter; import com.irccloud.android.ColorScheme; import com.irccloud.android.FontAwesome; import com.irccloud.android.IRCCloudApplication; import com.irccloud.android.IRCCloudJSONObject; import com.irccloud.android.IRCCloudLinkMovementMethod; import com.irccloud.android.Ignore; import com.irccloud.android.NetworkConnection; import com.irccloud.android.OffsetLinearLayout; import com.irccloud.android.R; import com.irccloud.android.activity.BaseActivity; import com.irccloud.android.data.collection.AvatarsList; import com.irccloud.android.data.model.Avatar; import com.irccloud.android.data.model.Buffer; import com.irccloud.android.data.collection.BuffersList; import com.irccloud.android.data.model.Event; import com.irccloud.android.data.collection.EventsList; import com.irccloud.android.data.model.Server; import com.irccloud.android.fragment.BuffersListFragment.OnBufferSelectedListener; import com.squareup.leakcanary.RefWatcher; import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.TreeSet; public class MessageViewFragment extends ListFragment implements NetworkConnection.IRCEventHandler { private NetworkConnection conn; private TextView statusView; private View headerViewContainer; private View headerView; private View footerViewContainer; private TextView backlogFailed; private Button loadBacklogButton; private TextView unreadTopLabel; private TextView unreadBottomLabel; private View unreadTopView; private View unreadBottomView; private TextView highlightsTopLabel; private TextView highlightsBottomLabel; public ImageView avatar; private AvatarsList mAvatarsList = AvatarsList.getInstance(); private OffsetLinearLayout avatarContainer; public Buffer buffer; private Server server; private long earliest_eid; private long backlog_eid = 0; private boolean requestingBacklog = false; private float avgInsertTime = 0; private int newMsgs = 0; private long newMsgTime = 0; private int newHighlights = 0; private MessageViewListener mListener; private View awayView = null; private TextView awayTxt = null; private int timestamp_width = -1; private float textSize = 14.0f; private View globalMsgView = null; private TextView globalMsg = null; private ProgressBar spinner = null; private final Handler mHandler = new Handler(); private ColorScheme colorScheme = ColorScheme.getInstance(); private Typeface hackRegular; public static final int ROW_MESSAGE = 0; public static final int ROW_TIMESTAMP = 1; public static final int ROW_BACKLOGMARKER = 2; public static final int ROW_SOCKETCLOSED = 3; public static final int ROW_LASTSEENEID = 4; private static final String TYPE_TIMESTAMP = "__timestamp__"; private static final String TYPE_BACKLOGMARKER = "__backlog__"; private static final String TYPE_LASTSEENEID = "__lastseeneid__"; private MessageAdapter adapter; private long currentCollapsedEid = -1; private long lastCollapsedEid = -1; private CollapsedEventsList collapsedEvents = new CollapsedEventsList(); private int lastCollapsedDay = -1; private HashSet<Long> expandedSectionEids = new HashSet<Long>(); private RefreshTask refreshTask = null; private HeartbeatTask heartbeatTask = null; private Ignore ignore = new Ignore(); private static Timer tapTimer = null; private TimerTask tapTimerTask = null; public boolean longPressOverride = false; private LinkMovementMethodNoLongPress linkMovementMethodNoLongPress = new LinkMovementMethodNoLongPress(); public boolean ready = false; private final Object adapterLock = new Object(); public View suggestionsContainer = null; public GridView suggestions = null; private boolean pref_24hr = false; private boolean pref_seconds = false; private boolean pref_trackUnread = true; private boolean pref_timeLeft = false; private boolean pref_nickColors = false; private boolean pref_hideJoinPart = false; private boolean pref_expandJoinPart = false; private boolean pref_avatarsOff = false; private boolean pref_chatOneLine = false; private boolean pref_norealname = false; private boolean pref_compact = false; private class LinkMovementMethodNoLongPress extends IRCCloudLinkMovementMethod { @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (!longPressOverride && (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN)) { return super.onTouchEvent(widget, buffer, event); } return false; } } private class MessageAdapter extends BaseAdapter { final ArrayList<Event> data; private ListFragment ctx; private long max_eid = 0; private long min_eid = 0; private int lastDay = -1; private int lastSeenEidMarkerPosition = -1; private int currentGroupPosition = -1; private TreeSet<Integer> unseenHighlightPositions; private class ViewHolder { int type; LinearLayout lastSeenEidWrapper; LinearLayout messageContainer; LinearLayout socketClosedBar; TextView timestamp; TextView timestamp_left; TextView timestamp_right; TextView message; TextView expandable; TextView nickname; TextView realname; ImageView failed; ImageView avatar; } public MessageAdapter(ListFragment context, int capacity) { ctx = context; data = new ArrayList<>(capacity + 10); unseenHighlightPositions = new TreeSet<>(Collections.reverseOrder()); } public void clear() { max_eid = 0; min_eid = 0; lastDay = -1; lastSeenEidMarkerPosition = -1; currentGroupPosition = -1; synchronized (data) { data.clear(); } unseenHighlightPositions.clear(); avatarContainer.setVisibility(View.GONE); avatar.setTag(null); } public void clearPending() { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).reqid != -1 && data.get(i).color == colorScheme.timestampColor) { data.remove(i); i--; } } } } public void removeItem(long eid) { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).eid == eid) { data.remove(i); i--; } } } } public int getBacklogMarkerPosition() { try { synchronized (data) { for (int i = 0; i < data.size(); i++) { Event e = data.get(i); if (e != null && e.row_type == ROW_BACKLOGMARKER) { return i; } } } } catch (Exception e) { } return -1; } public int insertLastSeenEIDMarker() { if (buffer == null) return -1; synchronized (data) { if (min_eid > 0 && buffer.getLast_seen_eid() > 0 && min_eid >= buffer.getLast_seen_eid()) { lastSeenEidMarkerPosition = 0; } else { for (int i = data.size() - 1; i >= 0; i--) { if (data.get(i).eid <= buffer.getLast_seen_eid() && data.get(i).row_type != ROW_LASTSEENEID) { lastSeenEidMarkerPosition = i; break; } } if (lastSeenEidMarkerPosition > 0 && lastSeenEidMarkerPosition != data.size() - 1 && !data.get(lastSeenEidMarkerPosition).self && !data.get(lastSeenEidMarkerPosition).pending) { if (data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP) lastSeenEidMarkerPosition--; if (lastSeenEidMarkerPosition > 0) { Event e = new Event(); e.bid = buffer.getBid(); e.cid = buffer.getCid(); e.eid = buffer.getLast_seen_eid() + 1; e.type = TYPE_LASTSEENEID; e.row_type = ROW_LASTSEENEID; if(EventsList.getInstance().getEvent(buffer.getLast_seen_eid(), buffer.getBid()) != null) e.from = EventsList.getInstance().getEvent(buffer.getLast_seen_eid(), buffer.getBid()).from; e.bg_color = colorScheme.socketclosedBackgroundDrawable; addItem(e.eid, e); EventsList.getInstance().addEvent(e); for (int i = 0; i < data.size(); i++) { if (data.get(i).row_type == ROW_LASTSEENEID && data.get(i) != e) { EventsList.getInstance().deleteEvent(data.get(i).eid, buffer.getBid()); data.remove(i); } } } } else { lastSeenEidMarkerPosition = -1; } } if (lastSeenEidMarkerPosition > 0 && lastSeenEidMarkerPosition <= currentGroupPosition) currentGroupPosition++; if (lastSeenEidMarkerPosition == -1) { for (int i = data.size() - 1; i >= 0; i--) { if (data.get(i).row_type == ROW_LASTSEENEID) { lastSeenEidMarkerPosition = i; break; } } } } return lastSeenEidMarkerPosition; } public void clearLastSeenEIDMarker() { if(buffer != null) { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).row_type == ROW_LASTSEENEID) { EventsList.getInstance().deleteEvent(data.get(i).eid, buffer.getBid()); data.remove(i); } } } if (lastSeenEidMarkerPosition > 0) lastSeenEidMarkerPosition = -1; } } public int getLastSeenEIDPosition() { return lastSeenEidMarkerPosition; } public int getUnreadHighlightsAbovePosition(int pos) { int count = 0; Iterator<Integer> i = unseenHighlightPositions.iterator(); while (i.hasNext()) { Integer p = i.next(); if (p < pos) break; count++; } return unseenHighlightPositions.size() - count; } public synchronized void addItem(long eid, Event e) { synchronized (data) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(e.getTime()); int insert_pos = -1; SimpleDateFormat formatter = null; if (e.timestamp == null || e.timestamp.length() == 0) { formatter = new SimpleDateFormat("h:mm a"); if (pref_24hr) { if (pref_seconds) formatter = new SimpleDateFormat("HH:mm:ss"); else formatter = new SimpleDateFormat("HH:mm"); } else if (pref_seconds) { formatter = new SimpleDateFormat("h:mm:ss a"); } e.timestamp = formatter.format(calendar.getTime()); } e.group_eid = currentCollapsedEid; if (e.group_msg != null && e.html == null) e.html = e.group_msg; /*if(e.html != null) { e.html = ColorFormatter.irc_to_html(e.html); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server); }*/ if (e.day < 1) { e.day = calendar.get(Calendar.DAY_OF_YEAR); } if (currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group calendar.setTimeInMillis(e.getTime()); lastDay = e.day; data.remove(currentGroupPosition); data.add(currentGroupPosition, e); insert_pos = currentGroupPosition; } else if (eid > max_eid || data.size() == 0 || eid > data.get(data.size() - 1).eid) { //Message at the bottom if (data.size() > 0) { lastDay = data.get(data.size() - 1).day; } else { lastDay = 0; } max_eid = eid; data.add(e); insert_pos = data.size() - 1; } else if (min_eid > eid) { //Message goes on top if (data.size() > 1) { lastDay = data.get(1).day; if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline data.add(0, e); insert_pos = 0; } else { //Insert below the dateline data.add(1, e); insert_pos = 1; } } else { data.add(0, e); insert_pos = 0; } } else { int i = 0; for (Event e1 : data) { if (e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid && e1.group_eid != eid) { //Insert the message if (i > 0 && data.get(i - 1).row_type != ROW_TIMESTAMP) { lastDay = data.get(i - 1).day; data.add(i, e); insert_pos = i; break; } else { //There was a date line above our insertion point lastDay = e1.day; if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline if (i > 1) { lastDay = data.get(i - 2).day; } else { //We're above the first dateline, so we'll need to put a new one on top! lastDay = 0; } data.add(i - 1, e); insert_pos = i - 1; } else { //Insert below the dateline data.add(i, e); insert_pos = i; } break; } } else if (e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(i); data.add(i, e); insert_pos = i; break; } i++; } } if (insert_pos == -1) { Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html); data.add(e); insert_pos = data.size() - 1; } if (eid > buffer.getLast_seen_eid() && e.highlight) unseenHighlightPositions.add(insert_pos); if (eid < min_eid || min_eid == 0) min_eid = eid; if (eid == currentCollapsedEid && e.eid == eid) { currentGroupPosition = insert_pos; } else if (currentCollapsedEid == -1) { currentGroupPosition = -1; } if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { if (formatter == null) formatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); else formatter.applyPattern("EEEE, MMMM dd, yyyy"); Event d = new Event(); d.type = TYPE_TIMESTAMP; d.row_type = ROW_TIMESTAMP; d.eid = eid - 1; d.timestamp = formatter.format(calendar.getTime()); d.bg_color = colorScheme.timestampBackgroundDrawable; d.day = lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.add(insert_pos++, d); if (currentGroupPosition > -1) currentGroupPosition++; } if (insert_pos > 0) { Event prev = data.get(insert_pos - ((e.row_type == ROW_LASTSEENEID)?2:1)); e.header = (e.isMessage() && e.from != null && e.from.length() > 0 && e.group_eid < 1) && (prev.from == null || !prev.from.equals(e.from) || !prev.type.equals(e.type)); } if (insert_pos < (data.size() - 1)) { Event next = data.get(insert_pos + 1); if (!e.isMessage() && e.row_type != ROW_LASTSEENEID) { next.header = (next.isMessage() && next.from != null && next.from.length() > 0 && next.group_eid < 1); } if (next.from != null && next.from.equals(e.from) && next.type.equals(e.type)) { next.header = false; } } } } @Override public int getCount() { synchronized (data) { if (ctx != null) return data.size(); else return 0; } } @Override public Object getItem(int position) { synchronized (data) { if (position < data.size()) return data.get(position); else return null; } } @Override public long getItemId(int position) { synchronized (data) { if (position < data.size()) return data.get(position).eid; else return -1; } } public void format() { for (int i = 0; i < data.size(); i++) { Event e = data.get(i); if (e != null) { synchronized (e) { if (e.html != null) { try { e.html = ColorFormatter.emojify(ColorFormatter.irc_to_html(e.html)); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server, e.entities); if (e.msg != null && e.msg.length() > 0) e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString(); if (e.from != null && e.from.length() > 0) { e.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(e.from, e.from_mode, !e.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (e.formatted_realname == null && e.from_realname != null && e.from_realname.length() > 0) { e.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(e.from_realname)), true, null); } } catch (Exception ex) { } } } } } } @Override public int getItemViewType(int position) { synchronized (data) { return data.get(position).row_type; } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position >= data.size() || ctx == null) return null; Event e; synchronized (data) { e = data.get(position); } synchronized (e) { View row = convertView; ViewHolder holder; if (row != null && ((ViewHolder) row.getTag()).type != e.row_type) row = null; if (row == null) { LayoutInflater inflater = ctx.getLayoutInflater(null); if (e.row_type == ROW_BACKLOGMARKER) row = inflater.inflate(R.layout.row_backlogmarker, parent, false); else if (e.row_type == ROW_TIMESTAMP) row = inflater.inflate(R.layout.row_timestamp, parent, false); else if (e.row_type == ROW_SOCKETCLOSED) row = inflater.inflate(R.layout.row_socketclosed, parent, false); else if (e.row_type == ROW_LASTSEENEID) row = inflater.inflate(R.layout.row_lastseeneid, parent, false); else row = inflater.inflate(R.layout.row_message, parent, false); holder = new ViewHolder(); holder.timestamp = (TextView) row.findViewById(R.id.timestamp); holder.timestamp_left = (TextView) row.findViewById(R.id.timestamp_left); holder.timestamp_right = (TextView) row.findViewById(R.id.timestamp_right); holder.message = (TextView) row.findViewById(R.id.message); holder.expandable = (TextView) row.findViewById(R.id.expandable); if(holder.expandable != null) holder.expandable.setTypeface(FontAwesome.getTypeface()); holder.nickname = (TextView) row.findViewById(R.id.nickname); holder.realname = (TextView) row.findViewById(R.id.realname); holder.failed = (ImageView) row.findViewById(R.id.failed); holder.avatar = (ImageView) row.findViewById(R.id.avatar); holder.lastSeenEidWrapper = (LinearLayout) row.findViewById(R.id.lastSeenEidWrapper); holder.messageContainer = (LinearLayout) row.findViewById(R.id.messageContainer); holder.socketClosedBar = (LinearLayout) row.findViewById(R.id.socketClosedBar); holder.type = e.row_type; row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } row.setOnClickListener(new OnItemClickListener(position)); row.setOnLongClickListener(new OnItemLongClickListener(position)); if (e.html != null && e.formatted == null) { e.html = ColorFormatter.emojify(ColorFormatter.irc_to_html(e.html)); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server, e.entities); if (e.msg != null && e.msg.length() > 0) e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString(); } if (e.formatted_nick == null && e.from != null && e.from.length() > 0) { e.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(e.from, e.from_mode, !e.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (e.formatted_realname == null && e.from_realname != null && e.from_realname.length() > 0) { e.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(e.from_realname)), true, null); } if (e.row_type == ROW_MESSAGE) { if (e.bg_color == colorScheme.contentBackgroundColor) row.setBackgroundDrawable(null); else row.setBackgroundColor(e.bg_color); if (e.contentDescription != null && e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) { row.setContentDescription("Message from " + e.from + " at " + e.timestamp + ": " + e.contentDescription); } } boolean mono = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("monospace", false); if(holder.timestamp_left != null) { if(pref_timeLeft && (pref_chatOneLine || pref_avatarsOff)) { holder.timestamp_left.setVisibility(View.VISIBLE); holder.timestamp_right.setVisibility(View.GONE); holder.timestamp = holder.timestamp_left; } else { holder.timestamp_left.setVisibility(View.GONE); holder.timestamp_right.setVisibility(View.VISIBLE); holder.timestamp = holder.timestamp_right; } } if (holder.timestamp != null) { holder.timestamp.setTypeface(mono ? hackRegular : Typeface.DEFAULT); if (e.row_type == ROW_TIMESTAMP) { holder.timestamp.setTextSize(textSize); } else { holder.timestamp.setTextSize(textSize - 2); if (timestamp_width == -1) { String s = " 88:88"; if (pref_seconds) s += ":88"; if (!pref_24hr) s += " MM"; timestamp_width = (int) holder.timestamp.getPaint().measureText(s); } holder.timestamp.setMinWidth(timestamp_width); } if (e.highlight && !e.self) holder.timestamp.setTextColor(colorScheme.highlightTimestampColor); else if (e.row_type != ROW_TIMESTAMP) holder.timestamp.setTextColor(colorScheme.timestampColor); holder.timestamp.setText(e.timestamp); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)holder.timestamp.getLayoutParams(); lp.topMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pref_compact?0:2, getResources().getDisplayMetrics()); } if (e.row_type == ROW_SOCKETCLOSED) { if (e.msg != null && e.msg.length() > 0) { holder.timestamp.setVisibility(View.VISIBLE); holder.message.setVisibility(View.VISIBLE); } else { holder.timestamp.setVisibility(View.GONE); holder.message.setVisibility(View.GONE); } } if (holder.message != null && e.html != null) { holder.message.setMovementMethod(linkMovementMethodNoLongPress); holder.message.setOnClickListener(new OnItemClickListener(position)); holder.message.setOnLongClickListener(new OnItemLongClickListener(position)); if (mono || (e.msg != null && e.msg.startsWith("<pre>"))) { holder.message.setTypeface(hackRegular); } else { holder.message.setTypeface(Typeface.DEFAULT); } try { holder.message.setTextColor(e.color); } catch (Exception e1) { } if (e.color == colorScheme.timestampColor || e.pending) holder.message.setLinkTextColor(colorScheme.lightLinkColor); else holder.message.setLinkTextColor(colorScheme.linkColor); if(pref_compact) holder.message.setLineSpacing(0,1); else holder.message.setLineSpacing(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()),1); Spanned formatted = e.formatted; if(formatted != null && !pref_avatarsOff && ((e.from != null && e.from.length() > 0) || e.type.equals("buffer_me_msg")) && e.group_eid < 0 && (pref_chatOneLine || e.type.equals("buffer_me_msg"))) { Bitmap b = mAvatarsList.getAvatar(e.cid, e.type.equals("buffer_me_msg")?e.nick:e.from).getBitmap(ColorScheme.getInstance().isDarkTheme, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, textSize+4, getResources().getDisplayMetrics()), e.self); if(b != null) { SpannableStringBuilder s = new SpannableStringBuilder(formatted); s.insert(0, " "); s.setSpan(new ImageSpan(getActivity(), b) { @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); canvas.save(); canvas.translate(x, top + ((paint.getFontMetricsInt().descent - paint.getFontMetricsInt().ascent) / 2) - ((b.getBounds().bottom - b.getBounds().top) / 2) - (((int)textSize - b.getIntrinsicHeight() / 2))); b.draw(canvas); canvas.restore(); } }, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); formatted = s; } } holder.message.setText(formatted); if (e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) { holder.message.setContentDescription(e.from + ": " + e.contentDescription); } holder.message.setTextSize(textSize); } if (holder.expandable != null) { if (e.group_eid > 0 && (e.group_eid != e.eid || expandedSectionEids.contains(e.group_eid))) { if (expandedSectionEids.contains(e.group_eid)) { if (e.group_eid == e.eid + 1) { holder.expandable.setText(FontAwesome.MINUS_SQUARE_O); holder.expandable.setContentDescription("expanded"); row.setBackgroundColor(colorScheme.collapsedHeadingBackgroundColor); } else { holder.expandable.setText(FontAwesome.ANGLE_RIGHT); holder.expandable.setContentDescription("collapse"); row.setBackgroundColor(colorScheme.contentBackgroundColor); } } else { holder.expandable.setText(FontAwesome.PLUS_SQUARE_O); holder.expandable.setContentDescription("expand"); } holder.expandable.setVisibility(View.VISIBLE); } else { holder.expandable.setVisibility(View.GONE); } holder.expandable.setTextColor(colorScheme.expandCollapseIndicatorColor); } if (holder.failed != null) holder.failed.setVisibility(e.failed ? View.VISIBLE : View.GONE); if (holder.messageContainer != null) { if(pref_compact) holder.messageContainer.setPadding(0,0,0,0); else holder.messageContainer.setPadding(0,0,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics())); } if (holder.avatar != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)holder.avatar.getLayoutParams(); if(pref_avatarsOff || pref_chatOneLine || (e.row_type == ROW_SOCKETCLOSED && (e.msg == null || e.msg.length() == 0))) { holder.avatar.setImageBitmap(null); lp.topMargin = lp.width = lp.height = 0; } else { lp.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 32, getResources().getDisplayMetrics()); Bitmap b = null; if (e.group_eid < 1 && e.from != null && e.from.length() > 0 && (pref_chatOneLine || e.header)) { Avatar a = mAvatarsList.getAvatar(e.cid, e.from); b = a.getBitmap(ColorScheme.getInstance().isDarkTheme, lp.width, e.self); holder.avatar.setVisibility(View.VISIBLE); holder.avatar.setTag(a); } holder.avatar.setImageBitmap(b); if(b != null) lp.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16 * ((!e.header || b == null || e.group_eid > 0)?1:2), getResources().getDisplayMetrics()); else lp.height = 0; } holder.avatar.setLayoutParams(lp); } if(!pref_chatOneLine && e.header && e.formatted_nick != null && e.formatted_nick.length() > 0 && e.group_eid < 1) { if (holder.nickname != null) { holder.nickname.setVisibility(View.VISIBLE); if (mono) holder.nickname.setTypeface(hackRegular); else holder.nickname.setTypeface(Typeface.DEFAULT); holder.nickname.setTextSize(textSize); holder.nickname.setText(e.formatted_nick); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.nickname.getLayoutParams(); lp.leftMargin = (pref_timeLeft&&pref_avatarsOff)?timestamp_width:0; holder.nickname.setLayoutParams(lp); } if (holder.realname != null) { holder.realname.setMovementMethod(linkMovementMethodNoLongPress); holder.realname.setVisibility((pref_chatOneLine || pref_norealname) ? View.GONE : View.VISIBLE); if (mono) holder.realname.setTypeface(hackRegular); else holder.realname.setTypeface(Typeface.DEFAULT); holder.realname.setTextSize(textSize); holder.realname.setTextColor(colorScheme.timestampColor); holder.realname.setText(e.formatted_realname); } } else { if (holder.nickname != null) holder.nickname.setVisibility(View.GONE); if (holder.realname != null) holder.realname.setVisibility(View.GONE); if (holder.avatar != null) holder.avatar.setVisibility((pref_avatarsOff || pref_chatOneLine) ? View.GONE : View.VISIBLE); if(holder.message != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.message.getLayoutParams(); lp.leftMargin = 0; holder.message.setLayoutParams(lp); } } if(holder.lastSeenEidWrapper != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.lastSeenEidWrapper.getLayoutParams(); if(!pref_avatarsOff && !pref_chatOneLine) lp.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 48, getResources().getDisplayMetrics()); else lp.leftMargin = 0; holder.lastSeenEidWrapper.setLayoutParams(lp); holder.lastSeenEidWrapper.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, pref_compact?(textSize + 2):(textSize + 4), getResources().getDisplayMetrics())); } if(holder.socketClosedBar != null) { holder.socketClosedBar.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSize + 2, getResources().getDisplayMetrics())); } if(e.row_type == ROW_BACKLOGMARKER) row.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, pref_compact?4:(textSize + 2), getResources().getDisplayMetrics())); return row; } } } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { hackRegular = Typeface.createFromAsset(getActivity().getAssets(), "Hack-Regular.otf"); final View v = inflater.inflate(R.layout.messageview, container, false); statusView = (TextView) v.findViewById(R.id.statusView); statusView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (buffer != null && conn != null && server != null && server.getStatus() != null && server.getStatus().equalsIgnoreCase("disconnected")) { NetworkConnection.getInstance().reconnect(buffer.getCid()); } } }); awayView = v.findViewById(R.id.away); awayView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(buffer != null) NetworkConnection.getInstance().back(buffer.getCid()); } }); awayTxt = (TextView) v.findViewById(R.id.awayTxt); unreadBottomView = v.findViewById(R.id.unreadBottom); unreadBottomView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(buffer != null) buffer.setScrolledUp(false); getListView().setSelection(adapter.getCount() - 1); hideView(unreadBottomView); } }); unreadBottomLabel = (TextView) v.findViewById(R.id.unread); highlightsBottomLabel = (TextView) v.findViewById(R.id.highlightsBottom); unreadTopView = v.findViewById(R.id.unreadTop); unreadTopView.setVisibility(View.GONE); unreadTopView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (adapter.getLastSeenEIDPosition() > 0) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); hideView(unreadTopView); } getListView().setSelection(adapter.getLastSeenEIDPosition()); } }); unreadTopLabel = (TextView) v.findViewById(R.id.unreadTopText); highlightsTopLabel = (TextView) v.findViewById(R.id.highlightsTop); Button b = (Button) v.findViewById(R.id.markAsRead); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { hideView(unreadTopView); if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } }); globalMsgView = v.findViewById(R.id.globalMessageView); globalMsg = (TextView) v.findViewById(R.id.globalMessageTxt); b = (Button) v.findViewById(R.id.dismissGlobalMessage); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (conn != null) conn.globalMsg = null; update_global_msg(); } }); spinner = (ProgressBar) v.findViewById(R.id.spinner); suggestionsContainer = v.findViewById(R.id.suggestionsContainer); suggestions = (GridView) v.findViewById(R.id.suggestions); headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null); headerView = headerViewContainer.findViewById(R.id.progress); backlogFailed = (TextView) headerViewContainer.findViewById(R.id.backlogFailed); loadBacklogButton = (Button) headerViewContainer.findViewById(R.id.loadBacklogButton); loadBacklogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (conn != null && buffer != null) { backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); headerView.setVisibility(View.VISIBLE); NetworkConnection.getInstance().request_backlog(buffer.getCid(), buffer.getBid(), earliest_eid); } } }); ((ListView) v.findViewById(android.R.id.list)).addHeaderView(headerViewContainer); footerViewContainer = new View(getActivity()); ((ListView) v.findViewById(android.R.id.list)).addFooterView(footerViewContainer, null, false); avatarContainer = (OffsetLinearLayout) v.findViewById(R.id.avatarContainer); avatar = (ImageView) v.findViewById(R.id.avatar); return v; } public void showSpinner(boolean show) { if (show) { if (Build.VERSION.SDK_INT < 16) { AlphaAnimation anim = new AlphaAnimation(0, 1); anim.setDuration(150); anim.setFillAfter(true); spinner.setAnimation(anim); } else { spinner.setAlpha(0); spinner.animate().alpha(1); } spinner.setVisibility(View.VISIBLE); } else { if (Build.VERSION.SDK_INT < 16) { AlphaAnimation anim = new AlphaAnimation(1, 0); anim.setDuration(150); anim.setFillAfter(true); anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { spinner.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); spinner.setAnimation(anim); } else { spinner.animate().alpha(0).withEndAction(new Runnable() { @Override public void run() { spinner.setVisibility(View.GONE); } }); } } } private void hideView(final View v) { if (v.getVisibility() != View.GONE) { if (Build.VERSION.SDK_INT >= 16) { v.animate().alpha(0).setDuration(100).withEndAction(new Runnable() { @Override public void run() { v.setVisibility(View.GONE); } }); } else { v.setVisibility(View.GONE); } } } private void showView(final View v) { if (v.getVisibility() != View.VISIBLE) { if (Build.VERSION.SDK_INT >= 16) { v.setAlpha(0); v.animate().alpha(1).setDuration(100); } v.setVisibility(View.VISIBLE); } } public void drawerClosed() { try { ListView v = getListView(); mOnScrollListener.onScroll(v, v.getFirstVisiblePosition(), v.getLastVisiblePosition() - v.getFirstVisiblePosition(), adapter.getCount()); } catch (Exception e) { } } private void hide_avatar() { if (avatarContainer.getVisibility() != View.GONE) avatarContainer.setVisibility(View.GONE); if (avatar.getTag() != null) { ((ImageView) avatar.getTag()).setVisibility(View.VISIBLE); avatar.setTag(null); } } private OnScrollListener mOnScrollListener = new OnScrollListener() { @Override public void onScroll(final AbsListView view, final int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!ready || buffer == null || adapter == null || visibleItemCount < 0) { hide_avatar(); return; } if (conn.ready && !requestingBacklog && headerView != null && buffer.getMin_eid() > 0) { if (firstVisibleItem == 0 && headerView.getVisibility() == View.VISIBLE && conn.getState() == NetworkConnection.STATE_CONNECTED) { requestingBacklog = true; conn.request_backlog(buffer.getCid(), buffer.getBid(), earliest_eid); hide_avatar(); return; } else if(firstVisibleItem > 0 && loadBacklogButton.getVisibility() == View.VISIBLE) { loadBacklogButton.setVisibility(View.GONE); headerView.setVisibility(View.VISIBLE); } } if (unreadBottomView != null && adapter.data.size() > 0) { if (firstVisibleItem + visibleItemCount >= totalItemCount) { if(unreadBottomView.getVisibility() != View.GONE) unreadBottomView.setVisibility(View.GONE); if (unreadTopView.getVisibility() == View.GONE && conn.getState() == NetworkConnection.STATE_CONNECTED) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } newMsgs = 0; newMsgTime = 0; newHighlights = 0; } } if (firstVisibleItem + visibleItemCount < totalItemCount - 1) { View v = view.getChildAt(0); buffer.setScrolledUp(true); buffer.setScrollPosition(firstVisibleItem); buffer.setScrollPositionOffset((v == null) ? 0 : v.getTop()); } else { buffer.setScrolledUp(false); buffer.setScrollPosition(-1); } if (adapter != null && adapter.data.size() > 0) { synchronized (adapter.data) { if (unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) { update_top_unread(firstVisibleItem); int markerPos = -1; if (adapter != null) markerPos = adapter.getLastSeenEIDPosition(); if (markerPos > 1 && getListView().getFirstVisiblePosition() <= markerPos) { unreadTopView.setVisibility(View.GONE); if (conn.getState() == NetworkConnection.STATE_CONNECTED) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } } } if (!pref_chatOneLine && !pref_avatarsOff && firstVisibleItem > ((ListView) view).getHeaderViewsCount()) { int offset = (unreadTopView.getVisibility() == View.VISIBLE) ? unreadTopView.getHeight() : 0; View v; int i = 0; do { v = view.getChildAt(i++); } while (v != null && v.getTop() + v.getHeight() <= offset - 1); if(v != null) { int first = firstVisibleItem - ((ListView) view).getHeaderViewsCount() + i - 1; MessageAdapter.ViewHolder vh = (MessageAdapter.ViewHolder) v.getTag(); MessageAdapter.ViewHolder top_vh = vh; Event e = first >= 0 ? (Event) adapter.getItem(first) : null; if (first > 0 && vh != null && v.getTop() <= offset && e != null && ((vh.avatar != null && e.group_eid < 1 && e.isMessage() && e.from != null && e.from.length() > 0) || e.row_type == ROW_LASTSEENEID)) { for (i = first; i < adapter.getCount() && i < first + 4; i++) { e = (Event) adapter.getItem(i); if(e.row_type == ROW_LASTSEENEID) e = (Event) adapter.getItem(i-1); int next = i + 1; Event e1 = (Event) adapter.getItem(next); if(e1 != null && e1.row_type == ROW_LASTSEENEID) { next++; if(next < adapter.getCount()) e1 = (Event) adapter.getItem(next); else break; } if (e != null && e1 != null && e.from != null && e.from.equals(e1.from) && e1.group_eid < 1 && !e1.header) { View v1 = view.getChildAt(next - (firstVisibleItem - ((ListView) view).getHeaderViewsCount())); if (v1 != null) { MessageAdapter.ViewHolder vh1 = (MessageAdapter.ViewHolder) v1.getTag(); if (vh1 != null && vh1.avatar != null) { v = v1; vh = vh1; } } } else { break; } } if (avatar.getTag() != null && avatar.getTag() != top_vh.avatar) { ((ImageView) avatar.getTag()).setVisibility(View.VISIBLE); } if(e != null) { Bitmap bitmap = mAvatarsList.getAvatar(e.cid, e.from).getBitmap(ColorScheme.getInstance().isDarkTheme, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 32, getResources().getDisplayMetrics()), e.self); if(vh.avatar != null && bitmap != null) { int topMargin, leftMargin; int height = bitmap.getHeight() + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()); if (v.getHeight() + v.getTop() < (height + offset)) { topMargin = v.getTop() + v.getHeight() - height; } else { topMargin = offset; } leftMargin = vh.avatar.getLeft(); avatarContainer.offset(leftMargin, topMargin); if (top_vh.avatar == null || (avatar.getTag() != top_vh.avatar || top_vh.avatar.getVisibility() != View.INVISIBLE)) { avatar.setTag(top_vh.avatar); avatar.setImageBitmap(bitmap); avatarContainer.setVisibility(View.VISIBLE); if(top_vh.avatar != null) top_vh.avatar.setVisibility(View.INVISIBLE); } } else { hide_avatar(); } } } else { hide_avatar(); } } else { hide_avatar(); } } else { hide_avatar(); } } } else { hide_avatar(); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); conn = NetworkConnection.getInstance(); conn.addHandler(this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (MessageViewListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement MessageViewListener"); } if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); } @Override public void setArguments(Bundle args) { ready = false; if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = null; if (tapTimerTask != null) tapTimerTask.cancel(); tapTimerTask = null; if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); if (buffer != null && buffer.getBid() != args.getInt("bid", -1) && adapter != null) adapter.clearLastSeenEIDMarker(); buffer = BuffersList.getInstance().getBuffer(args.getInt("bid", -1)); if (buffer != null) { server = buffer.getServer(); Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: switched to bid: " + buffer.getBid()); } else { Crashlytics.log(Log.WARN, "IRCCloud", "MessageViewFragment: couldn't find buffer to switch to"); } requestingBacklog = false; avgInsertTime = 0; newMsgs = 0; newMsgTime = 0; newHighlights = 0; earliest_eid = 0; backlog_eid = 0; currentCollapsedEid = -1; lastCollapsedDay = -1; if (server != null) { ignore.setIgnores(server.ignores); if (server.getAway() != null && server.getAway().length() > 0) { awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.getAway() + ")"))).toString()); awayView.setVisibility(View.VISIBLE); } else { awayView.setVisibility(View.GONE); } collapsedEvents.setServer(server); update_status(server.getStatus(), server.getFail_info()); } if (avatar != null) { avatarContainer.setVisibility(View.GONE); avatar.setTag(null); } if (unreadTopView != null) unreadTopView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); try { if (getListView().getHeaderViewsCount() == 0) { getListView().addHeaderView(headerViewContainer); } } catch (IllegalStateException e) { } ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams(); lp.topMargin = 0; headerView.setLayoutParams(lp); lp = (ViewGroup.MarginLayoutParams) backlogFailed.getLayoutParams(); lp.topMargin = 0; backlogFailed.setLayoutParams(lp); if (buffer != null && EventsList.getInstance().getEventsForBuffer(buffer.getBid()) != null) { requestingBacklog = true; if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); if (args.getBoolean("fade")) { Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: Loading message contents in the background"); refreshTask.execute((Void) null); } else { Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: Loading message contents"); refreshTask.onPreExecute(); refreshTask.onPostExecute(refreshTask.doInBackground()); } } else { if (buffer == null || buffer.getMin_eid() == 0 || earliest_eid == buffer.getMin_eid() || conn.getState() != NetworkConnection.STATE_CONNECTED || !conn.ready) { headerView.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } else { headerView.setVisibility(View.VISIBLE); loadBacklogButton.setVisibility(View.GONE); } if (adapter != null) { adapter.clear(); adapter.notifyDataSetInvalidated(); } else { adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); } if(mListener != null) mListener.onMessageViewReady(); ready = true; } } private void runOnUiThread(Runnable r) { if (getActivity() != null) getActivity().runOnUiThread(r); } @Override public void onLowMemory() { super.onLowMemory(); Crashlytics.log(Log.DEBUG, "IRCCloud", "Received low memory warning in the foreground, cleaning backlog in other buffers"); for (Buffer b : BuffersList.getInstance().getBuffers()) { if (b != buffer) EventsList.getInstance().pruneEvents(b.getBid()); } } private synchronized void insertEvent(final MessageAdapter adapter, Event event, boolean backlog, boolean nextIsGrouped) { synchronized (adapterLock) { try { long start = System.currentTimeMillis(); if (event.eid <= buffer.getMin_eid()) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } if (earliest_eid == 0 || event.eid < earliest_eid) earliest_eid = event.eid; String type = event.type; long eid = event.eid; if (type.startsWith("you_")) type = type.substring(4); if (type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange") || type.equals("quit") || type.equals("user_channel_mode") || type.equals("socket_closed") || type.equals("connecting_cancelled") || type.equals("connecting_failed")) { collapsedEvents.showChan = !buffer.isChannel(); if (pref_hideJoinPart && !type.equals("socket_closed") && !type.equals("connecting_cancelled") && !type.equals("connecting_failed")) { adapter.removeItem(event.eid); if (!backlog) adapter.notifyDataSetChanged(); return; } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(event.getTime()); if (pref_expandJoinPart) expandedSectionEids.clear(); if (event.type.equals("socket_closed") || event.type.equals("connecting_failed") || event.type.equals("connecting_cancelled")) { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null && !last.type.equals("socket_closed") && !last.type.equals("connecting_failed") && !last.type.equals("connecting_cancelled")) currentCollapsedEid = -1; } else { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null && (last.type.equals("socket_closed") || last.type.equals("connecting_failed") || last.type.equals("connecting_cancelled"))) currentCollapsedEid = -1; } if (currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || pref_expandJoinPart || event.type.equals("you_parted_channel")) { collapsedEvents.clear(); currentCollapsedEid = eid; lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR); } if (!collapsedEvents.showChan) event.chan = buffer.getName(); if (!collapsedEvents.addEvent(event)) collapsedEvents.clear(); if ((currentCollapsedEid == event.eid || pref_expandJoinPart) && type.equals("user_channel_mode")) { event.color = colorScheme.messageTextColor; event.bg_color = colorScheme.collapsedHeadingBackgroundColor; } else { event.color = colorScheme.collapsedRowTextColor; event.bg_color = colorScheme.contentBackgroundColor; } String msg; if (expandedSectionEids.contains(currentCollapsedEid)) { CollapsedEventsList c = new CollapsedEventsList(); c.showChan = collapsedEvents.showChan; c.setServer(server); c.addEvent(event); msg = c.getCollapsedMessage(); if (!nextIsGrouped) { String group_msg = collapsedEvents.getCollapsedMessage(); if (group_msg == null && type.equals("nickchange")) { group_msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if (group_msg == null && type.equals("user_channel_mode")) { if (event.from != null && event.from.length() > 0) msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>"; else msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>"; currentCollapsedEid = eid; } Event heading = new Event(); heading.type = "__expanded_group_heading__"; heading.cid = event.cid; heading.bid = event.bid; heading.eid = currentCollapsedEid - 1; heading.group_msg = group_msg; heading.color = colorScheme.timestampColor; heading.bg_color = colorScheme.contentBackgroundColor; heading.linkify = false; adapter.addItem(currentCollapsedEid - 1, heading); if (event.type.equals("socket_closed") || event.type.equals("connecting_failed") || event.type.equals("connecting_cancelled")) { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null) last.row_type = ROW_MESSAGE; event.row_type = ROW_SOCKETCLOSED; } } event.timestamp = null; } else { msg = (nextIsGrouped && currentCollapsedEid != event.eid) ? "" : collapsedEvents.getCollapsedMessage(); } if (msg == null && type.equals("nickchange")) { msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if (msg == null && type.equals("user_channel_mode")) { if (event.from != null && event.from.length() > 0) msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>"; else msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>"; currentCollapsedEid = eid; } if (!expandedSectionEids.contains(currentCollapsedEid)) { if (eid != currentCollapsedEid) { event.color = colorScheme.timestampColor; event.bg_color = colorScheme.contentBackgroundColor; } eid = currentCollapsedEid; } event.group_msg = msg; event.html = null; event.formatted = null; event.linkify = false; lastCollapsedEid = event.eid; if ((buffer.isConsole() && !event.type.equals("socket_closed") && !event.type.equals("connecting_failed") && !event.type.equals("connecting_cancelled")) || event.type.equals("you_parted_channel")) { currentCollapsedEid = -1; lastCollapsedEid = -1; collapsedEvents.clear(); } } else { currentCollapsedEid = -1; lastCollapsedEid = -1; collapsedEvents.clear(); if (event.html == null) { if ((pref_chatOneLine || !event.isMessage()) && event.from != null && event.from.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> " + event.msg; else if (pref_chatOneLine && event.type.equals("buffer_msg") && event.server != null && event.server.length() > 0) event.html = "<b>" + event.server + "</b> " + event.msg; else event.html = event.msg; } if (event.formatted_nick == null && event.from != null && event.from.length() > 0) { event.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (event.formatted_realname == null && event.from_realname != null && event.from_realname.length() > 0) { event.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(event.from_realname)), true, null); } } String from = event.from; if (from == null || from.length() == 0) from = event.nick; if (from != null && event.hostmask != null && event.isMessage() && buffer.getType() != null && !buffer.isConversation()) { String usermask = from + "!" + event.hostmask; if (ignore.match(usermask)) { if (unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } return; } } switch (type) { case "channel_mode": if (event.nick != null && event.nick.length() > 0) event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>"; else if (event.server != null && event.server.length() > 0) event.html = event.msg + " by the server <b>" + event.server + "</b>"; break; case "buffer_me_msg": event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> " + event.msg + "</i>"; break; case "buffer_msg": case "notice": if (pref_chatOneLine && event.from != null && event.from.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> "; else event.html = ""; if(event.target_mode != null && server != null && server.PREFIX != null) { if (server.PREFIX.has(server.MODE_OPER) && server.PREFIX.get(server.MODE_OPER) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OPER).asText())) event.html += collapsedEvents.formatNick("Opers", server.MODE_OPER, false) + " "; else if (server.PREFIX.has(server.MODE_OWNER) && server.PREFIX.get(server.MODE_OWNER) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OWNER).asText())) event.html += collapsedEvents.formatNick("Owners", server.MODE_OWNER, false) + " "; else if (server.PREFIX.has(server.MODE_ADMIN) && server.PREFIX.get(server.MODE_ADMIN) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_ADMIN).asText())) event.html += collapsedEvents.formatNick("Admins", server.MODE_ADMIN, false) + " "; else if (server.PREFIX.has(server.MODE_OP) && server.PREFIX.get(server.MODE_OP) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OP).asText())) event.html += collapsedEvents.formatNick("Ops", server.MODE_OP, false) + " "; else if (server.PREFIX.has(server.MODE_HALFOP) && server.PREFIX.get(server.MODE_HALFOP) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_HALFOP).asText())) event.html += collapsedEvents.formatNick("Half Ops", server.MODE_HALFOP, false) + " "; else if (server.PREFIX.has(server.MODE_VOICED) && server.PREFIX.get(server.MODE_VOICED) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_VOICED).asText())) event.html += collapsedEvents.formatNick("Voiced", server.MODE_VOICED, false) + " "; } if (buffer.isConsole() && event.to_chan && event.chan != null && event.chan.length() > 0) { event.html += "<b>" + event.chan + "</b>: " + event.msg; } else if (buffer.isConsole() && event.self && event.nick != null && event.nick.length() > 0) { event.html += "<b>" + event.nick + "</b>: " + event.msg; } else { event.html += event.msg; } break; case "kicked_channel": event.html = "← "; if (event.type.startsWith("you_")) event.html += "You"; else event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>"; if (event.hostmask != null && event.hostmask.length() > 0) event.html += " (" + event.hostmask + ")"; if (event.type.startsWith("you_")) event.html += " were"; else event.html += " was"; if (event.from_hostmask != null && event.from_hostmask.length() > 0) event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>"; else event.html += " kicked by the server <b>" + event.nick + "</b>"; if (event.msg != null && event.msg.length() > 0 && !event.msg.equals(event.nick)) event.html += ": " + event.msg; break; case "callerid": event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> (" + event.hostmask + ") " + event.msg + " Tap to accept."; break; case "channel_mode_list_change": if (event.from.length() == 0) { if (event.nick != null && event.nick.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> " + event.msg; else if (event.server != null && event.server.length() > 0) event.html = "The server <b>" + event.server + "</b> " + event.msg; } break; } adapter.addItem(eid, event); if (!backlog) adapter.notifyDataSetChanged(); long time = (System.currentTimeMillis() - start); if (avgInsertTime == 0) avgInsertTime = time; avgInsertTime += time; avgInsertTime /= 2.0; //Log.i("IRCCloud", "Average insert time: " + avgInsertTime); if (!backlog && buffer.getScrolledUp() && !event.self && event.isImportant(type)) { if (newMsgTime == 0) newMsgTime = System.currentTimeMillis(); newMsgs++; if (event.highlight) newHighlights++; update_unread(); adapter.insertLastSeenEIDMarker(); adapter.notifyDataSetChanged(); } if (!backlog && !buffer.getScrolledUp()) { getListView().setSelection(adapter.getCount() - 1); if (tapTimer != null) { tapTimer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { try { getListView().setSelection(adapter.getCount() - 1); } catch (Exception e) { //List view isn't ready yet } } }); } }, 200); } } if (!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) { Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit(); editor.putBoolean("mentionTip", true); editor.commit(); } if (!backlog) { int markerPos = adapter.getLastSeenEIDPosition(); if (markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages"); } } } catch (Exception e) { // TODO Auto-generated catch block NetworkConnection.printStackTraceToCrashlytics(e); } } } private class OnItemLongClickListener implements View.OnLongClickListener { private int pos; OnItemLongClickListener(int position) { pos = position; } @Override public boolean onLongClick(View view) { try { longPressOverride = mListener.onMessageLongClicked((Event) adapter.getItem(pos)); return longPressOverride; } catch (Exception e) { } return false; } } private class OnItemClickListener implements OnClickListener { private int pos; OnItemClickListener(int position) { pos = position; } @Override public void onClick(View arg0) { longPressOverride = false; if (pos < 0 || pos >= adapter.data.size()) return; if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); if (adapter != null) { if (tapTimerTask != null) { tapTimerTask.cancel(); tapTimerTask = null; mListener.onMessageDoubleClicked(adapter.data.get(pos)); } else { tapTimerTask = new TimerTask() { int position = pos; @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null && adapter.data != null && position < adapter.data.size()) { Event e = adapter.data.get(position); if (e != null) { if (e.type.equals("channel_invite")) { conn.join(buffer.getCid(), e.old_nick, null); } else if (e.type.equals("callerid")) { conn.say(buffer.getCid(), null, "/accept " + e.from); Buffer b = BuffersList.getInstance().getBufferByName(buffer.getCid(), e.from); if (b != null) { mListener.onBufferSelected(b.getBid()); } else { conn.say(buffer.getCid(), null, "/query " + e.from); } } else if (e.failed) { if(mListener != null) mListener.onFailedMessageClicked(e); } else { long group = e.group_eid; if (expandedSectionEids.contains(group)) expandedSectionEids.remove(group); else if (e.eid != group) expandedSectionEids.add(group); if (e.eid != e.group_eid) { adapter.clearLastSeenEIDMarker(); if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } } } } } }); tapTimerTask = null; } }; tapTimer.schedule(tapTimerTask, 300); } } } } @SuppressWarnings("unchecked") public void onResume() { super.onResume(); getListView().setOnScrollListener(mOnScrollListener); update_global_msg(); if (buffer != null && adapter != null) { if(buffer.getUnread() == 0 && !buffer.getScrolledUp()) adapter.clearLastSeenEIDMarker(); adapter.notifyDataSetChanged(); } } @Override public void onDestroyView() { super.onDestroyView(); getListView().setAdapter(null); } @Override public void onStop() { if(headerViewContainer != null) headerViewContainer.setVisibility(View.GONE); if(footerViewContainer != null) footerViewContainer.setVisibility(View.GONE); super.onStop(); } @Override public void onStart() { if(headerViewContainer != null) headerViewContainer.setVisibility(View.VISIBLE); if(footerViewContainer != null) footerViewContainer.setVisibility(View.VISIBLE); super.onStart(); } @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = IRCCloudApplication.getRefWatcher(getActivity()); if (refWatcher != null) refWatcher.watch(this); if (tapTimer != null) { tapTimer.cancel(); tapTimer = null; } if(conn != null) conn.removeHandler(this); mListener = null; heartbeatTask = null; } private class HeartbeatTask extends AsyncTaskEx<Void, Void, Void> { Buffer b; public HeartbeatTask() { b = buffer; /*if(buffer != null) Log.d("IRCCloud", "Heartbeat task created. Ready: " + ready + " BID: " + buffer.getBid()); Thread.dumpStack();*/ } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(250); } catch (InterruptedException e) { } if (isCancelled() || !conn.ready || conn.getState() != NetworkConnection.STATE_CONNECTED || b == null || !ready || requestingBacklog) return null; if (getActivity() != null) { try { DrawerLayout drawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawerLayout); if (drawerLayout != null && (drawerLayout.isDrawerOpen(Gravity.LEFT) || drawerLayout.isDrawerOpen(Gravity.RIGHT))) return null; } catch (Exception e) { } } if (unreadTopView.getVisibility() == View.VISIBLE || unreadBottomView.getVisibility() == View.VISIBLE) return null; try { Long eid = EventsList.getInstance().lastEidForBuffer(b.getBid()); if (eid >= b.getLast_seen_eid() && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { if (getActivity() != null && getActivity().getIntent() != null) getActivity().getIntent().putExtra("last_seen_eid", eid); NetworkConnection.getInstance().heartbeat(b.getCid(), b.getBid(), eid); b.setLast_seen_eid(eid); b.setUnread(0); b.setHighlights(0); //Log.e("IRCCloud", "Heartbeat: " + buffer.name + ": " + events.get(events.lastKey()).msg); } } catch (Exception e) { } return null; } @Override protected void onPostExecute(Void result) { if (!isCancelled()) heartbeatTask = null; } } private class FormatTask extends AsyncTaskEx<Void, Void, Void> { @Override protected void onPreExecute() { } @Override protected Void doInBackground(Void... params) { adapter.format(); return null; } @Override protected void onPostExecute(Void result) { } } private class RefreshTask extends AsyncTaskEx<Void, Void, Void> { private MessageAdapter adapter; TreeMap<Long, Event> events; Buffer buffer; int oldPosition = -1; int topOffset = -1; @Override protected void onPreExecute() { //Debug.startMethodTracing("refresh"); try { oldPosition = getListView().getFirstVisiblePosition(); View v = getListView().getChildAt(0); topOffset = (v == null) ? 0 : v.getTop(); buffer = MessageViewFragment.this.buffer; } catch (IllegalStateException e) { //The list view isn't on screen anymore cancel(true); refreshTask = null; } } @SuppressWarnings("unchecked") @Override protected Void doInBackground(Void... params) { TreeMap<Long, Event> evs = null; long time = System.currentTimeMillis(); if (buffer != null) evs = EventsList.getInstance().getEventsForBuffer(buffer.getBid()); Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms"); if (!isCancelled() && evs != null && evs.size() > 0) { try { events = (TreeMap<Long, Event>) evs.clone(); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); return null; } if (isCancelled()) return null; if (events != null) { try { if (events.size() > 0 && MessageViewFragment.this.adapter != null && MessageViewFragment.this.adapter.data.size() > 0 && earliest_eid > events.firstKey()) { if (oldPosition > 0 && oldPosition == MessageViewFragment.this.adapter.data.size()) oldPosition--; Event e = MessageViewFragment.this.adapter.data.get(oldPosition); if (e != null) backlog_eid = e.group_eid - 1; else backlog_eid = -1; if (backlog_eid < 0) { backlog_eid = MessageViewFragment.this.adapter.getItemId(oldPosition) - 1; } Event backlogMarker = new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.html = "__backlog__"; backlogMarker.bg_color = colorScheme.contentBackgroundColor; events.put(backlog_eid, backlogMarker); } adapter = new MessageAdapter(MessageViewFragment.this, events.size()); refresh(adapter, events); } catch (IllegalStateException e) { //The list view doesn't exist yet NetworkConnection.printStackTraceToCrashlytics(e); Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist."); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); return null; } } } else if (buffer != null && buffer.getMin_eid() > 0 && conn.ready && conn.getState() == NetworkConnection.STATE_CONNECTED && !isCancelled()) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.VISIBLE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; requestingBacklog = true; conn.request_backlog(buffer.getCid(), buffer.getBid(), 0); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; } }); } return null; } @Override protected void onPostExecute(Void result) { if (!isCancelled() && adapter != null) { try { avatarContainer.setVisibility(View.GONE); avatar.setTag(null); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams(); if (adapter.getLastSeenEIDPosition() == 0) lp.topMargin = (int) getSafeResources().getDimension(R.dimen.top_bar_height); else lp.topMargin = 0; headerView.setLayoutParams(lp); lp = (ViewGroup.MarginLayoutParams) backlogFailed.getLayoutParams(); if (adapter.getLastSeenEIDPosition() == 0) lp.topMargin = (int) getSafeResources().getDimension(R.dimen.top_bar_height); else lp.topMargin = 0; backlogFailed.setLayoutParams(lp); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; if (events != null && events.size() > 0) { int markerPos = adapter.getBacklogMarkerPosition(); if (markerPos != -1 && requestingBacklog) getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight()); else if (!buffer.getScrolledUp()) getListView().setSelection(adapter.getCount() - 1); else { getListView().setSelectionFromTop(buffer.getScrollPosition(), buffer.getScrollPositionOffset()); if (adapter.getLastSeenEIDPosition() > buffer.getScrollPosition()) { newMsgs = 0; newHighlights = 0; for (int i = adapter.data.size() - 1; i >= 0; i--) { Event e = adapter.data.get(i); if (e.eid <= buffer.getLast_seen_eid()) break; if (e.isImportant(buffer.getType())) { if (e.highlight) newHighlights++; else newMsgs++; } } } update_unread(); } } new FormatTask().execute((Void) null); } catch (IllegalStateException e) { //The list view isn't on screen anymore NetworkConnection.printStackTraceToCrashlytics(e); } refreshTask = null; requestingBacklog = false; mHandler.postDelayed(new Runnable() { @Override public void run() { try { update_top_unread(getListView().getFirstVisiblePosition()); } catch (IllegalStateException e) { //List view not ready yet } if (server != null) update_status(server.getStatus(), server.getFail_info()); if (mListener != null && !ready) mListener.onMessageViewReady(); ready = true; try { ListView v = getListView(); mOnScrollListener.onScroll(v, v.getFirstVisiblePosition(), v.getLastVisiblePosition() - v.getFirstVisiblePosition(), adapter.getCount()); } catch (Exception e) { } } }, 250); //Debug.stopMethodTracing(); } } } private synchronized void refresh(MessageAdapter adapter, TreeMap<Long, Event> events) { pref_24hr = false; pref_seconds = false; pref_trackUnread = true; pref_timeLeft = false; pref_nickColors = false; pref_hideJoinPart = false; pref_expandJoinPart = false; pref_avatarsOff = false; pref_chatOneLine = false; pref_norealname = false; pref_compact = false; if (NetworkConnection.getInstance().getUserInfo() != null && NetworkConnection.getInstance().getUserInfo().prefs != null) { try { JSONObject prefs = NetworkConnection.getInstance().getUserInfo().prefs; pref_compact = (prefs.has("ascii-compact") && prefs.get("ascii-compact") instanceof Boolean && prefs.getBoolean("ascii-compact")); pref_24hr = (prefs.has("time-24hr") && prefs.get("time-24hr") instanceof Boolean && prefs.getBoolean("time-24hr")); pref_seconds = (prefs.has("time-seconds") && prefs.get("time-seconds") instanceof Boolean && prefs.getBoolean("time-seconds")); pref_timeLeft = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("time-left", true); pref_nickColors = (prefs.has("nick-colors") && prefs.get("nick-colors") instanceof Boolean && prefs.getBoolean("nick-colors")); pref_avatarsOff = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("avatars-off", true); pref_chatOneLine = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("chat-oneline", true); pref_norealname = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("chat-norealname", true); if(prefs.has("channel-disableTrackUnread")) { JSONObject disabledMap = prefs.getJSONObject("channel-disableTrackUnread"); if (disabledMap.has(String.valueOf(buffer.getBid())) && disabledMap.getBoolean(String.valueOf(buffer.getBid()))) { pref_trackUnread = false; } } JSONObject hiddenMap = null; if (buffer.isChannel()) { if (prefs.has("channel-hideJoinPart")) hiddenMap = prefs.getJSONObject("channel-hideJoinPart"); } else { if (prefs.has("buffer-hideJoinPart")) hiddenMap = prefs.getJSONObject("buffer-hideJoinPart"); } pref_hideJoinPart = (prefs.has("hideJoinPart") && prefs.get("hideJoinPart") instanceof Boolean && prefs.getBoolean("hideJoinPart")) || (hiddenMap != null && hiddenMap.has(String.valueOf(buffer.getBid())) && hiddenMap.getBoolean(String.valueOf(buffer.getBid()))); JSONObject expandMap = null; if (buffer.isChannel()) { if (prefs.has("channel-expandJoinPart")) expandMap = prefs.getJSONObject("channel-expandJoinPart"); } else if (buffer.isConsole()) { if (prefs.has("buffer-expandDisco")) expandMap = prefs.getJSONObject("buffer-expandDisco"); } else { if (prefs.has("buffer-expandJoinPart")) expandMap = prefs.getJSONObject("buffer-expandJoinPart"); } pref_expandJoinPart = ((prefs.has("expandJoinPart") && prefs.get("expandJoinPart") instanceof Boolean && prefs.getBoolean("expandJoinPart")) || (expandMap != null && expandMap.has(String.valueOf(buffer.getBid())) && expandMap.getBoolean(String.valueOf(buffer.getBid())))); } catch (JSONException e1) { NetworkConnection.printStackTraceToCrashlytics(e1); } } synchronized (adapterLock) { if (getActivity() != null) textSize = PreferenceManager.getDefaultSharedPreferences(getActivity()).getInt("textSize", getActivity().getResources().getInteger(R.integer.default_text_size)); timestamp_width = -1; if (conn.getReconnectTimestamp() == 0) conn.cancel_idle_timer(); //This may take a while... collapsedEvents.clear(); currentCollapsedEid = -1; lastCollapsedDay = -1; if (events == null || (events.size() == 0 && buffer.getMin_eid() > 0)) { if (buffer != null && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { requestingBacklog = true; runOnUiThread(new Runnable() { @Override public void run() { conn.request_backlog(buffer.getCid(), buffer.getBid(), 0); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } } else if (events.size() > 0) { if (server != null) { ignore.setIgnores(server.ignores); } else { ignore.setIgnores(null); } collapsedEvents.setServer(server); earliest_eid = events.firstKey(); if (events.size() > 0) { avgInsertTime = 0; //Debug.startMethodTracing("refresh"); long start = System.currentTimeMillis(); Iterator<Event> i = events.values().iterator(); Event next = i.next(); Calendar calendar = Calendar.getInstance(); while (next != null) { Event e = next; next = i.hasNext() ? i.next() : null; String type = (next == null) ? "" : next.type; if (next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) { calendar.setTimeInMillis(next.getTime()); insertEvent(adapter, e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay); } else { insertEvent(adapter, e, true, false); } } adapter.insertLastSeenEIDMarker(); Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms"); //Debug.stopMethodTracing(); avgInsertTime = 0; //adapter.notifyDataSetChanged(); if (events.firstKey() > buffer.getMin_eid() && buffer.getMin_eid() > 0 && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.VISIBLE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } } } if (conn.getReconnectTimestamp() == 0 && conn.getState() == NetworkConnection.STATE_CONNECTED) conn.schedule_idle_timer(); } } private void update_top_unread(int first) { if (adapter != null && buffer != null) { try { int markerPos = adapter.getLastSeenEIDPosition(); if (markerPos >= 0 && first > (markerPos + 1) && buffer.getUnread() > 0) { if (pref_trackUnread) { int highlights = adapter.getUnreadHighlightsAbovePosition(first); int count = (first - markerPos - 1) - highlights; StringBuilder txt = new StringBuilder(); if (highlights > 0) { if (highlights == 1) txt.append("mention"); else if (highlights > 0) txt.append("mentions"); highlightsTopLabel.setText(String.valueOf(highlights)); highlightsTopLabel.setVisibility(View.VISIBLE); if (count > 0) txt.append(" and "); } else { highlightsTopLabel.setVisibility(View.GONE); } if (markerPos == 0) { long seconds = (long) Math.ceil((earliest_eid - buffer.getLast_seen_eid()) / 1000000.0); if (seconds < 0) { if (count < 0) { hideView(unreadTopView); return; } else { if (count == 1) txt.append(count).append(" unread message"); else if (count > 0) txt.append(count).append(" unread messages"); } } else { int minutes = (int) Math.ceil(seconds / 60.0); int hours = (int) Math.ceil(seconds / 60.0 / 60.0); int days = (int) Math.ceil(seconds / 60.0 / 60.0 / 24.0); if (hours >= 24) { if (days == 1) txt.append(days).append(" day of unread messages"); else txt.append(days).append(" days of unread messages"); } else if (hours > 0) { if (hours == 1) txt.append(hours).append(" hour of unread messages"); else txt.append(hours).append(" hours of unread messages"); } else if (minutes > 0) { if (minutes == 1) txt.append(minutes).append(" minute of unread messages"); else txt.append(minutes).append(" minutes of unread messages"); } else { if (seconds == 1) txt.append(seconds).append(" second of unread messages"); else txt.append(seconds).append(" seconds of unread messages"); } } } else { if (count == 1) txt.append(count).append(" unread message"); else if (count > 0) txt.append(count).append(" unread messages"); } unreadTopLabel.setText(txt); showView(unreadTopView); } else { hideView(unreadTopView); } } else { if (markerPos > 0) { hideView(unreadTopView); if (adapter.data.size() > 0 && ready) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } } } } catch (IllegalStateException e) { //The list view wasn't on screen yet NetworkConnection.printStackTraceToCrashlytics(e); } } } private class UnreadRefreshRunnable implements Runnable { @Override public void run() { update_unread(); } } UnreadRefreshRunnable unreadRefreshRunnable = null; private void update_unread() { if (unreadRefreshRunnable != null) { mHandler.removeCallbacks(unreadRefreshRunnable); unreadRefreshRunnable = null; } if (newMsgs > 0) { /*int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000); if(minutes < 1) unreadBottomLabel.setText("Less than a minute of chatter ("); else if(minutes == 1) unreadBottomLabel.setText("1 minute of chatter ("); else unreadBottomLabel.setText(minutes + " minutes of chatter ("); if(newMsgs == 1) unreadBottomLabel.setText(unreadBottomLabel.getText() + "1 message)"); else unreadBottomLabel.setText(unreadBottomLabel.getText() + (newMsgs + " messages)"));*/ String txt = ""; int msgCnt = newMsgs - newHighlights; if (newHighlights > 0) { if (newHighlights == 1) txt = "mention"; else txt = "mentions"; if (msgCnt > 0) txt += " and "; highlightsBottomLabel.setText(String.valueOf(newHighlights)); highlightsBottomLabel.setVisibility(View.VISIBLE); } else { highlightsBottomLabel.setVisibility(View.GONE); } if (msgCnt == 1) txt += msgCnt + " unread message"; else if (msgCnt > 0) txt += msgCnt + " unread messages"; unreadBottomLabel.setText(txt); showView(unreadBottomView); unreadRefreshRunnable = new UnreadRefreshRunnable(); mHandler.postDelayed(unreadRefreshRunnable, 10000); } } private class StatusRefreshRunnable implements Runnable { String status; JsonNode fail_info; public StatusRefreshRunnable(String status, JsonNode fail_info) { this.status = status; this.fail_info = fail_info; } @Override public void run() { update_status(status, fail_info); } } StatusRefreshRunnable statusRefreshRunnable = null; public static String ordinal(int i) { String[] sufixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; switch (i % 100) { case 11: case 12: case 13: return i + "th"; default: return i + sufixes[i % 10]; } } private String reason_txt(String reason) { String r = reason; switch (reason.toLowerCase()) { case "pool_lost": r = "Connection pool failed"; case "no_pool": r = "No available connection pools"; break; case "enetdown": r = "Network down"; break; case "etimedout": case "timeout": r = "Timed out"; break; case "ehostunreach": r = "Host unreachable"; break; case "econnrefused": r = "Connection refused"; break; case "nxdomain": case "einval": r = "Invalid hostname"; break; case "server_ping_timeout": r = "PING timeout"; break; case "ssl_certificate_error": r = "SSL certificate error"; break; case "ssl_error": r = "SSL error"; break; case "crash": r = "Connection crashed"; break; case "networks": r = "You've exceeded the connection limit for free accounts."; break; case "passworded_servers": r = "You can't connect to passworded servers with free accounts."; break; case "unverified": r = "You can’t connect to external servers until you confirm your email address."; break; } return r; } private void update_status(String status, JsonNode fail_info) { if (statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } statusView.setTextColor(colorScheme.connectionBarTextColor); statusView.setBackgroundColor(colorScheme.connectionBarColor); switch (status) { case "connected_ready": statusView.setVisibility(View.GONE); statusView.setText(""); break; case "quitting": statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnecting"); break; case "disconnected": statusView.setVisibility(View.VISIBLE); if (fail_info.has("type") && fail_info.get("type").asText().length() > 0) { String text = "Disconnected: "; if (fail_info.get("type").asText().equals("connecting_restricted")) { text = reason_txt(fail_info.get("reason").asText()); if (text.equals(fail_info.get("reason").asText())) text = "You can’t connect to this server with a free account."; } else if (fail_info.get("type").asText().equals("connection_blocked")) { text = "Disconnected - Connections to this server have been blocked"; } else { if (fail_info.has("type") && fail_info.get("type").asText().equals("killed")) text = "Disconnected - Killed: "; else if (fail_info.has("type") && fail_info.get("type").asText().equals("connecting_failed")) text = "Disconnected: Failed to connect - "; if (fail_info.has("reason")) text += reason_txt(fail_info.get("reason").asText()); } statusView.setText(text); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); } else { statusView.setText("Disconnected. Tap to reconnect."); } break; case "queued": statusView.setVisibility(View.VISIBLE); statusView.setText("Connection queued"); break; case "connecting": statusView.setVisibility(View.VISIBLE); statusView.setText("Connecting"); break; case "connected": statusView.setVisibility(View.VISIBLE); statusView.setText("Connected"); break; case "connected_joining": statusView.setVisibility(View.VISIBLE); statusView.setText("Connected: Joining Channels"); break; case "pool_unavailable": statusView.setVisibility(View.VISIBLE); statusView.setText("Connection temporarily unavailable"); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); break; case "waiting_to_retry": try { statusView.setVisibility(View.VISIBLE); long seconds = (fail_info.get("timestamp").asLong() + fail_info.get("retry_timeout").asLong() - conn.clockOffset) - System.currentTimeMillis() / 1000; if (seconds > 0) { String text = "Disconnected"; if (fail_info.has("reason") && fail_info.get("reason").asText().length() > 0) { String reason = fail_info.get("reason").asText(); reason = reason_txt(reason); text += ": " + reason + ". "; } else text += "; "; text += "Reconnecting in "; int minutes = (int) (seconds / 60.0); int hours = (int) (seconds / 60.0 / 60.0); int days = (int) (seconds / 60.0 / 60.0 / 24.0); if (days > 0) { if (days == 1) text += days + " day."; else text += days + " days."; } else if (hours > 0) { if (hours == 1) text += hours + " hour."; else text += hours + " hours."; } else if (minutes > 0) { if (minutes == 1) text += minutes + " minute."; else text += minutes + " minutes."; } else { if (seconds == 1) text += seconds + " second."; else text += seconds + " seconds."; } int attempts = fail_info.get("attempts").asInt(); if (attempts > 1) text += " (" + ordinal(attempts) + " attempt)"; statusView.setText(text); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info); } else { statusView.setVisibility(View.VISIBLE); statusView.setText("Ready to connect, waiting our turn…"); } mHandler.postDelayed(statusRefreshRunnable, 500); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); } break; case "ip_retry": statusView.setVisibility(View.VISIBLE); statusView.setText("Trying another IP address"); break; } } private void update_global_msg() { if (globalMsgView != null) { if (conn != null && conn.globalMsg != null) { globalMsg.setText(Html.fromHtml(conn.globalMsg)); globalMsgView.setVisibility(View.VISIBLE); } else { globalMsgView.setVisibility(View.GONE); } } } @Override public void onPause() { super.onPause(); if(getActivity() == null || !((BaseActivity)getActivity()).isMultiWindow()) { if (statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } try { getListView().setOnScrollListener(null); } catch (Exception e) { } ready = false; } } public void onIRCEvent(int what, final Object obj) { IRCCloudJSONObject e; switch (what) { case NetworkConnection.EVENT_BACKLOG_FAILED: runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.VISIBLE); loadBacklogButton.setVisibility(View.VISIBLE); } }); break; case NetworkConnection.EVENT_BACKLOG_END: case NetworkConnection.EVENT_CONNECTIVITY: case NetworkConnection.EVENT_USERINFO: if(buffer != null) { runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } break; case NetworkConnection.EVENT_CONNECTIONLAG: try { IRCCloudJSONObject object = (IRCCloudJSONObject) obj; if (server != null && buffer != null && object.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { update_status(server.getStatus(), server.getFail_info()); } }); } } catch (Exception ex) { NetworkConnection.printStackTraceToCrashlytics(ex); } break; case NetworkConnection.EVENT_STATUSCHANGED: try { final IRCCloudJSONObject object = (IRCCloudJSONObject) obj; if (buffer != null && object.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { update_status(object.getString("new_status"), object.getJsonObject("fail_info")); } }); } } catch (Exception ex) { NetworkConnection.printStackTraceToCrashlytics(ex); } break; case NetworkConnection.EVENT_SETIGNORES: e = (IRCCloudJSONObject) obj; if (buffer != null && e.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } break; case NetworkConnection.EVENT_HEARTBEATECHO: try { if (buffer != null && adapter != null && adapter.data.size() > 0) { if (buffer.getLast_seen_eid() == adapter.data.get(adapter.data.size() - 1).eid || !pref_trackUnread) { runOnUiThread(new Runnable() { @Override public void run() { hideView(unreadTopView); } }); } } } catch (Exception ex) { } break; case NetworkConnection.EVENT_CHANNELTOPIC: case NetworkConnection.EVENT_JOIN: case NetworkConnection.EVENT_PART: case NetworkConnection.EVENT_NICKCHANGE: case NetworkConnection.EVENT_QUIT: case NetworkConnection.EVENT_KICK: case NetworkConnection.EVENT_CHANNELMODE: case NetworkConnection.EVENT_USERMODE: case NetworkConnection.EVENT_USERCHANNELMODE: e = (IRCCloudJSONObject) obj; if (buffer != null && e.bid() == buffer.getBid()) { final Event event = EventsList.getInstance().getEvent(e.eid(), e.bid()); runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null) insertEvent(adapter, event, false, false); } }); } break; case NetworkConnection.EVENT_SELFDETAILS: case NetworkConnection.EVENT_BUFFERMSG: final Event event = (Event) obj; if (buffer != null && event.bid == buffer.getBid()) { if (event.from != null && event.from.equalsIgnoreCase(buffer.getName()) && event.reqid == -1) { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null) adapter.clearPending(); } }); } else if (event.reqid != -1) { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null && adapter.data != null) { for (int i = 0; i < adapter.data.size(); i++) { Event e = adapter.data.get(i); if (e.reqid == event.reqid && e.pending) { if (i > 0) { Event p = adapter.data.get(i - 1); if (p.row_type == ROW_TIMESTAMP) { adapter.data.remove(p); i--; } } adapter.data.remove(e); i--; } } } } }); } runOnUiThread(new Runnable() { @Override public void run() { insertEvent(adapter, event, false, false); } }); if (event.pending && event.self && adapter != null && getListView() != null) { runOnUiThread(new Runnable() { @Override public void run() { getListView().setSelection(adapter.getCount() - 1); } }); } } Buffer b = BuffersList.getInstance().getBuffer(event.bid); if (b != null && !b.getScrolledUp() && EventsList.getInstance().getSizeOfBuffer(b.getBid()) > 200) { EventsList.getInstance().pruneEvents(b.getBid()); if (buffer != null && b.getBid() == buffer.getBid()) { if (b.getLast_seen_eid() < event.eid && unreadTopView.getVisibility() == View.GONE) b.setLast_seen_eid(event.eid); runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } } break; case NetworkConnection.EVENT_AWAY: case NetworkConnection.EVENT_SELFBACK: if (server != null) { runOnUiThread(new Runnable() { @Override public void run() { if (server.getAway() != null && server.getAway().length() > 0) { awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.getAway() + ")"))).toString()); awayView.setVisibility(View.VISIBLE); } else { awayView.setVisibility(View.GONE); } } }); } break; case NetworkConnection.EVENT_GLOBALMSG: runOnUiThread(new Runnable() { @Override public void run() { update_global_msg(); } }); break; default: break; } } @Override public void onIRCRequestSucceeded(int reqid, IRCCloudJSONObject object) { } @Override public void onIRCRequestFailed(int reqid, IRCCloudJSONObject object) { } public static Resources getSafeResources() { return IRCCloudApplication.getInstance().getApplicationContext().getResources(); } public interface MessageViewListener extends OnBufferSelectedListener { public void onMessageViewReady(); public boolean onMessageLongClicked(Event event); public void onMessageDoubleClicked(Event event); public void onFailedMessageClicked(Event event); } }
src/com/irccloud/android/fragment/MessageViewFragment.java
/* * Copyright (c) 2015 IRCCloud, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.irccloud.android.fragment; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v4.app.ListFragment; import android.support.v4.widget.DrawerLayout; import android.text.Html; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.style.ImageSpan; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.fasterxml.jackson.databind.JsonNode; import com.irccloud.android.AsyncTaskEx; import com.irccloud.android.CollapsedEventsList; import com.irccloud.android.ColorFormatter; import com.irccloud.android.ColorScheme; import com.irccloud.android.FontAwesome; import com.irccloud.android.IRCCloudApplication; import com.irccloud.android.IRCCloudJSONObject; import com.irccloud.android.IRCCloudLinkMovementMethod; import com.irccloud.android.Ignore; import com.irccloud.android.NetworkConnection; import com.irccloud.android.OffsetLinearLayout; import com.irccloud.android.R; import com.irccloud.android.activity.BaseActivity; import com.irccloud.android.data.collection.AvatarsList; import com.irccloud.android.data.model.Avatar; import com.irccloud.android.data.model.Buffer; import com.irccloud.android.data.collection.BuffersList; import com.irccloud.android.data.model.Event; import com.irccloud.android.data.collection.EventsList; import com.irccloud.android.data.model.Server; import com.irccloud.android.fragment.BuffersListFragment.OnBufferSelectedListener; import com.squareup.leakcanary.RefWatcher; import org.json.JSONException; import org.json.JSONObject; import java.lang.ref.WeakReference; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import java.util.TreeSet; public class MessageViewFragment extends ListFragment implements NetworkConnection.IRCEventHandler { private NetworkConnection conn; private TextView statusView; private View headerViewContainer; private View headerView; private View footerViewContainer; private TextView backlogFailed; private Button loadBacklogButton; private TextView unreadTopLabel; private TextView unreadBottomLabel; private View unreadTopView; private View unreadBottomView; private TextView highlightsTopLabel; private TextView highlightsBottomLabel; public ImageView avatar; private AvatarsList mAvatarsList = AvatarsList.getInstance(); private OffsetLinearLayout avatarContainer; public Buffer buffer; private Server server; private long earliest_eid; private long backlog_eid = 0; private boolean requestingBacklog = false; private float avgInsertTime = 0; private int newMsgs = 0; private long newMsgTime = 0; private int newHighlights = 0; private MessageViewListener mListener; private View awayView = null; private TextView awayTxt = null; private int timestamp_width = -1; private float textSize = 14.0f; private View globalMsgView = null; private TextView globalMsg = null; private ProgressBar spinner = null; private final Handler mHandler = new Handler(); private ColorScheme colorScheme = ColorScheme.getInstance(); private Typeface hackRegular; public static final int ROW_MESSAGE = 0; public static final int ROW_TIMESTAMP = 1; public static final int ROW_BACKLOGMARKER = 2; public static final int ROW_SOCKETCLOSED = 3; public static final int ROW_LASTSEENEID = 4; private static final String TYPE_TIMESTAMP = "__timestamp__"; private static final String TYPE_BACKLOGMARKER = "__backlog__"; private static final String TYPE_LASTSEENEID = "__lastseeneid__"; private MessageAdapter adapter; private long currentCollapsedEid = -1; private long lastCollapsedEid = -1; private CollapsedEventsList collapsedEvents = new CollapsedEventsList(); private int lastCollapsedDay = -1; private HashSet<Long> expandedSectionEids = new HashSet<Long>(); private RefreshTask refreshTask = null; private HeartbeatTask heartbeatTask = null; private Ignore ignore = new Ignore(); private static Timer tapTimer = null; private TimerTask tapTimerTask = null; public boolean longPressOverride = false; private LinkMovementMethodNoLongPress linkMovementMethodNoLongPress = new LinkMovementMethodNoLongPress(); public boolean ready = false; private final Object adapterLock = new Object(); public View suggestionsContainer = null; public GridView suggestions = null; private boolean pref_24hr = false; private boolean pref_seconds = false; private boolean pref_trackUnread = true; private boolean pref_timeLeft = false; private boolean pref_nickColors = false; private boolean pref_hideJoinPart = false; private boolean pref_expandJoinPart = false; private boolean pref_avatarsOff = false; private boolean pref_chatOneLine = false; private boolean pref_norealname = false; private boolean pref_compact = false; private class LinkMovementMethodNoLongPress extends IRCCloudLinkMovementMethod { @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (!longPressOverride && (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN)) { return super.onTouchEvent(widget, buffer, event); } return false; } } private class MessageAdapter extends BaseAdapter { final ArrayList<Event> data; private ListFragment ctx; private long max_eid = 0; private long min_eid = 0; private int lastDay = -1; private int lastSeenEidMarkerPosition = -1; private int currentGroupPosition = -1; private TreeSet<Integer> unseenHighlightPositions; private class ViewHolder { int type; LinearLayout lastSeenEidWrapper; LinearLayout messageContainer; LinearLayout socketClosedBar; TextView timestamp; TextView timestamp_left; TextView timestamp_right; TextView message; TextView expandable; TextView nickname; TextView realname; ImageView failed; ImageView avatar; } public MessageAdapter(ListFragment context, int capacity) { ctx = context; data = new ArrayList<>(capacity + 10); unseenHighlightPositions = new TreeSet<>(Collections.reverseOrder()); } public void clear() { max_eid = 0; min_eid = 0; lastDay = -1; lastSeenEidMarkerPosition = -1; currentGroupPosition = -1; synchronized (data) { data.clear(); } unseenHighlightPositions.clear(); avatarContainer.setVisibility(View.GONE); avatar.setTag(null); } public void clearPending() { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).reqid != -1 && data.get(i).color == colorScheme.timestampColor) { data.remove(i); i--; } } } } public void removeItem(long eid) { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).eid == eid) { data.remove(i); i--; } } } } public int getBacklogMarkerPosition() { try { synchronized (data) { for (int i = 0; i < data.size(); i++) { Event e = data.get(i); if (e != null && e.row_type == ROW_BACKLOGMARKER) { return i; } } } } catch (Exception e) { } return -1; } public int insertLastSeenEIDMarker() { if (buffer == null) return -1; synchronized (data) { if (min_eid > 0 && buffer.getLast_seen_eid() > 0 && min_eid >= buffer.getLast_seen_eid()) { lastSeenEidMarkerPosition = 0; } else { for (int i = data.size() - 1; i >= 0; i--) { if (data.get(i).eid <= buffer.getLast_seen_eid() && data.get(i).row_type != ROW_LASTSEENEID) { lastSeenEidMarkerPosition = i; break; } } if (lastSeenEidMarkerPosition > 0 && lastSeenEidMarkerPosition != data.size() - 1 && !data.get(lastSeenEidMarkerPosition).self && !data.get(lastSeenEidMarkerPosition).pending) { if (data.get(lastSeenEidMarkerPosition - 1).row_type == ROW_TIMESTAMP) lastSeenEidMarkerPosition--; if (lastSeenEidMarkerPosition > 0) { Event e = new Event(); e.bid = buffer.getBid(); e.cid = buffer.getCid(); e.eid = buffer.getLast_seen_eid() + 1; e.type = TYPE_LASTSEENEID; e.row_type = ROW_LASTSEENEID; if(EventsList.getInstance().getEvent(buffer.getLast_seen_eid(), buffer.getBid()) != null) e.from = EventsList.getInstance().getEvent(buffer.getLast_seen_eid(), buffer.getBid()).from; e.bg_color = colorScheme.socketclosedBackgroundDrawable; addItem(e.eid, e); EventsList.getInstance().addEvent(e); for (int i = 0; i < data.size(); i++) { if (data.get(i).row_type == ROW_LASTSEENEID && data.get(i) != e) { EventsList.getInstance().deleteEvent(data.get(i).eid, buffer.getBid()); data.remove(i); } } } } else { lastSeenEidMarkerPosition = -1; } } if (lastSeenEidMarkerPosition > 0 && lastSeenEidMarkerPosition <= currentGroupPosition) currentGroupPosition++; if (lastSeenEidMarkerPosition == -1) { for (int i = data.size() - 1; i >= 0; i--) { if (data.get(i).row_type == ROW_LASTSEENEID) { lastSeenEidMarkerPosition = i; break; } } } } return lastSeenEidMarkerPosition; } public void clearLastSeenEIDMarker() { if(buffer != null) { synchronized (data) { for (int i = 0; i < data.size(); i++) { if (data.get(i).row_type == ROW_LASTSEENEID) { EventsList.getInstance().deleteEvent(data.get(i).eid, buffer.getBid()); data.remove(i); } } } if (lastSeenEidMarkerPosition > 0) lastSeenEidMarkerPosition = -1; } } public int getLastSeenEIDPosition() { return lastSeenEidMarkerPosition; } public int getUnreadHighlightsAbovePosition(int pos) { int count = 0; Iterator<Integer> i = unseenHighlightPositions.iterator(); while (i.hasNext()) { Integer p = i.next(); if (p < pos) break; count++; } return unseenHighlightPositions.size() - count; } public synchronized void addItem(long eid, Event e) { synchronized (data) { Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(e.getTime()); int insert_pos = -1; SimpleDateFormat formatter = null; if (e.timestamp == null || e.timestamp.length() == 0) { formatter = new SimpleDateFormat("h:mm a"); if (pref_24hr) { if (pref_seconds) formatter = new SimpleDateFormat("HH:mm:ss"); else formatter = new SimpleDateFormat("HH:mm"); } else if (pref_seconds) { formatter = new SimpleDateFormat("h:mm:ss a"); } e.timestamp = formatter.format(calendar.getTime()); } e.group_eid = currentCollapsedEid; if (e.group_msg != null && e.html == null) e.html = e.group_msg; /*if(e.html != null) { e.html = ColorFormatter.irc_to_html(e.html); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server); }*/ if (e.day < 1) { e.day = calendar.get(Calendar.DAY_OF_YEAR); } if (currentGroupPosition > 0 && eid == currentCollapsedEid && e.eid != eid) { //Shortcut for replacing the current group calendar.setTimeInMillis(e.getTime()); lastDay = e.day; data.remove(currentGroupPosition); data.add(currentGroupPosition, e); insert_pos = currentGroupPosition; } else if (eid > max_eid || data.size() == 0 || eid > data.get(data.size() - 1).eid) { //Message at the bottom if (data.size() > 0) { lastDay = data.get(data.size() - 1).day; } else { lastDay = 0; } max_eid = eid; data.add(e); insert_pos = data.size() - 1; } else if (min_eid > eid) { //Message goes on top if (data.size() > 1) { lastDay = data.get(1).day; if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline data.add(0, e); insert_pos = 0; } else { //Insert below the dateline data.add(1, e); insert_pos = 1; } } else { data.add(0, e); insert_pos = 0; } } else { int i = 0; for (Event e1 : data) { if (e1.row_type != ROW_TIMESTAMP && e1.eid > eid && e.eid == eid && e1.group_eid != eid) { //Insert the message if (i > 0 && data.get(i - 1).row_type != ROW_TIMESTAMP) { lastDay = data.get(i - 1).day; data.add(i, e); insert_pos = i; break; } else { //There was a date line above our insertion point lastDay = e1.day; if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { //Insert above the dateline if (i > 1) { lastDay = data.get(i - 2).day; } else { //We're above the first dateline, so we'll need to put a new one on top! lastDay = 0; } data.add(i - 1, e); insert_pos = i - 1; } else { //Insert below the dateline data.add(i, e); insert_pos = i; } break; } } else if (e1.row_type != ROW_TIMESTAMP && (e1.eid == eid || e1.group_eid == eid)) { //Replace the message lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.remove(i); data.add(i, e); insert_pos = i; break; } i++; } } if (insert_pos == -1) { Log.e("IRCCloud", "Couldn't insert EID: " + eid + " MSG: " + e.html); data.add(e); insert_pos = data.size() - 1; } if (eid > buffer.getLast_seen_eid() && e.highlight) unseenHighlightPositions.add(insert_pos); if (eid < min_eid || min_eid == 0) min_eid = eid; if (eid == currentCollapsedEid && e.eid == eid) { currentGroupPosition = insert_pos; } else if (currentCollapsedEid == -1) { currentGroupPosition = -1; } if (calendar.get(Calendar.DAY_OF_YEAR) != lastDay) { if (formatter == null) formatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); else formatter.applyPattern("EEEE, MMMM dd, yyyy"); Event d = new Event(); d.type = TYPE_TIMESTAMP; d.row_type = ROW_TIMESTAMP; d.eid = eid - 1; d.timestamp = formatter.format(calendar.getTime()); d.bg_color = colorScheme.timestampBackgroundDrawable; d.day = lastDay = calendar.get(Calendar.DAY_OF_YEAR); data.add(insert_pos++, d); if (currentGroupPosition > -1) currentGroupPosition++; } if (insert_pos > 0) { Event prev = data.get(insert_pos - ((e.row_type == ROW_LASTSEENEID)?2:1)); e.header = (e.isMessage() && e.from != null && e.from.length() > 0 && e.group_eid < 1) && (prev.from == null || !prev.from.equals(e.from) || !prev.type.equals(e.type)); } if (insert_pos < (data.size() - 1)) { Event next = data.get(insert_pos + 1); if (!e.isMessage() && e.row_type != ROW_LASTSEENEID) { next.header = (next.isMessage() && next.from != null && next.from.length() > 0 && next.group_eid < 1); } if (next.from != null && next.from.equals(e.from) && next.type.equals(e.type)) { next.header = false; } } } } @Override public int getCount() { synchronized (data) { if (ctx != null) return data.size(); else return 0; } } @Override public Object getItem(int position) { synchronized (data) { if (position < data.size()) return data.get(position); else return null; } } @Override public long getItemId(int position) { synchronized (data) { if (position < data.size()) return data.get(position).eid; else return -1; } } public void format() { for (int i = 0; i < data.size(); i++) { Event e = data.get(i); if (e != null) { synchronized (e) { if (e.html != null) { try { e.html = ColorFormatter.emojify(ColorFormatter.irc_to_html(e.html)); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server, e.entities); if (e.msg != null && e.msg.length() > 0) e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString(); if (e.from != null && e.from.length() > 0) { e.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(e.from, e.from_mode, !e.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (e.formatted_realname == null && e.from_realname != null && e.from_realname.length() > 0) { e.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(e.from_realname)), true, null); } } catch (Exception ex) { } } } } } } @Override public int getItemViewType(int position) { synchronized (data) { return data.get(position).row_type; } } @Override public View getView(int position, View convertView, ViewGroup parent) { if (position >= data.size() || ctx == null) return null; Event e; synchronized (data) { e = data.get(position); } synchronized (e) { View row = convertView; ViewHolder holder; if (row != null && ((ViewHolder) row.getTag()).type != e.row_type) row = null; if (row == null) { LayoutInflater inflater = ctx.getLayoutInflater(null); if (e.row_type == ROW_BACKLOGMARKER) row = inflater.inflate(R.layout.row_backlogmarker, parent, false); else if (e.row_type == ROW_TIMESTAMP) row = inflater.inflate(R.layout.row_timestamp, parent, false); else if (e.row_type == ROW_SOCKETCLOSED) row = inflater.inflate(R.layout.row_socketclosed, parent, false); else if (e.row_type == ROW_LASTSEENEID) row = inflater.inflate(R.layout.row_lastseeneid, parent, false); else row = inflater.inflate(R.layout.row_message, parent, false); holder = new ViewHolder(); holder.timestamp = (TextView) row.findViewById(R.id.timestamp); holder.timestamp_left = (TextView) row.findViewById(R.id.timestamp_left); holder.timestamp_right = (TextView) row.findViewById(R.id.timestamp_right); holder.message = (TextView) row.findViewById(R.id.message); holder.expandable = (TextView) row.findViewById(R.id.expandable); if(holder.expandable != null) holder.expandable.setTypeface(FontAwesome.getTypeface()); holder.nickname = (TextView) row.findViewById(R.id.nickname); holder.realname = (TextView) row.findViewById(R.id.realname); holder.failed = (ImageView) row.findViewById(R.id.failed); holder.avatar = (ImageView) row.findViewById(R.id.avatar); holder.lastSeenEidWrapper = (LinearLayout) row.findViewById(R.id.lastSeenEidWrapper); holder.messageContainer = (LinearLayout) row.findViewById(R.id.messageContainer); holder.socketClosedBar = (LinearLayout) row.findViewById(R.id.socketClosedBar); holder.type = e.row_type; row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } row.setOnClickListener(new OnItemClickListener(position)); row.setOnLongClickListener(new OnItemLongClickListener(position)); if (e.html != null && e.formatted == null) { e.html = ColorFormatter.emojify(ColorFormatter.irc_to_html(e.html)); e.formatted = ColorFormatter.html_to_spanned(e.html, e.linkify, server, e.entities); if (e.msg != null && e.msg.length() > 0) e.contentDescription = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(e.msg), e.linkify, server).toString(); } if (e.formatted_nick == null && e.from != null && e.from.length() > 0) { e.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(e.from, e.from_mode, !e.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (e.formatted_realname == null && e.from_realname != null && e.from_realname.length() > 0) { e.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(e.from_realname)), true, null); } if (e.row_type == ROW_MESSAGE) { if (e.bg_color == colorScheme.contentBackgroundColor) row.setBackgroundDrawable(null); else row.setBackgroundColor(e.bg_color); if (e.contentDescription != null && e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) { row.setContentDescription("Message from " + e.from + " at " + e.timestamp + ": " + e.contentDescription); } } boolean mono = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("monospace", false); if(holder.timestamp_left != null) { if(pref_timeLeft && (pref_chatOneLine || pref_avatarsOff)) { holder.timestamp_left.setVisibility(View.VISIBLE); holder.timestamp_right.setVisibility(View.GONE); holder.timestamp = holder.timestamp_left; } else { holder.timestamp_left.setVisibility(View.GONE); holder.timestamp_right.setVisibility(View.VISIBLE); holder.timestamp = holder.timestamp_right; } } if (holder.timestamp != null) { holder.timestamp.setTypeface(mono ? hackRegular : Typeface.DEFAULT); if (e.row_type == ROW_TIMESTAMP) { holder.timestamp.setTextSize(textSize); } else { holder.timestamp.setTextSize(textSize - 2); if (timestamp_width == -1) { String s = " 88:88"; if (pref_seconds) s += ":88"; if (!pref_24hr) s += " MM"; timestamp_width = (int) holder.timestamp.getPaint().measureText(s); } holder.timestamp.setMinWidth(timestamp_width); } if (e.highlight && !e.self) holder.timestamp.setTextColor(colorScheme.highlightTimestampColor); else if (e.row_type != ROW_TIMESTAMP) holder.timestamp.setTextColor(colorScheme.timestampColor); holder.timestamp.setText(e.timestamp); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)holder.timestamp.getLayoutParams(); lp.topMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pref_compact?0:2, getResources().getDisplayMetrics()); } if (e.row_type == ROW_SOCKETCLOSED) { if (e.msg != null && e.msg.length() > 0) { holder.timestamp.setVisibility(View.VISIBLE); holder.message.setVisibility(View.VISIBLE); } else { holder.timestamp.setVisibility(View.GONE); holder.message.setVisibility(View.GONE); } } if (holder.message != null && e.html != null) { holder.message.setMovementMethod(linkMovementMethodNoLongPress); holder.message.setOnClickListener(new OnItemClickListener(position)); holder.message.setOnLongClickListener(new OnItemLongClickListener(position)); if (mono || (e.msg != null && e.msg.startsWith("<pre>"))) { holder.message.setTypeface(hackRegular); } else { holder.message.setTypeface(Typeface.DEFAULT); } try { holder.message.setTextColor(e.color); } catch (Exception e1) { } if (e.color == colorScheme.timestampColor || e.pending) holder.message.setLinkTextColor(colorScheme.lightLinkColor); else holder.message.setLinkTextColor(colorScheme.linkColor); if(pref_compact) holder.message.setLineSpacing(0,1); else holder.message.setLineSpacing(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()),1); Spanned formatted = e.formatted; if(formatted != null && !pref_avatarsOff && ((e.from != null && e.from.length() > 0) || e.type.equals("buffer_me_msg")) && e.group_eid < 0 && (pref_chatOneLine || e.type.equals("buffer_me_msg"))) { Bitmap b = mAvatarsList.getAvatar(e.cid, e.type.equals("buffer_me_msg")?e.nick:e.from).getBitmap(ColorScheme.getInstance().isDarkTheme, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, textSize+4, getResources().getDisplayMetrics()), e.self); if(b != null) { SpannableStringBuilder s = new SpannableStringBuilder(formatted); s.insert(0, " "); s.setSpan(new ImageSpan(getActivity(), b) { @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { Drawable b = getDrawable(); canvas.save(); canvas.translate(x, top + ((paint.getFontMetricsInt().descent - paint.getFontMetricsInt().ascent) / 2) - ((b.getBounds().bottom - b.getBounds().top) / 2) - (((int)textSize - b.getIntrinsicHeight() / 2))); b.draw(canvas); canvas.restore(); } }, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); formatted = s; } } holder.message.setText(formatted); if (e.from != null && e.from.length() > 0 && e.msg != null && e.msg.length() > 0) { holder.message.setContentDescription(e.from + ": " + e.contentDescription); } holder.message.setTextSize(textSize); } if (holder.expandable != null) { if (e.group_eid > 0 && (e.group_eid != e.eid || expandedSectionEids.contains(e.group_eid))) { if (expandedSectionEids.contains(e.group_eid)) { if (e.group_eid == e.eid + 1) { holder.expandable.setText(FontAwesome.MINUS_SQUARE_O); holder.expandable.setContentDescription("expanded"); row.setBackgroundColor(colorScheme.collapsedHeadingBackgroundColor); } else { holder.expandable.setText(FontAwesome.ANGLE_RIGHT); holder.expandable.setContentDescription("collapse"); row.setBackgroundColor(colorScheme.contentBackgroundColor); } } else { holder.expandable.setText(FontAwesome.PLUS_SQUARE_O); holder.expandable.setContentDescription("expand"); } holder.expandable.setVisibility(View.VISIBLE); } else { holder.expandable.setVisibility(View.GONE); } holder.expandable.setTextColor(colorScheme.expandCollapseIndicatorColor); } if (holder.failed != null) holder.failed.setVisibility(e.failed ? View.VISIBLE : View.GONE); if (holder.messageContainer != null) { if(pref_compact) holder.messageContainer.setPadding(0,0,0,0); else holder.messageContainer.setPadding(0,0,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics())); } if (holder.avatar != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams)holder.avatar.getLayoutParams(); if(pref_avatarsOff || pref_chatOneLine || (e.row_type == ROW_SOCKETCLOSED && (e.msg == null || e.msg.length() == 0))) { holder.avatar.setImageBitmap(null); lp.topMargin = lp.width = lp.height = 0; } else { lp.topMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()); lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 32, getResources().getDisplayMetrics()); Bitmap b = null; if (e.group_eid < 1 && e.from != null && e.from.length() > 0 && (pref_chatOneLine || e.header)) { Avatar a = mAvatarsList.getAvatar(e.cid, e.from); b = a.getBitmap(ColorScheme.getInstance().isDarkTheme, lp.width, e.self); holder.avatar.setVisibility(View.VISIBLE); holder.avatar.setTag(a); } holder.avatar.setImageBitmap(b); if(b != null) lp.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16 * ((!e.header || b == null || e.group_eid > 0)?1:2), getResources().getDisplayMetrics()); else lp.height = 0; } holder.avatar.setLayoutParams(lp); } if(!pref_chatOneLine && e.header && e.formatted_nick != null && e.formatted_nick.length() > 0 && e.group_eid < 1) { if (holder.nickname != null) { holder.nickname.setVisibility(View.VISIBLE); if (mono) holder.nickname.setTypeface(hackRegular); else holder.nickname.setTypeface(Typeface.DEFAULT); holder.nickname.setTextSize(textSize); holder.nickname.setText(e.formatted_nick); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.nickname.getLayoutParams(); lp.leftMargin = (pref_timeLeft&&pref_avatarsOff)?timestamp_width:0; holder.nickname.setLayoutParams(lp); } if (holder.realname != null) { holder.realname.setMovementMethod(linkMovementMethodNoLongPress); holder.realname.setVisibility((pref_chatOneLine || pref_norealname) ? View.GONE : View.VISIBLE); if (mono) holder.realname.setTypeface(hackRegular); else holder.realname.setTypeface(Typeface.DEFAULT); holder.realname.setTextSize(textSize); holder.realname.setTextColor(colorScheme.timestampColor); holder.realname.setText(e.formatted_realname); } } else { if (holder.nickname != null) holder.nickname.setVisibility(View.GONE); if (holder.realname != null) holder.realname.setVisibility(View.GONE); if (holder.avatar != null) holder.avatar.setVisibility((pref_avatarsOff || pref_chatOneLine) ? View.GONE : View.VISIBLE); if(holder.message != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.message.getLayoutParams(); lp.leftMargin = 0; holder.message.setLayoutParams(lp); } } if(holder.lastSeenEidWrapper != null) { ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) holder.lastSeenEidWrapper.getLayoutParams(); if(!pref_avatarsOff && !pref_chatOneLine) lp.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 48, getResources().getDisplayMetrics()); else lp.leftMargin = 0; holder.lastSeenEidWrapper.setLayoutParams(lp); holder.lastSeenEidWrapper.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, pref_compact?(textSize + 2):(textSize + 16), getResources().getDisplayMetrics())); } if(holder.socketClosedBar != null) { holder.socketClosedBar.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, textSize + 2, getResources().getDisplayMetrics())); } if(e.row_type == ROW_BACKLOGMARKER) row.setMinimumHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, pref_compact?4:(textSize + 2), getResources().getDisplayMetrics())); return row; } } } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { hackRegular = Typeface.createFromAsset(getActivity().getAssets(), "Hack-Regular.otf"); final View v = inflater.inflate(R.layout.messageview, container, false); statusView = (TextView) v.findViewById(R.id.statusView); statusView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (buffer != null && conn != null && server != null && server.getStatus() != null && server.getStatus().equalsIgnoreCase("disconnected")) { NetworkConnection.getInstance().reconnect(buffer.getCid()); } } }); awayView = v.findViewById(R.id.away); awayView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(buffer != null) NetworkConnection.getInstance().back(buffer.getCid()); } }); awayTxt = (TextView) v.findViewById(R.id.awayTxt); unreadBottomView = v.findViewById(R.id.unreadBottom); unreadBottomView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(buffer != null) buffer.setScrolledUp(false); getListView().setSelection(adapter.getCount() - 1); hideView(unreadBottomView); } }); unreadBottomLabel = (TextView) v.findViewById(R.id.unread); highlightsBottomLabel = (TextView) v.findViewById(R.id.highlightsBottom); unreadTopView = v.findViewById(R.id.unreadTop); unreadTopView.setVisibility(View.GONE); unreadTopView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (adapter.getLastSeenEIDPosition() > 0) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); hideView(unreadTopView); } getListView().setSelection(adapter.getLastSeenEIDPosition()); } }); unreadTopLabel = (TextView) v.findViewById(R.id.unreadTopText); highlightsTopLabel = (TextView) v.findViewById(R.id.highlightsTop); Button b = (Button) v.findViewById(R.id.markAsRead); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { hideView(unreadTopView); if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } }); globalMsgView = v.findViewById(R.id.globalMessageView); globalMsg = (TextView) v.findViewById(R.id.globalMessageTxt); b = (Button) v.findViewById(R.id.dismissGlobalMessage); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (conn != null) conn.globalMsg = null; update_global_msg(); } }); spinner = (ProgressBar) v.findViewById(R.id.spinner); suggestionsContainer = v.findViewById(R.id.suggestionsContainer); suggestions = (GridView) v.findViewById(R.id.suggestions); headerViewContainer = getLayoutInflater(null).inflate(R.layout.messageview_header, null); headerView = headerViewContainer.findViewById(R.id.progress); backlogFailed = (TextView) headerViewContainer.findViewById(R.id.backlogFailed); loadBacklogButton = (Button) headerViewContainer.findViewById(R.id.loadBacklogButton); loadBacklogButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (conn != null && buffer != null) { backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); headerView.setVisibility(View.VISIBLE); NetworkConnection.getInstance().request_backlog(buffer.getCid(), buffer.getBid(), earliest_eid); } } }); ((ListView) v.findViewById(android.R.id.list)).addHeaderView(headerViewContainer); footerViewContainer = new View(getActivity()); ((ListView) v.findViewById(android.R.id.list)).addFooterView(footerViewContainer, null, false); avatarContainer = (OffsetLinearLayout) v.findViewById(R.id.avatarContainer); avatar = (ImageView) v.findViewById(R.id.avatar); return v; } public void showSpinner(boolean show) { if (show) { if (Build.VERSION.SDK_INT < 16) { AlphaAnimation anim = new AlphaAnimation(0, 1); anim.setDuration(150); anim.setFillAfter(true); spinner.setAnimation(anim); } else { spinner.setAlpha(0); spinner.animate().alpha(1); } spinner.setVisibility(View.VISIBLE); } else { if (Build.VERSION.SDK_INT < 16) { AlphaAnimation anim = new AlphaAnimation(1, 0); anim.setDuration(150); anim.setFillAfter(true); anim.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { spinner.setVisibility(View.GONE); } @Override public void onAnimationRepeat(Animation animation) { } }); spinner.setAnimation(anim); } else { spinner.animate().alpha(0).withEndAction(new Runnable() { @Override public void run() { spinner.setVisibility(View.GONE); } }); } } } private void hideView(final View v) { if (v.getVisibility() != View.GONE) { if (Build.VERSION.SDK_INT >= 16) { v.animate().alpha(0).setDuration(100).withEndAction(new Runnable() { @Override public void run() { v.setVisibility(View.GONE); } }); } else { v.setVisibility(View.GONE); } } } private void showView(final View v) { if (v.getVisibility() != View.VISIBLE) { if (Build.VERSION.SDK_INT >= 16) { v.setAlpha(0); v.animate().alpha(1).setDuration(100); } v.setVisibility(View.VISIBLE); } } public void drawerClosed() { try { ListView v = getListView(); mOnScrollListener.onScroll(v, v.getFirstVisiblePosition(), v.getLastVisiblePosition() - v.getFirstVisiblePosition(), adapter.getCount()); } catch (Exception e) { } } private void hide_avatar() { if (avatarContainer.getVisibility() != View.GONE) avatarContainer.setVisibility(View.GONE); if (avatar.getTag() != null) { ((ImageView) avatar.getTag()).setVisibility(View.VISIBLE); avatar.setTag(null); } } private OnScrollListener mOnScrollListener = new OnScrollListener() { @Override public void onScroll(final AbsListView view, final int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (!ready || buffer == null || adapter == null || visibleItemCount < 0) { hide_avatar(); return; } if (conn.ready && !requestingBacklog && headerView != null && buffer.getMin_eid() > 0) { if (firstVisibleItem == 0 && headerView.getVisibility() == View.VISIBLE && conn.getState() == NetworkConnection.STATE_CONNECTED) { requestingBacklog = true; conn.request_backlog(buffer.getCid(), buffer.getBid(), earliest_eid); hide_avatar(); return; } else if(firstVisibleItem > 0 && loadBacklogButton.getVisibility() == View.VISIBLE) { loadBacklogButton.setVisibility(View.GONE); headerView.setVisibility(View.VISIBLE); } } if (unreadBottomView != null && adapter.data.size() > 0) { if (firstVisibleItem + visibleItemCount >= totalItemCount) { if(unreadBottomView.getVisibility() != View.GONE) unreadBottomView.setVisibility(View.GONE); if (unreadTopView.getVisibility() == View.GONE && conn.getState() == NetworkConnection.STATE_CONNECTED) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } newMsgs = 0; newMsgTime = 0; newHighlights = 0; } } if (firstVisibleItem + visibleItemCount < totalItemCount - 1) { View v = view.getChildAt(0); buffer.setScrolledUp(true); buffer.setScrollPosition(firstVisibleItem); buffer.setScrollPositionOffset((v == null) ? 0 : v.getTop()); } else { buffer.setScrolledUp(false); buffer.setScrollPosition(-1); } if (adapter != null && adapter.data.size() > 0) { synchronized (adapter.data) { if (unreadTopView != null && unreadTopView.getVisibility() == View.VISIBLE) { update_top_unread(firstVisibleItem); int markerPos = -1; if (adapter != null) markerPos = adapter.getLastSeenEIDPosition(); if (markerPos > 1 && getListView().getFirstVisiblePosition() <= markerPos) { unreadTopView.setVisibility(View.GONE); if (conn.getState() == NetworkConnection.STATE_CONNECTED) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } } } if (!pref_chatOneLine && !pref_avatarsOff && firstVisibleItem > ((ListView) view).getHeaderViewsCount()) { int offset = (unreadTopView.getVisibility() == View.VISIBLE) ? unreadTopView.getHeight() : 0; View v; int i = 0; do { v = view.getChildAt(i++); } while (v != null && v.getTop() + v.getHeight() <= offset - 1); if(v != null) { int first = firstVisibleItem - ((ListView) view).getHeaderViewsCount() + i - 1; MessageAdapter.ViewHolder vh = (MessageAdapter.ViewHolder) v.getTag(); MessageAdapter.ViewHolder top_vh = vh; Event e = first >= 0 ? (Event) adapter.getItem(first) : null; if (first > 0 && vh != null && v.getTop() <= offset && e != null && ((vh.avatar != null && e.group_eid < 1 && e.isMessage() && e.from != null && e.from.length() > 0) || e.row_type == ROW_LASTSEENEID)) { for (i = first; i < adapter.getCount() && i < first + 4; i++) { e = (Event) adapter.getItem(i); if(e.row_type == ROW_LASTSEENEID) e = (Event) adapter.getItem(i-1); int next = i + 1; Event e1 = (Event) adapter.getItem(next); if(e1 != null && e1.row_type == ROW_LASTSEENEID) { next++; if(next < adapter.getCount()) e1 = (Event) adapter.getItem(next); else break; } if (e != null && e1 != null && e.from != null && e.from.equals(e1.from) && e1.group_eid < 1 && !e1.header) { View v1 = view.getChildAt(next - (firstVisibleItem - ((ListView) view).getHeaderViewsCount())); if (v1 != null) { MessageAdapter.ViewHolder vh1 = (MessageAdapter.ViewHolder) v1.getTag(); if (vh1 != null && vh1.avatar != null) { v = v1; vh = vh1; } } } else { break; } } if (avatar.getTag() != null && avatar.getTag() != top_vh.avatar) { ((ImageView) avatar.getTag()).setVisibility(View.VISIBLE); } if(e != null) { Bitmap bitmap = mAvatarsList.getAvatar(e.cid, e.from).getBitmap(ColorScheme.getInstance().isDarkTheme, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 32, getResources().getDisplayMetrics()), e.self); if(vh.avatar != null && bitmap != null) { int topMargin, leftMargin; int height = bitmap.getHeight() + (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics()); if (v.getHeight() + v.getTop() < (height + offset)) { topMargin = v.getTop() + v.getHeight() - height; } else { topMargin = offset; } leftMargin = vh.avatar.getLeft(); avatarContainer.offset(leftMargin, topMargin); if (top_vh.avatar == null || (avatar.getTag() != top_vh.avatar || top_vh.avatar.getVisibility() != View.INVISIBLE)) { avatar.setTag(top_vh.avatar); avatar.setImageBitmap(bitmap); avatarContainer.setVisibility(View.VISIBLE); if(top_vh.avatar != null) top_vh.avatar.setVisibility(View.INVISIBLE); } } else { hide_avatar(); } } } else { hide_avatar(); } } else { hide_avatar(); } } else { hide_avatar(); } } } else { hide_avatar(); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); conn = NetworkConnection.getInstance(); conn.addHandler(this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (MessageViewListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement MessageViewListener"); } if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); } @Override public void setArguments(Bundle args) { ready = false; if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = null; if (tapTimerTask != null) tapTimerTask.cancel(); tapTimerTask = null; if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); if (buffer != null && buffer.getBid() != args.getInt("bid", -1) && adapter != null) adapter.clearLastSeenEIDMarker(); buffer = BuffersList.getInstance().getBuffer(args.getInt("bid", -1)); if (buffer != null) { server = buffer.getServer(); Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: switched to bid: " + buffer.getBid()); } else { Crashlytics.log(Log.WARN, "IRCCloud", "MessageViewFragment: couldn't find buffer to switch to"); } requestingBacklog = false; avgInsertTime = 0; newMsgs = 0; newMsgTime = 0; newHighlights = 0; earliest_eid = 0; backlog_eid = 0; currentCollapsedEid = -1; lastCollapsedDay = -1; if (server != null) { ignore.setIgnores(server.ignores); if (server.getAway() != null && server.getAway().length() > 0) { awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.getAway() + ")"))).toString()); awayView.setVisibility(View.VISIBLE); } else { awayView.setVisibility(View.GONE); } collapsedEvents.setServer(server); update_status(server.getStatus(), server.getFail_info()); } if (avatar != null) { avatarContainer.setVisibility(View.GONE); avatar.setTag(null); } if (unreadTopView != null) unreadTopView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); try { if (getListView().getHeaderViewsCount() == 0) { getListView().addHeaderView(headerViewContainer); } } catch (IllegalStateException e) { } ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams(); lp.topMargin = 0; headerView.setLayoutParams(lp); lp = (ViewGroup.MarginLayoutParams) backlogFailed.getLayoutParams(); lp.topMargin = 0; backlogFailed.setLayoutParams(lp); if (buffer != null && EventsList.getInstance().getEventsForBuffer(buffer.getBid()) != null) { requestingBacklog = true; if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); if (args.getBoolean("fade")) { Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: Loading message contents in the background"); refreshTask.execute((Void) null); } else { Crashlytics.log(Log.DEBUG, "IRCCloud", "MessageViewFragment: Loading message contents"); refreshTask.onPreExecute(); refreshTask.onPostExecute(refreshTask.doInBackground()); } } else { if (buffer == null || buffer.getMin_eid() == 0 || earliest_eid == buffer.getMin_eid() || conn.getState() != NetworkConnection.STATE_CONNECTED || !conn.ready) { headerView.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } else { headerView.setVisibility(View.VISIBLE); loadBacklogButton.setVisibility(View.GONE); } if (adapter != null) { adapter.clear(); adapter.notifyDataSetInvalidated(); } else { adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); } if(mListener != null) mListener.onMessageViewReady(); ready = true; } } private void runOnUiThread(Runnable r) { if (getActivity() != null) getActivity().runOnUiThread(r); } @Override public void onLowMemory() { super.onLowMemory(); Crashlytics.log(Log.DEBUG, "IRCCloud", "Received low memory warning in the foreground, cleaning backlog in other buffers"); for (Buffer b : BuffersList.getInstance().getBuffers()) { if (b != buffer) EventsList.getInstance().pruneEvents(b.getBid()); } } private synchronized void insertEvent(final MessageAdapter adapter, Event event, boolean backlog, boolean nextIsGrouped) { synchronized (adapterLock) { try { long start = System.currentTimeMillis(); if (event.eid <= buffer.getMin_eid()) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } if (earliest_eid == 0 || event.eid < earliest_eid) earliest_eid = event.eid; String type = event.type; long eid = event.eid; if (type.startsWith("you_")) type = type.substring(4); if (type.equals("joined_channel") || type.equals("parted_channel") || type.equals("nickchange") || type.equals("quit") || type.equals("user_channel_mode") || type.equals("socket_closed") || type.equals("connecting_cancelled") || type.equals("connecting_failed")) { collapsedEvents.showChan = !buffer.isChannel(); if (pref_hideJoinPart && !type.equals("socket_closed") && !type.equals("connecting_cancelled") && !type.equals("connecting_failed")) { adapter.removeItem(event.eid); if (!backlog) adapter.notifyDataSetChanged(); return; } Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(event.getTime()); if (pref_expandJoinPart) expandedSectionEids.clear(); if (event.type.equals("socket_closed") || event.type.equals("connecting_failed") || event.type.equals("connecting_cancelled")) { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null && !last.type.equals("socket_closed") && !last.type.equals("connecting_failed") && !last.type.equals("connecting_cancelled")) currentCollapsedEid = -1; } else { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null && (last.type.equals("socket_closed") || last.type.equals("connecting_failed") || last.type.equals("connecting_cancelled"))) currentCollapsedEid = -1; } if (currentCollapsedEid == -1 || calendar.get(Calendar.DAY_OF_YEAR) != lastCollapsedDay || pref_expandJoinPart || event.type.equals("you_parted_channel")) { collapsedEvents.clear(); currentCollapsedEid = eid; lastCollapsedDay = calendar.get(Calendar.DAY_OF_YEAR); } if (!collapsedEvents.showChan) event.chan = buffer.getName(); if (!collapsedEvents.addEvent(event)) collapsedEvents.clear(); if ((currentCollapsedEid == event.eid || pref_expandJoinPart) && type.equals("user_channel_mode")) { event.color = colorScheme.messageTextColor; event.bg_color = colorScheme.collapsedHeadingBackgroundColor; } else { event.color = colorScheme.collapsedRowTextColor; event.bg_color = colorScheme.contentBackgroundColor; } String msg; if (expandedSectionEids.contains(currentCollapsedEid)) { CollapsedEventsList c = new CollapsedEventsList(); c.showChan = collapsedEvents.showChan; c.setServer(server); c.addEvent(event); msg = c.getCollapsedMessage(); if (!nextIsGrouped) { String group_msg = collapsedEvents.getCollapsedMessage(); if (group_msg == null && type.equals("nickchange")) { group_msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if (group_msg == null && type.equals("user_channel_mode")) { if (event.from != null && event.from.length() > 0) msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>"; else msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>"; currentCollapsedEid = eid; } Event heading = new Event(); heading.type = "__expanded_group_heading__"; heading.cid = event.cid; heading.bid = event.bid; heading.eid = currentCollapsedEid - 1; heading.group_msg = group_msg; heading.color = colorScheme.timestampColor; heading.bg_color = colorScheme.contentBackgroundColor; heading.linkify = false; adapter.addItem(currentCollapsedEid - 1, heading); if (event.type.equals("socket_closed") || event.type.equals("connecting_failed") || event.type.equals("connecting_cancelled")) { Event last = EventsList.getInstance().getEvent(lastCollapsedEid, buffer.getBid()); if (last != null) last.row_type = ROW_MESSAGE; event.row_type = ROW_SOCKETCLOSED; } } event.timestamp = null; } else { msg = (nextIsGrouped && currentCollapsedEid != event.eid) ? "" : collapsedEvents.getCollapsedMessage(); } if (msg == null && type.equals("nickchange")) { msg = event.old_nick + " → <b>" + event.nick + "</b>"; } if (msg == null && type.equals("user_channel_mode")) { if (event.from != null && event.from.length() > 0) msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by <b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b>"; else msg = collapsedEvents.formatNick(event.nick, event.target_mode, false) + " was set to <b>" + event.diff + "</b> by the server <b>" + event.server + "</b>"; currentCollapsedEid = eid; } if (!expandedSectionEids.contains(currentCollapsedEid)) { if (eid != currentCollapsedEid) { event.color = colorScheme.timestampColor; event.bg_color = colorScheme.contentBackgroundColor; } eid = currentCollapsedEid; } event.group_msg = msg; event.html = null; event.formatted = null; event.linkify = false; lastCollapsedEid = event.eid; if ((buffer.isConsole() && !event.type.equals("socket_closed") && !event.type.equals("connecting_failed") && !event.type.equals("connecting_cancelled")) || event.type.equals("you_parted_channel")) { currentCollapsedEid = -1; lastCollapsedEid = -1; collapsedEvents.clear(); } } else { currentCollapsedEid = -1; lastCollapsedEid = -1; collapsedEvents.clear(); if (event.html == null) { if ((pref_chatOneLine || !event.isMessage()) && event.from != null && event.from.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> " + event.msg; else if (pref_chatOneLine && event.type.equals("buffer_msg") && event.server != null && event.server.length() > 0) event.html = "<b>" + event.server + "</b> " + event.msg; else event.html = event.msg; } if (event.formatted_nick == null && event.from != null && event.from.length() > 0) { event.formatted_nick = Html.fromHtml("<b>" + ColorFormatter.irc_to_html(collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor)) + "</b>"); } if (event.formatted_realname == null && event.from_realname != null && event.from_realname.length() > 0) { event.formatted_realname = ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(ColorFormatter.emojify(event.from_realname)), true, null); } } String from = event.from; if (from == null || from.length() == 0) from = event.nick; if (from != null && event.hostmask != null && event.isMessage() && buffer.getType() != null && !buffer.isConversation()) { String usermask = from + "!" + event.hostmask; if (ignore.match(usermask)) { if (unreadTopView != null && unreadTopView.getVisibility() == View.GONE && unreadBottomView != null && unreadBottomView.getVisibility() == View.GONE) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } return; } } switch (type) { case "channel_mode": if (event.nick != null && event.nick.length() > 0) event.html = event.msg + " by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>"; else if (event.server != null && event.server.length() > 0) event.html = event.msg + " by the server <b>" + event.server + "</b>"; break; case "buffer_me_msg": event.html = "— <i><b>" + collapsedEvents.formatNick(event.nick, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> " + event.msg + "</i>"; break; case "buffer_msg": case "notice": if (pref_chatOneLine && event.from != null && event.from.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, !event.self && pref_nickColors, ColorScheme.getInstance().selfTextColor) + "</b> "; else event.html = ""; if(event.target_mode != null && server != null && server.PREFIX != null) { if (server.PREFIX.has(server.MODE_OPER) && server.PREFIX.get(server.MODE_OPER) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OPER).asText())) event.html += collapsedEvents.formatNick("Opers", server.MODE_OPER, false) + " "; else if (server.PREFIX.has(server.MODE_OWNER) && server.PREFIX.get(server.MODE_OWNER) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OWNER).asText())) event.html += collapsedEvents.formatNick("Owners", server.MODE_OWNER, false) + " "; else if (server.PREFIX.has(server.MODE_ADMIN) && server.PREFIX.get(server.MODE_ADMIN) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_ADMIN).asText())) event.html += collapsedEvents.formatNick("Admins", server.MODE_ADMIN, false) + " "; else if (server.PREFIX.has(server.MODE_OP) && server.PREFIX.get(server.MODE_OP) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_OP).asText())) event.html += collapsedEvents.formatNick("Ops", server.MODE_OP, false) + " "; else if (server.PREFIX.has(server.MODE_HALFOP) && server.PREFIX.get(server.MODE_HALFOP) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_HALFOP).asText())) event.html += collapsedEvents.formatNick("Half Ops", server.MODE_HALFOP, false) + " "; else if (server.PREFIX.has(server.MODE_VOICED) && server.PREFIX.get(server.MODE_VOICED) != null && event.target_mode.equals(server.PREFIX.get(server.MODE_VOICED).asText())) event.html += collapsedEvents.formatNick("Voiced", server.MODE_VOICED, false) + " "; } if (buffer.isConsole() && event.to_chan && event.chan != null && event.chan.length() > 0) { event.html += "<b>" + event.chan + "</b>: " + event.msg; } else if (buffer.isConsole() && event.self && event.nick != null && event.nick.length() > 0) { event.html += "<b>" + event.nick + "</b>: " + event.msg; } else { event.html += event.msg; } break; case "kicked_channel": event.html = "← "; if (event.type.startsWith("you_")) event.html += "You"; else event.html += "<b>" + collapsedEvents.formatNick(event.old_nick, null, false) + "</b>"; if (event.hostmask != null && event.hostmask.length() > 0) event.html += " (" + event.hostmask + ")"; if (event.type.startsWith("you_")) event.html += " were"; else event.html += " was"; if (event.from_hostmask != null && event.from_hostmask.length() > 0) event.html += " kicked by <b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b>"; else event.html += " kicked by the server <b>" + event.nick + "</b>"; if (event.msg != null && event.msg.length() > 0 && !event.msg.equals(event.nick)) event.html += ": " + event.msg; break; case "callerid": event.html = "<b>" + collapsedEvents.formatNick(event.from, event.from_mode, false) + "</b> (" + event.hostmask + ") " + event.msg + " Tap to accept."; break; case "channel_mode_list_change": if (event.from.length() == 0) { if (event.nick != null && event.nick.length() > 0) event.html = "<b>" + collapsedEvents.formatNick(event.nick, event.from_mode, false) + "</b> " + event.msg; else if (event.server != null && event.server.length() > 0) event.html = "The server <b>" + event.server + "</b> " + event.msg; } break; } adapter.addItem(eid, event); if (!backlog) adapter.notifyDataSetChanged(); long time = (System.currentTimeMillis() - start); if (avgInsertTime == 0) avgInsertTime = time; avgInsertTime += time; avgInsertTime /= 2.0; //Log.i("IRCCloud", "Average insert time: " + avgInsertTime); if (!backlog && buffer.getScrolledUp() && !event.self && event.isImportant(type)) { if (newMsgTime == 0) newMsgTime = System.currentTimeMillis(); newMsgs++; if (event.highlight) newHighlights++; update_unread(); adapter.insertLastSeenEIDMarker(); adapter.notifyDataSetChanged(); } if (!backlog && !buffer.getScrolledUp()) { getListView().setSelection(adapter.getCount() - 1); if (tapTimer != null) { tapTimer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { try { getListView().setSelection(adapter.getCount() - 1); } catch (Exception e) { //List view isn't ready yet } } }); } }, 200); } } if (!backlog && event.highlight && !getActivity().getSharedPreferences("prefs", 0).getBoolean("mentionTip", false)) { Toast.makeText(getActivity(), "Double-tap a message to quickly reply to the sender", Toast.LENGTH_LONG).show(); SharedPreferences.Editor editor = getActivity().getSharedPreferences("prefs", 0).edit(); editor.putBoolean("mentionTip", true); editor.commit(); } if (!backlog) { int markerPos = adapter.getLastSeenEIDPosition(); if (markerPos > 0 && getListView().getFirstVisiblePosition() > markerPos) { unreadTopLabel.setText((getListView().getFirstVisiblePosition() - markerPos) + " unread messages"); } } } catch (Exception e) { // TODO Auto-generated catch block NetworkConnection.printStackTraceToCrashlytics(e); } } } private class OnItemLongClickListener implements View.OnLongClickListener { private int pos; OnItemLongClickListener(int position) { pos = position; } @Override public boolean onLongClick(View view) { try { longPressOverride = mListener.onMessageLongClicked((Event) adapter.getItem(pos)); return longPressOverride; } catch (Exception e) { } return false; } } private class OnItemClickListener implements OnClickListener { private int pos; OnItemClickListener(int position) { pos = position; } @Override public void onClick(View arg0) { longPressOverride = false; if (pos < 0 || pos >= adapter.data.size()) return; if(tapTimer == null) tapTimer = new Timer("message-tap-timer"); if (adapter != null) { if (tapTimerTask != null) { tapTimerTask.cancel(); tapTimerTask = null; mListener.onMessageDoubleClicked(adapter.data.get(pos)); } else { tapTimerTask = new TimerTask() { int position = pos; @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null && adapter.data != null && position < adapter.data.size()) { Event e = adapter.data.get(position); if (e != null) { if (e.type.equals("channel_invite")) { conn.join(buffer.getCid(), e.old_nick, null); } else if (e.type.equals("callerid")) { conn.say(buffer.getCid(), null, "/accept " + e.from); Buffer b = BuffersList.getInstance().getBufferByName(buffer.getCid(), e.from); if (b != null) { mListener.onBufferSelected(b.getBid()); } else { conn.say(buffer.getCid(), null, "/query " + e.from); } } else if (e.failed) { if(mListener != null) mListener.onFailedMessageClicked(e); } else { long group = e.group_eid; if (expandedSectionEids.contains(group)) expandedSectionEids.remove(group); else if (e.eid != group) expandedSectionEids.add(group); if (e.eid != e.group_eid) { adapter.clearLastSeenEIDMarker(); if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } } } } } }); tapTimerTask = null; } }; tapTimer.schedule(tapTimerTask, 300); } } } } @SuppressWarnings("unchecked") public void onResume() { super.onResume(); getListView().setOnScrollListener(mOnScrollListener); update_global_msg(); if (buffer != null && adapter != null) { if(buffer.getUnread() == 0 && !buffer.getScrolledUp()) adapter.clearLastSeenEIDMarker(); adapter.notifyDataSetChanged(); } } @Override public void onDestroyView() { super.onDestroyView(); getListView().setAdapter(null); } @Override public void onStop() { if(headerViewContainer != null) headerViewContainer.setVisibility(View.GONE); if(footerViewContainer != null) footerViewContainer.setVisibility(View.GONE); super.onStop(); } @Override public void onStart() { if(headerViewContainer != null) headerViewContainer.setVisibility(View.VISIBLE); if(footerViewContainer != null) footerViewContainer.setVisibility(View.VISIBLE); super.onStart(); } @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = IRCCloudApplication.getRefWatcher(getActivity()); if (refWatcher != null) refWatcher.watch(this); if (tapTimer != null) { tapTimer.cancel(); tapTimer = null; } if(conn != null) conn.removeHandler(this); mListener = null; heartbeatTask = null; } private class HeartbeatTask extends AsyncTaskEx<Void, Void, Void> { Buffer b; public HeartbeatTask() { b = buffer; /*if(buffer != null) Log.d("IRCCloud", "Heartbeat task created. Ready: " + ready + " BID: " + buffer.getBid()); Thread.dumpStack();*/ } @Override protected Void doInBackground(Void... params) { try { Thread.sleep(250); } catch (InterruptedException e) { } if (isCancelled() || !conn.ready || conn.getState() != NetworkConnection.STATE_CONNECTED || b == null || !ready || requestingBacklog) return null; if (getActivity() != null) { try { DrawerLayout drawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawerLayout); if (drawerLayout != null && (drawerLayout.isDrawerOpen(Gravity.LEFT) || drawerLayout.isDrawerOpen(Gravity.RIGHT))) return null; } catch (Exception e) { } } if (unreadTopView.getVisibility() == View.VISIBLE || unreadBottomView.getVisibility() == View.VISIBLE) return null; try { Long eid = EventsList.getInstance().lastEidForBuffer(b.getBid()); if (eid >= b.getLast_seen_eid() && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { if (getActivity() != null && getActivity().getIntent() != null) getActivity().getIntent().putExtra("last_seen_eid", eid); NetworkConnection.getInstance().heartbeat(b.getCid(), b.getBid(), eid); b.setLast_seen_eid(eid); b.setUnread(0); b.setHighlights(0); //Log.e("IRCCloud", "Heartbeat: " + buffer.name + ": " + events.get(events.lastKey()).msg); } } catch (Exception e) { } return null; } @Override protected void onPostExecute(Void result) { if (!isCancelled()) heartbeatTask = null; } } private class FormatTask extends AsyncTaskEx<Void, Void, Void> { @Override protected void onPreExecute() { } @Override protected Void doInBackground(Void... params) { adapter.format(); return null; } @Override protected void onPostExecute(Void result) { } } private class RefreshTask extends AsyncTaskEx<Void, Void, Void> { private MessageAdapter adapter; TreeMap<Long, Event> events; Buffer buffer; int oldPosition = -1; int topOffset = -1; @Override protected void onPreExecute() { //Debug.startMethodTracing("refresh"); try { oldPosition = getListView().getFirstVisiblePosition(); View v = getListView().getChildAt(0); topOffset = (v == null) ? 0 : v.getTop(); buffer = MessageViewFragment.this.buffer; } catch (IllegalStateException e) { //The list view isn't on screen anymore cancel(true); refreshTask = null; } } @SuppressWarnings("unchecked") @Override protected Void doInBackground(Void... params) { TreeMap<Long, Event> evs = null; long time = System.currentTimeMillis(); if (buffer != null) evs = EventsList.getInstance().getEventsForBuffer(buffer.getBid()); Log.i("IRCCloud", "Loaded data in " + (System.currentTimeMillis() - time) + "ms"); if (!isCancelled() && evs != null && evs.size() > 0) { try { events = (TreeMap<Long, Event>) evs.clone(); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); return null; } if (isCancelled()) return null; if (events != null) { try { if (events.size() > 0 && MessageViewFragment.this.adapter != null && MessageViewFragment.this.adapter.data.size() > 0 && earliest_eid > events.firstKey()) { if (oldPosition > 0 && oldPosition == MessageViewFragment.this.adapter.data.size()) oldPosition--; Event e = MessageViewFragment.this.adapter.data.get(oldPosition); if (e != null) backlog_eid = e.group_eid - 1; else backlog_eid = -1; if (backlog_eid < 0) { backlog_eid = MessageViewFragment.this.adapter.getItemId(oldPosition) - 1; } Event backlogMarker = new Event(); backlogMarker.eid = backlog_eid; backlogMarker.type = TYPE_BACKLOGMARKER; backlogMarker.row_type = ROW_BACKLOGMARKER; backlogMarker.html = "__backlog__"; backlogMarker.bg_color = colorScheme.contentBackgroundColor; events.put(backlog_eid, backlogMarker); } adapter = new MessageAdapter(MessageViewFragment.this, events.size()); refresh(adapter, events); } catch (IllegalStateException e) { //The list view doesn't exist yet NetworkConnection.printStackTraceToCrashlytics(e); Log.e("IRCCloud", "Tried to refresh the message list, but it didn't exist."); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); return null; } } } else if (buffer != null && buffer.getMin_eid() > 0 && conn.ready && conn.getState() == NetworkConnection.STATE_CONNECTED && !isCancelled()) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.VISIBLE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; requestingBacklog = true; conn.request_backlog(buffer.getCid(), buffer.getBid(), 0); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); adapter = new MessageAdapter(MessageViewFragment.this, 0); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; } }); } return null; } @Override protected void onPostExecute(Void result) { if (!isCancelled() && adapter != null) { try { avatarContainer.setVisibility(View.GONE); avatar.setTag(null); ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) headerView.getLayoutParams(); if (adapter.getLastSeenEIDPosition() == 0) lp.topMargin = (int) getSafeResources().getDimension(R.dimen.top_bar_height); else lp.topMargin = 0; headerView.setLayoutParams(lp); lp = (ViewGroup.MarginLayoutParams) backlogFailed.getLayoutParams(); if (adapter.getLastSeenEIDPosition() == 0) lp.topMargin = (int) getSafeResources().getDimension(R.dimen.top_bar_height); else lp.topMargin = 0; backlogFailed.setLayoutParams(lp); setListAdapter(adapter); MessageViewFragment.this.adapter = adapter; if (events != null && events.size() > 0) { int markerPos = adapter.getBacklogMarkerPosition(); if (markerPos != -1 && requestingBacklog) getListView().setSelectionFromTop(oldPosition + markerPos + 1, headerViewContainer.getHeight()); else if (!buffer.getScrolledUp()) getListView().setSelection(adapter.getCount() - 1); else { getListView().setSelectionFromTop(buffer.getScrollPosition(), buffer.getScrollPositionOffset()); if (adapter.getLastSeenEIDPosition() > buffer.getScrollPosition()) { newMsgs = 0; newHighlights = 0; for (int i = adapter.data.size() - 1; i >= 0; i--) { Event e = adapter.data.get(i); if (e.eid <= buffer.getLast_seen_eid()) break; if (e.isImportant(buffer.getType())) { if (e.highlight) newHighlights++; else newMsgs++; } } } update_unread(); } } new FormatTask().execute((Void) null); } catch (IllegalStateException e) { //The list view isn't on screen anymore NetworkConnection.printStackTraceToCrashlytics(e); } refreshTask = null; requestingBacklog = false; mHandler.postDelayed(new Runnable() { @Override public void run() { try { update_top_unread(getListView().getFirstVisiblePosition()); } catch (IllegalStateException e) { //List view not ready yet } if (server != null) update_status(server.getStatus(), server.getFail_info()); if (mListener != null && !ready) mListener.onMessageViewReady(); ready = true; try { ListView v = getListView(); mOnScrollListener.onScroll(v, v.getFirstVisiblePosition(), v.getLastVisiblePosition() - v.getFirstVisiblePosition(), adapter.getCount()); } catch (Exception e) { } } }, 250); //Debug.stopMethodTracing(); } } } private synchronized void refresh(MessageAdapter adapter, TreeMap<Long, Event> events) { pref_24hr = false; pref_seconds = false; pref_trackUnread = true; pref_timeLeft = false; pref_nickColors = false; pref_hideJoinPart = false; pref_expandJoinPart = false; pref_avatarsOff = false; pref_chatOneLine = false; pref_norealname = false; pref_compact = false; if (NetworkConnection.getInstance().getUserInfo() != null && NetworkConnection.getInstance().getUserInfo().prefs != null) { try { JSONObject prefs = NetworkConnection.getInstance().getUserInfo().prefs; pref_compact = (prefs.has("ascii-compact") && prefs.get("ascii-compact") instanceof Boolean && prefs.getBoolean("ascii-compact")); pref_24hr = (prefs.has("time-24hr") && prefs.get("time-24hr") instanceof Boolean && prefs.getBoolean("time-24hr")); pref_seconds = (prefs.has("time-seconds") && prefs.get("time-seconds") instanceof Boolean && prefs.getBoolean("time-seconds")); pref_timeLeft = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("time-left", true); pref_nickColors = (prefs.has("nick-colors") && prefs.get("nick-colors") instanceof Boolean && prefs.getBoolean("nick-colors")); pref_avatarsOff = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("avatars-off", true); pref_chatOneLine = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("chat-oneline", true); pref_norealname = !PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean("chat-norealname", true); if(prefs.has("channel-disableTrackUnread")) { JSONObject disabledMap = prefs.getJSONObject("channel-disableTrackUnread"); if (disabledMap.has(String.valueOf(buffer.getBid())) && disabledMap.getBoolean(String.valueOf(buffer.getBid()))) { pref_trackUnread = false; } } JSONObject hiddenMap = null; if (buffer.isChannel()) { if (prefs.has("channel-hideJoinPart")) hiddenMap = prefs.getJSONObject("channel-hideJoinPart"); } else { if (prefs.has("buffer-hideJoinPart")) hiddenMap = prefs.getJSONObject("buffer-hideJoinPart"); } pref_hideJoinPart = (prefs.has("hideJoinPart") && prefs.get("hideJoinPart") instanceof Boolean && prefs.getBoolean("hideJoinPart")) || (hiddenMap != null && hiddenMap.has(String.valueOf(buffer.getBid())) && hiddenMap.getBoolean(String.valueOf(buffer.getBid()))); JSONObject expandMap = null; if (buffer.isChannel()) { if (prefs.has("channel-expandJoinPart")) expandMap = prefs.getJSONObject("channel-expandJoinPart"); } else if (buffer.isConsole()) { if (prefs.has("buffer-expandDisco")) expandMap = prefs.getJSONObject("buffer-expandDisco"); } else { if (prefs.has("buffer-expandJoinPart")) expandMap = prefs.getJSONObject("buffer-expandJoinPart"); } pref_expandJoinPart = ((prefs.has("expandJoinPart") && prefs.get("expandJoinPart") instanceof Boolean && prefs.getBoolean("expandJoinPart")) || (expandMap != null && expandMap.has(String.valueOf(buffer.getBid())) && expandMap.getBoolean(String.valueOf(buffer.getBid())))); } catch (JSONException e1) { NetworkConnection.printStackTraceToCrashlytics(e1); } } synchronized (adapterLock) { if (getActivity() != null) textSize = PreferenceManager.getDefaultSharedPreferences(getActivity()).getInt("textSize", getActivity().getResources().getInteger(R.integer.default_text_size)); timestamp_width = -1; if (conn.getReconnectTimestamp() == 0) conn.cancel_idle_timer(); //This may take a while... collapsedEvents.clear(); currentCollapsedEid = -1; lastCollapsedDay = -1; if (events == null || (events.size() == 0 && buffer.getMin_eid() > 0)) { if (buffer != null && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { requestingBacklog = true; runOnUiThread(new Runnable() { @Override public void run() { conn.request_backlog(buffer.getCid(), buffer.getBid(), 0); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } } else if (events.size() > 0) { if (server != null) { ignore.setIgnores(server.ignores); } else { ignore.setIgnores(null); } collapsedEvents.setServer(server); earliest_eid = events.firstKey(); if (events.size() > 0) { avgInsertTime = 0; //Debug.startMethodTracing("refresh"); long start = System.currentTimeMillis(); Iterator<Event> i = events.values().iterator(); Event next = i.next(); Calendar calendar = Calendar.getInstance(); while (next != null) { Event e = next; next = i.hasNext() ? i.next() : null; String type = (next == null) ? "" : next.type; if (next != null && currentCollapsedEid != -1 && !expandedSectionEids.contains(currentCollapsedEid) && (type.equalsIgnoreCase("joined_channel") || type.equalsIgnoreCase("parted_channel") || type.equalsIgnoreCase("nickchange") || type.equalsIgnoreCase("quit") || type.equalsIgnoreCase("user_channel_mode"))) { calendar.setTimeInMillis(next.getTime()); insertEvent(adapter, e, true, calendar.get(Calendar.DAY_OF_YEAR) == lastCollapsedDay); } else { insertEvent(adapter, e, true, false); } } adapter.insertLastSeenEIDMarker(); Log.i("IRCCloud", "Backlog rendering took: " + (System.currentTimeMillis() - start) + "ms"); //Debug.stopMethodTracing(); avgInsertTime = 0; //adapter.notifyDataSetChanged(); if (events.firstKey() > buffer.getMin_eid() && buffer.getMin_eid() > 0 && conn != null && conn.getState() == NetworkConnection.STATE_CONNECTED) { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.VISIBLE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } else { runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.GONE); loadBacklogButton.setVisibility(View.GONE); } }); } } } if (conn.getReconnectTimestamp() == 0 && conn.getState() == NetworkConnection.STATE_CONNECTED) conn.schedule_idle_timer(); } } private void update_top_unread(int first) { if (adapter != null && buffer != null) { try { int markerPos = adapter.getLastSeenEIDPosition(); if (markerPos >= 0 && first > (markerPos + 1) && buffer.getUnread() > 0) { if (pref_trackUnread) { int highlights = adapter.getUnreadHighlightsAbovePosition(first); int count = (first - markerPos - 1) - highlights; StringBuilder txt = new StringBuilder(); if (highlights > 0) { if (highlights == 1) txt.append("mention"); else if (highlights > 0) txt.append("mentions"); highlightsTopLabel.setText(String.valueOf(highlights)); highlightsTopLabel.setVisibility(View.VISIBLE); if (count > 0) txt.append(" and "); } else { highlightsTopLabel.setVisibility(View.GONE); } if (markerPos == 0) { long seconds = (long) Math.ceil((earliest_eid - buffer.getLast_seen_eid()) / 1000000.0); if (seconds < 0) { if (count < 0) { hideView(unreadTopView); return; } else { if (count == 1) txt.append(count).append(" unread message"); else if (count > 0) txt.append(count).append(" unread messages"); } } else { int minutes = (int) Math.ceil(seconds / 60.0); int hours = (int) Math.ceil(seconds / 60.0 / 60.0); int days = (int) Math.ceil(seconds / 60.0 / 60.0 / 24.0); if (hours >= 24) { if (days == 1) txt.append(days).append(" day of unread messages"); else txt.append(days).append(" days of unread messages"); } else if (hours > 0) { if (hours == 1) txt.append(hours).append(" hour of unread messages"); else txt.append(hours).append(" hours of unread messages"); } else if (minutes > 0) { if (minutes == 1) txt.append(minutes).append(" minute of unread messages"); else txt.append(minutes).append(" minutes of unread messages"); } else { if (seconds == 1) txt.append(seconds).append(" second of unread messages"); else txt.append(seconds).append(" seconds of unread messages"); } } } else { if (count == 1) txt.append(count).append(" unread message"); else if (count > 0) txt.append(count).append(" unread messages"); } unreadTopLabel.setText(txt); showView(unreadTopView); } else { hideView(unreadTopView); } } else { if (markerPos > 0) { hideView(unreadTopView); if (adapter.data.size() > 0 && ready) { if (heartbeatTask != null) heartbeatTask.cancel(true); heartbeatTask = new HeartbeatTask(); heartbeatTask.execute((Void) null); } } } } catch (IllegalStateException e) { //The list view wasn't on screen yet NetworkConnection.printStackTraceToCrashlytics(e); } } } private class UnreadRefreshRunnable implements Runnable { @Override public void run() { update_unread(); } } UnreadRefreshRunnable unreadRefreshRunnable = null; private void update_unread() { if (unreadRefreshRunnable != null) { mHandler.removeCallbacks(unreadRefreshRunnable); unreadRefreshRunnable = null; } if (newMsgs > 0) { /*int minutes = (int)((System.currentTimeMillis() - newMsgTime)/60000); if(minutes < 1) unreadBottomLabel.setText("Less than a minute of chatter ("); else if(minutes == 1) unreadBottomLabel.setText("1 minute of chatter ("); else unreadBottomLabel.setText(minutes + " minutes of chatter ("); if(newMsgs == 1) unreadBottomLabel.setText(unreadBottomLabel.getText() + "1 message)"); else unreadBottomLabel.setText(unreadBottomLabel.getText() + (newMsgs + " messages)"));*/ String txt = ""; int msgCnt = newMsgs - newHighlights; if (newHighlights > 0) { if (newHighlights == 1) txt = "mention"; else txt = "mentions"; if (msgCnt > 0) txt += " and "; highlightsBottomLabel.setText(String.valueOf(newHighlights)); highlightsBottomLabel.setVisibility(View.VISIBLE); } else { highlightsBottomLabel.setVisibility(View.GONE); } if (msgCnt == 1) txt += msgCnt + " unread message"; else if (msgCnt > 0) txt += msgCnt + " unread messages"; unreadBottomLabel.setText(txt); showView(unreadBottomView); unreadRefreshRunnable = new UnreadRefreshRunnable(); mHandler.postDelayed(unreadRefreshRunnable, 10000); } } private class StatusRefreshRunnable implements Runnable { String status; JsonNode fail_info; public StatusRefreshRunnable(String status, JsonNode fail_info) { this.status = status; this.fail_info = fail_info; } @Override public void run() { update_status(status, fail_info); } } StatusRefreshRunnable statusRefreshRunnable = null; public static String ordinal(int i) { String[] sufixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; switch (i % 100) { case 11: case 12: case 13: return i + "th"; default: return i + sufixes[i % 10]; } } private String reason_txt(String reason) { String r = reason; switch (reason.toLowerCase()) { case "pool_lost": r = "Connection pool failed"; case "no_pool": r = "No available connection pools"; break; case "enetdown": r = "Network down"; break; case "etimedout": case "timeout": r = "Timed out"; break; case "ehostunreach": r = "Host unreachable"; break; case "econnrefused": r = "Connection refused"; break; case "nxdomain": case "einval": r = "Invalid hostname"; break; case "server_ping_timeout": r = "PING timeout"; break; case "ssl_certificate_error": r = "SSL certificate error"; break; case "ssl_error": r = "SSL error"; break; case "crash": r = "Connection crashed"; break; case "networks": r = "You've exceeded the connection limit for free accounts."; break; case "passworded_servers": r = "You can't connect to passworded servers with free accounts."; break; case "unverified": r = "You can’t connect to external servers until you confirm your email address."; break; } return r; } private void update_status(String status, JsonNode fail_info) { if (statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } statusView.setTextColor(colorScheme.connectionBarTextColor); statusView.setBackgroundColor(colorScheme.connectionBarColor); switch (status) { case "connected_ready": statusView.setVisibility(View.GONE); statusView.setText(""); break; case "quitting": statusView.setVisibility(View.VISIBLE); statusView.setText("Disconnecting"); break; case "disconnected": statusView.setVisibility(View.VISIBLE); if (fail_info.has("type") && fail_info.get("type").asText().length() > 0) { String text = "Disconnected: "; if (fail_info.get("type").asText().equals("connecting_restricted")) { text = reason_txt(fail_info.get("reason").asText()); if (text.equals(fail_info.get("reason").asText())) text = "You can’t connect to this server with a free account."; } else if (fail_info.get("type").asText().equals("connection_blocked")) { text = "Disconnected - Connections to this server have been blocked"; } else { if (fail_info.has("type") && fail_info.get("type").asText().equals("killed")) text = "Disconnected - Killed: "; else if (fail_info.has("type") && fail_info.get("type").asText().equals("connecting_failed")) text = "Disconnected: Failed to connect - "; if (fail_info.has("reason")) text += reason_txt(fail_info.get("reason").asText()); } statusView.setText(text); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); } else { statusView.setText("Disconnected. Tap to reconnect."); } break; case "queued": statusView.setVisibility(View.VISIBLE); statusView.setText("Connection queued"); break; case "connecting": statusView.setVisibility(View.VISIBLE); statusView.setText("Connecting"); break; case "connected": statusView.setVisibility(View.VISIBLE); statusView.setText("Connected"); break; case "connected_joining": statusView.setVisibility(View.VISIBLE); statusView.setText("Connected: Joining Channels"); break; case "pool_unavailable": statusView.setVisibility(View.VISIBLE); statusView.setText("Connection temporarily unavailable"); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); break; case "waiting_to_retry": try { statusView.setVisibility(View.VISIBLE); long seconds = (fail_info.get("timestamp").asLong() + fail_info.get("retry_timeout").asLong() - conn.clockOffset) - System.currentTimeMillis() / 1000; if (seconds > 0) { String text = "Disconnected"; if (fail_info.has("reason") && fail_info.get("reason").asText().length() > 0) { String reason = fail_info.get("reason").asText(); reason = reason_txt(reason); text += ": " + reason + ". "; } else text += "; "; text += "Reconnecting in "; int minutes = (int) (seconds / 60.0); int hours = (int) (seconds / 60.0 / 60.0); int days = (int) (seconds / 60.0 / 60.0 / 24.0); if (days > 0) { if (days == 1) text += days + " day."; else text += days + " days."; } else if (hours > 0) { if (hours == 1) text += hours + " hour."; else text += hours + " hours."; } else if (minutes > 0) { if (minutes == 1) text += minutes + " minute."; else text += minutes + " minutes."; } else { if (seconds == 1) text += seconds + " second."; else text += seconds + " seconds."; } int attempts = fail_info.get("attempts").asInt(); if (attempts > 1) text += " (" + ordinal(attempts) + " attempt)"; statusView.setText(text); statusView.setTextColor(colorScheme.networkErrorColor); statusView.setBackgroundColor(colorScheme.networkErrorBackgroundColor); statusRefreshRunnable = new StatusRefreshRunnable(status, fail_info); } else { statusView.setVisibility(View.VISIBLE); statusView.setText("Ready to connect, waiting our turn…"); } mHandler.postDelayed(statusRefreshRunnable, 500); } catch (Exception e) { NetworkConnection.printStackTraceToCrashlytics(e); } break; case "ip_retry": statusView.setVisibility(View.VISIBLE); statusView.setText("Trying another IP address"); break; } } private void update_global_msg() { if (globalMsgView != null) { if (conn != null && conn.globalMsg != null) { globalMsg.setText(Html.fromHtml(conn.globalMsg)); globalMsgView.setVisibility(View.VISIBLE); } else { globalMsgView.setVisibility(View.GONE); } } } @Override public void onPause() { super.onPause(); if(getActivity() == null || !((BaseActivity)getActivity()).isMultiWindow()) { if (statusRefreshRunnable != null) { mHandler.removeCallbacks(statusRefreshRunnable); statusRefreshRunnable = null; } try { getListView().setOnScrollListener(null); } catch (Exception e) { } ready = false; } } public void onIRCEvent(int what, final Object obj) { IRCCloudJSONObject e; switch (what) { case NetworkConnection.EVENT_BACKLOG_FAILED: runOnUiThread(new Runnable() { @Override public void run() { headerView.setVisibility(View.GONE); backlogFailed.setVisibility(View.VISIBLE); loadBacklogButton.setVisibility(View.VISIBLE); } }); break; case NetworkConnection.EVENT_BACKLOG_END: case NetworkConnection.EVENT_CONNECTIVITY: case NetworkConnection.EVENT_USERINFO: if(buffer != null) { runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } break; case NetworkConnection.EVENT_CONNECTIONLAG: try { IRCCloudJSONObject object = (IRCCloudJSONObject) obj; if (server != null && buffer != null && object.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { update_status(server.getStatus(), server.getFail_info()); } }); } } catch (Exception ex) { NetworkConnection.printStackTraceToCrashlytics(ex); } break; case NetworkConnection.EVENT_STATUSCHANGED: try { final IRCCloudJSONObject object = (IRCCloudJSONObject) obj; if (buffer != null && object.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { update_status(object.getString("new_status"), object.getJsonObject("fail_info")); } }); } } catch (Exception ex) { NetworkConnection.printStackTraceToCrashlytics(ex); } break; case NetworkConnection.EVENT_SETIGNORES: e = (IRCCloudJSONObject) obj; if (buffer != null && e.cid() == buffer.getCid()) { runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } break; case NetworkConnection.EVENT_HEARTBEATECHO: try { if (buffer != null && adapter != null && adapter.data.size() > 0) { if (buffer.getLast_seen_eid() == adapter.data.get(adapter.data.size() - 1).eid || !pref_trackUnread) { runOnUiThread(new Runnable() { @Override public void run() { hideView(unreadTopView); } }); } } } catch (Exception ex) { } break; case NetworkConnection.EVENT_CHANNELTOPIC: case NetworkConnection.EVENT_JOIN: case NetworkConnection.EVENT_PART: case NetworkConnection.EVENT_NICKCHANGE: case NetworkConnection.EVENT_QUIT: case NetworkConnection.EVENT_KICK: case NetworkConnection.EVENT_CHANNELMODE: case NetworkConnection.EVENT_USERMODE: case NetworkConnection.EVENT_USERCHANNELMODE: e = (IRCCloudJSONObject) obj; if (buffer != null && e.bid() == buffer.getBid()) { final Event event = EventsList.getInstance().getEvent(e.eid(), e.bid()); runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null) insertEvent(adapter, event, false, false); } }); } break; case NetworkConnection.EVENT_SELFDETAILS: case NetworkConnection.EVENT_BUFFERMSG: final Event event = (Event) obj; if (buffer != null && event.bid == buffer.getBid()) { if (event.from != null && event.from.equalsIgnoreCase(buffer.getName()) && event.reqid == -1) { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null) adapter.clearPending(); } }); } else if (event.reqid != -1) { runOnUiThread(new Runnable() { @Override public void run() { if (adapter != null && adapter.data != null) { for (int i = 0; i < adapter.data.size(); i++) { Event e = adapter.data.get(i); if (e.reqid == event.reqid && e.pending) { if (i > 0) { Event p = adapter.data.get(i - 1); if (p.row_type == ROW_TIMESTAMP) { adapter.data.remove(p); i--; } } adapter.data.remove(e); i--; } } } } }); } runOnUiThread(new Runnable() { @Override public void run() { insertEvent(adapter, event, false, false); } }); if (event.pending && event.self && adapter != null && getListView() != null) { runOnUiThread(new Runnable() { @Override public void run() { getListView().setSelection(adapter.getCount() - 1); } }); } } Buffer b = BuffersList.getInstance().getBuffer(event.bid); if (b != null && !b.getScrolledUp() && EventsList.getInstance().getSizeOfBuffer(b.getBid()) > 200) { EventsList.getInstance().pruneEvents(b.getBid()); if (buffer != null && b.getBid() == buffer.getBid()) { if (b.getLast_seen_eid() < event.eid && unreadTopView.getVisibility() == View.GONE) b.setLast_seen_eid(event.eid); runOnUiThread(new Runnable() { @Override public void run() { if (refreshTask != null) refreshTask.cancel(true); refreshTask = new RefreshTask(); refreshTask.execute((Void) null); } }); } } break; case NetworkConnection.EVENT_AWAY: case NetworkConnection.EVENT_SELFBACK: if (server != null) { runOnUiThread(new Runnable() { @Override public void run() { if (server.getAway() != null && server.getAway().length() > 0) { awayTxt.setText(ColorFormatter.html_to_spanned(ColorFormatter.irc_to_html(TextUtils.htmlEncode("Away (" + server.getAway() + ")"))).toString()); awayView.setVisibility(View.VISIBLE); } else { awayView.setVisibility(View.GONE); } } }); } break; case NetworkConnection.EVENT_GLOBALMSG: runOnUiThread(new Runnable() { @Override public void run() { update_global_msg(); } }); break; default: break; } } @Override public void onIRCRequestSucceeded(int reqid, IRCCloudJSONObject object) { } @Override public void onIRCRequestFailed(int reqid, IRCCloudJSONObject object) { } public static Resources getSafeResources() { return IRCCloudApplication.getInstance().getApplicationContext().getResources(); } public interface MessageViewListener extends OnBufferSelectedListener { public void onMessageViewReady(); public boolean onMessageLongClicked(Event event); public void onMessageDoubleClicked(Event event); public void onFailedMessageClicked(Event event); } }
smaller spacing around the new messages marker
src/com/irccloud/android/fragment/MessageViewFragment.java
smaller spacing around the new messages marker
Java
apache-2.0
2abcc10a5deb0c24adc5f799431488095a4ffbc2
0
basheersubei/swift-t,blue42u/swift-t,basheersubei/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,blue42u/swift-t,blue42u/swift-t,blue42u/swift-t,JohnPJenkins/swift-t,blue42u/swift-t,swift-lang/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,basheersubei/swift-t,swift-lang/swift-t,blue42u/swift-t,swift-lang/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,swift-lang/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t,JohnPJenkins/swift-t,basheersubei/swift-t
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package exm.stc.frontend; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import exm.stc.ast.SwiftAST; import exm.stc.ast.antlr.ExMParser; import exm.stc.common.Logging; import exm.stc.common.exceptions.STCRuntimeError; import exm.stc.common.exceptions.TypeMismatchException; import exm.stc.common.exceptions.UndefinedFunctionException; import exm.stc.common.exceptions.UndefinedOperatorException; import exm.stc.common.exceptions.UserException; import exm.stc.common.lang.ForeignFunctions; import exm.stc.common.lang.Operators; import exm.stc.common.lang.Operators.Op; import exm.stc.common.lang.Operators.OpType; import exm.stc.common.lang.Types; import exm.stc.common.lang.Types.ArrayType; import exm.stc.common.lang.Types.ExprType; import exm.stc.common.lang.Types.FunctionType; import exm.stc.common.lang.Types.RefType; import exm.stc.common.lang.Types.ScalarFutureType; import exm.stc.common.lang.Types.ScalarUpdateableType; import exm.stc.common.lang.Types.StructType; import exm.stc.common.lang.Types.Type; import exm.stc.common.lang.Types.UnionType; import exm.stc.common.lang.Var; import exm.stc.common.util.MultiMap; import exm.stc.common.util.Pair; import exm.stc.common.util.TernaryLogic.Ternary; import exm.stc.frontend.tree.ArrayElems; import exm.stc.frontend.tree.ArrayRange; import exm.stc.frontend.tree.Assignment.AssignOp; import exm.stc.frontend.tree.FunctionCall; /** * This module handles checking the internal consistency of expressions, * and inferring the types of expressions in the SwiftScript AST */ public class TypeChecker { /** * Determine the expected type of an expression. If the expression is valid, * then this will return the type of the expression. If it is invalid, * it will throw an exception. * * @param context * the context in which the expression resides * @param tree * the expression tree * @return * @throws UserException */ public static ExprType findExprType(Context context, SwiftAST tree) throws UserException { // Memoize this function to avoid recalculating type ExprType cached = tree.getExprType(); if (cached != null) { LogHelper.trace(context, "Expr has cached type " + cached.toString()); return cached; } else { ExprType calcedType = uncachedFindExprType(context, tree); tree.setType(calcedType); LogHelper.trace(context, "Expr found type " + calcedType.toString()); return calcedType; } } private static ExprType uncachedFindExprType(Context context, SwiftAST tree) throws UserException { int token = tree.getType(); switch (token) { case ExMParser.CALL_FUNCTION: { return callFunction(context, tree, true); } case ExMParser.VARIABLE: { Var var = context.lookupVarUser(tree.child(0).getText()); Type exprType = var.type(); if (Types.isScalarUpdateable(exprType)) { // Can coerce to future return new ExprType(UnionType.createUnionType(exprType, ScalarUpdateableType.asScalarFuture(exprType))); } return new ExprType(exprType); } case ExMParser.INT_LITERAL: // interpret as float return new ExprType(UnionType.createUnionType(Types.F_INT, Types.F_FLOAT)); case ExMParser.FLOAT_LITERAL: return new ExprType(Types.F_FLOAT); case ExMParser.STRING_LITERAL: return new ExprType(Types.F_STRING); case ExMParser.BOOL_LITERAL: return new ExprType(Types.F_BOOL); case ExMParser.OPERATOR: return findOperatorResultType(context, tree); case ExMParser.STRUCT_LOAD: ExprType structTypeL = findExprType(context, tree.child(0)); String fieldName = tree.child(1).getText(); if (structTypeL.elems() != 1) { throw new TypeMismatchException(context, "Trying to lookup field on return value of function with" + " zero or multiple return values"); } Type structType = structTypeL.get(0); Type fieldType; fieldType = findStructFieldType(context, fieldName, structType); if (fieldType == null) { throw new TypeMismatchException(context, "No field called " + fieldName + " in structure type " + ((StructType) structType).getTypeName()); } if (Types.isStruct(structType)) { return new ExprType(fieldType); } else { assert(Types.isStructRef(structType)); return new ExprType(dereferenceResultType(fieldType)); } case ExMParser.ARRAY_LOAD: Type arrType = findSingleExprType(context, tree.child(0)); List<Type> resultAlts = new ArrayList<Type>(); for (Type arrAlt: UnionType.getAlternatives(arrType)) { if (Types.isArray(arrAlt) || Types.isArrayRef(arrAlt)) { Type memberType = Types.containerElemType(arrAlt); // Depending on the member type of the array, the result type might be // the actual member type, or a reference to the member type resultAlts.add(dereferenceResultType(memberType)); } else { throw new TypeMismatchException(context, "Trying to index into non-array expression of type " + arrType.toString()); } } return new ExprType(UnionType.makeUnion(resultAlts)); case ExMParser.ARRAY_RANGE: { // Check the arguments for type validity ArrayRange ar = ArrayRange.fromAST(context, tree); ar.typeCheck(context); // Type is always the same: an array of integers return new ExprType(ArrayType.sharedArray(Types.F_INT, Types.F_INT)); } case ExMParser.ARRAY_ELEMS: case ExMParser.ARRAY_KV_ELEMS: { return ArrayElems.fromAST(context, tree).getType(context); } default: throw new STCRuntimeError("Unexpected token type in expression context: " + LogHelper.tokName(token)); } } /** * Find the type of a particular field * @param context * @param fieldName * @param type a struct or a reference to a struct * @return * @throws TypeMismatchException if the type isn't a struct or struct ref, * or the field doesn't exist in the type */ public static Type findStructFieldType(Context context, String fieldName, Type type) throws TypeMismatchException { StructType structType; if (Types.isStruct(type)) { structType = ((StructType) type); } else if (Types.isStructRef(type)) { structType = ((StructType) (type.memberType())); } else { throw new TypeMismatchException(context, "Trying to access named field " + fieldName + " on non-struct expression of type " + type.toString()); } Type fieldType = structType.getFieldTypeByName(fieldName); if (fieldType == null) { throw new TypeMismatchException(context, "Field named " + fieldName + " does not exist in structure type " + structType.typeName()); } return fieldType; } /** * Same as findExprType, but check that we don't have a multiple * value type * @param context * @param tree * @return * @throws UserException */ public static Type findSingleExprType(Context context, SwiftAST tree) throws UserException { ExprType typeL = findExprType(context, tree); if (typeL.elems() != 1) { throw new TypeMismatchException(context, "Expected expression to have " + "a single value, instead had " + typeL.elems() + " values"); } return typeL.get(0); } private static String extractOpName(SwiftAST opTree) { int tok = opTree.child(0).getType(); try { return ExMParser.tokenNames[tok].toLowerCase(); } catch (IndexOutOfBoundsException ex) { throw new STCRuntimeError("Out of range token number: " + tok); } } private static ExprType findOperatorResultType(Context context, SwiftAST tree) throws TypeMismatchException, UserException { ArrayList<Type> argTypes = new ArrayList<Type>(); List<Op> ops = getOpsFromTree(context, tree, argTypes); assert(ops != null); assert(ops.size() > 0); // Handle possibility of multiple return types List<Type> alternatives = new ArrayList<Type>(ops.size()); for (Op op: ops) { alternatives.add(new ScalarFutureType(op.type.out)); } return new ExprType(UnionType.makeUnion(alternatives)); } /** * Get a list of possible matches * @param context * @param tree * @param argTypes * @return * @throws UserException */ public static List<Op> getOpsFromTree(Context context, SwiftAST tree, List<Type> argTypes) throws UserException { return getOpsFromTree(context, tree, null, argTypes, false); } /** * Get the final operator match using output argument info * @param context * @param tree * @param outType * @return * @throws UserException */ public static Op getOpFromTree(Context context, SwiftAST tree, Type outType) throws UserException { List<Op> matches = getOpsFromTree(context, tree, outType, null, true); assert(matches.size() > 0); return matches.get(0); } /** * * @param context * @param tree * @param expectedResult * @param outType if not null, only return operators with this output type * @param outArgTypes Put the argument types of the operator in this list if not null * @param expectUnambig at this stage, expect operator not to be ambiguous - log * debug message if it is * @return at least one builtin operator * @throws TypeMismatchException if no matches possible */ private static List<Op> getOpsFromTree(Context context, SwiftAST tree, Type outType, List<Type> outArgTypes, boolean expectUnambig) throws UserException { assert(tree.getType() == ExMParser.OPERATOR); assert(tree.getChildCount() >= 1); int opTok = tree.child(0).getType(); String opName = extractOpName(tree); List<Type> argTypes = findOperatorArgTypes(context, tree, opName); if (outArgTypes != null) { // Store for caller outArgTypes.clear(); outArgTypes.addAll(argTypes); } // Track operators that matched List<Op> matched = new ArrayList<Op>(); for (Op candidate: Operators.getOps(opTok)) { // TODO: check input types OpType opType = candidate.type; if (opOutputMatches(outType, opType) && opInputsMatch(argTypes, opType)) { matched.add(candidate); } } if (matched.size() != 1) { // Hope to match exactly one operator List<String> typeNames = new ArrayList<String>(); for (Type argType: argTypes) { typeNames.add(argType.typeName()); } if (matched.size() == 0) { // Error - no matches String msg = "Operator " + opName + " not supported for these input " + "types : " + typeNames.toString(); if (outType != null) { msg += " and output type " + outType; } throw new UndefinedOperatorException(context, msg); } else if (expectUnambig) { // Ambiguous operator - might be of interest assert(matched.size() > 1); Logging.getSTCLogger().debug("Ambiguous operator " + opName + " for arg types " + typeNames + ". Matched: " + matched.toString()); } } return matched; } private static boolean opInputsMatch(List<Type> argTypes, OpType opType) { if (argTypes.size() != opType.in.size()) { return false; } for (int i = 0; i < argTypes.size(); i++) { ScalarFutureType inFT = new ScalarFutureType(opType.in.get(i)); if (!argTypes.get(i).assignableTo(inFT)) { return false; } } return true; } private static boolean opOutputMatches(Type outType, OpType opType) { return outType == null || (opType.out != null && new ScalarFutureType(opType.out).assignableTo(outType)); } /** * Find the argument type of the operators to a function * assuming all operators take all the same argument types. * Preference order of types determined by first expression's * union type order * @param context * @param tree * @param opName * @param argTypes used to return arg types of function, null for no return * @return * @throws TypeMismatchException * @throws UserException */ private static List<Type> findOperatorArgTypes(Context context, SwiftAST tree, String opName) throws TypeMismatchException, UserException { int argcount = tree.getChildCount() - 1; if (argcount == 0) { throw new TypeMismatchException(context, "provided no arguments to operator " + opName); } List<Type> argTypes = new ArrayList<Type>(argcount); for (SwiftAST argTree: tree.children(1)) { argTypes.add(findSingleExprType(context, argTree)); } return argTypes; } /** * The type of the internal variable that will be created from an array * dereference * * @param memberType * the type of array memebrs for the array being dereferenced * @return */ public static Type dereferenceResultType(Type memberType) { Type resultType; if (Types.isPrimFuture(memberType)) { resultType = memberType; } else if (Types.isContainer(memberType) || Types.isStruct(memberType)) { resultType = new RefType(memberType); } else { throw new STCRuntimeError("Unexpected array member type" + memberType.toString()); } return resultType; } private static TypeMismatchException argumentTypeException(Context context, int argPos, Type expType, Type actType, String errContext) { return new TypeMismatchException(context, "Expected argument " + (argPos + 1) + " to have one of the following types: " + expType.typeName() + ", but had type: " + actType.typeName() + errContext); } /** * * @param formalArgT * @param argExprT * @return (selected type of argument, selected type of variable) */ public static Pair<Type, Type> whichAlternativeType(Type formalArgT, Type argExprT) { /* * Handles cases where both function formal argument type and expression type * are union types. In case of multiple possibilities prefers picking first * alternative in expression type, followed by first formal argument alternative */ for (Type argExprAlt: UnionType.getAlternatives(argExprT)) { // Handle if argument type is union. for (Type formalArgAlt: UnionType.getAlternatives(formalArgT)) { Type concreteArgType = compatibleArgTypes(formalArgAlt, argExprAlt); if (concreteArgType != null) { return Pair.create(formalArgAlt, concreteArgType); } } } return null; // if no alternatives } /** * Check if an expression type can be used for function argument * @param argType non-polymorphic function argument type * @param exprType type of argument expression * @return concretized argType if compatible, null if incompatible */ public static Type compatibleArgTypes(Type argType, Type exprType) { if (exprType.assignableTo(argType)) { // Obviously ok if types are exactly the same return exprType.concretize(argType); } else if (Types.isAssignableRefTo(exprType, argType)) { // We can block on reference, so we can transform type here return exprType.concretize(new RefType(argType)); } else { return null; } } private static ExprType callFunction(Context context, SwiftAST tree, boolean noWarn) throws UndefinedFunctionException, UserException { FunctionCall f = FunctionCall.fromAST(context, tree, false); List<FunctionType> alts = concretiseFunctionCall(context, f.function(), f.type(), f.args(), noWarn); if (alts.size() == 1) { // Function type determined entirely by input type return new ExprType(alts.get(0).getOutputs()); } else { // Ambiguous type variable binding (based on inputs) assert(alts.size() >= 2); int numOutputs = f.type().getOutputs().size(); if (numOutputs == 0) { return new ExprType(Collections.<Type>emptyList()); } else { // Turn into a list of UnionTypes List<Type> altOutputs = new ArrayList<Type>(); for (int out = 0; out < numOutputs; out++) { List<Type> altOutput = new ArrayList<Type>(); for (FunctionType ft: alts) { altOutput.add(ft.getOutputs().get(out)); } altOutputs.add(UnionType.makeUnion(altOutput)); } return new ExprType(altOutputs); } } } public static FunctionType concretiseFunctionCall(Context context, String function, FunctionType abstractType, List<SwiftAST> args, List<Var> outputs, boolean firstCall) throws UserException { List<Type> outTs = new ArrayList<Type>(outputs.size()); for (Var output: outputs) { checkFunctionOutputValid(context, function, output); outTs.add(output.type()); } List<FunctionType> alts = concretiseFunctionCall(context, function, abstractType, args, firstCall); assert(alts.size() > 0); for (FunctionType alt: alts) { assert(alt.getOutputs().size() == outputs.size()); boolean match = true; for (int i = 0; i < outTs.size(); i++) { if (!alt.getOutputs().get(i).assignableTo(outTs.get(i))) { match = false; break; } } LogHelper.trace(context, "Call " + function + " alternative " + "function type " + alt + " match: " + match); // Choose first viable alternative if (match) { return alt; } } throw new TypeMismatchException(context, "Could not find consistent " + "binding for type variables. Viable function signatures based on " + "input arguments were: " + alts + " but output types were " + outTs); } /** * Check that function output var is valid * @param output * @throws TypeMismatchException */ private static void checkFunctionOutputValid(Context context, String function, Var output) throws TypeMismatchException { if (Types.isFile(output) && output.isMapped() == Ternary.FALSE && !output.type().fileKind().supportsTmpImmediate() && !ForeignFunctions.initsOutputMapping(function)) { /* * We can't create temporary files for this type. If we detect any * where a definitely unmapped var is an output to a function, then * we can avoid generating code where this happens. Why? * Suppose that write a program where a leaf function is called with * an unmapped output file. There are two cases: * 1. The unmapped input file is declared in the same scope as * the leaf function => isMapped() == false and we're done. * 2. The unmapped input file is a function output argument => * backtrack through the caller hierarchy until we reach the * function where the unmapped variable was declared. In that * function we called a composite function with the (definitely) * unmapped variable for which isMapped() == false. * So by this simple check we can prevent leaf functions being called * with unmapped output files. * The exception to this is a special function that will initialize an * unmapped variable on its own */ throw new TypeMismatchException(context, "Type " + output.type().typeName() + " does not support creating temporary files. Unmapped var " + output.name() + " cannot be used as function output variable."); } } /** * @param context * @param abstractType function type with varargs, typevars, union types * @param args input argument expressions * @param noWarn don't issue warnings * @return list of possible concrete function types with varargs, typevars * and union type args removed * @throws UserException */ public static List<FunctionType> concretiseFunctionCall(Context context, String func, FunctionType abstractType, List<SwiftAST> args, boolean noWarn) throws UserException { List<Type> argTypes = new ArrayList<Type>(args.size()); for (SwiftAST arg: args) { argTypes.add(findSingleExprType(context, arg)); } // Expand varargs List<Type> expandedInputs = expandVarargs(context, abstractType, func, args.size()); // Narrow down possible bindings - choose union types // find possible typevar bindings List<Type> specificInputs = new ArrayList<Type>(args.size()); MultiMap<String, Type> tvConstraints = new MultiMap<String, Type>(); for (int i = 0; i < args.size(); i++) { Type exp = expandedInputs.get(i); Type act = argTypes.get(i); // a more specific type than expected Type exp2; exp2 = narrowArgType(context, func, i, exp, act, tvConstraints); specificInputs.add(exp2); } LogHelper.trace(context, "Call " + func + " specificInputs: " + specificInputs + " possible bindings: " + tvConstraints); // Narrow down type variable bindings depending on constraints Map<String, List<Type>> bindings = unifyTypeVarConstraints(context, func, abstractType.getTypeVars(), tvConstraints, noWarn); LogHelper.trace(context, "Call " + func + " unified bindings: " + tvConstraints); List<FunctionType> possibilities = findPossibleFunctionTypes(context, func, abstractType, specificInputs, bindings); LogHelper.trace(context, "Call " + func + " possible concrete types: " + possibilities); if (possibilities.size() == 0) { throw new TypeMismatchException(context, "Arguments for call to " + "function " + func + " were incompatible with function " + "type. Function input types were: " + abstractType.getInputs() + ", argument types were " + argTypes); } return possibilities; } /** * Narrow down the possible argument types for a function call * @param context * @param func * @param arg number of argument * @param formalArgT Formal argument type from abstract function type * @param argExprT Type of argument expression for function * @param tvConstrains Filled in with constraints for each type variable * @return * @throws TypeMismatchException */ private static Type narrowArgType(Context context, String func, int arg, Type formalArgT, Type argExprT, MultiMap<String, Type> tvConstrains) throws TypeMismatchException { if (formalArgT.hasTypeVar()) { return checkFunArgTV(context, func, arg, formalArgT, argExprT, tvConstrains); } else { return checkFunArg(context, func, arg, formalArgT, argExprT).val1; } } /** * Check function argument type * Returns a tuple indicating which formal argument type is selected and * what type the input argument expression should be interpreted as having. * Does not handle type variables * @param context * @param function * @param argNum * @param formalArgT * @param argExprT * @return (selected formal argument type, selected argument expression type) * @throws TypeMismatchException */ public static Pair<Type, Type> checkFunArg(Context context, String function, int argNum, Type formalArgT, Type argExprT) throws TypeMismatchException { assert(!formalArgT.hasTypeVar()); Pair<Type, Type> res = whichAlternativeType(formalArgT, argExprT); if (res == null) { throw argumentTypeException(context, argNum, formalArgT, argExprT, " in call to function " + function); } assert(res.val1.isConcrete()) : "Non-concrete arg type: " + res.val1; assert(res.val2.isConcrete()) : "Non-concrete arg type: " + res.val2; return res; } /** * Check function argument type * Returns which formal argument type is selected. * Only handles case where formalArgT has a type variable * @param context * @param func * @param arg * @param formalArgT * @param argExprT * @param tvConstraints fill in constraints for type variables * @return * @throws TypeMismatchException */ private static Type checkFunArgTV(Context context, String func, int arg, Type formalArgT, Type argExprT, MultiMap<String, Type> tvConstraints) throws TypeMismatchException { if (Types.isUnion(formalArgT)) { throw new TypeMismatchException(context, "Union type " + formalArgT + " with type variable is not supported"); } if (Types.isRef(argExprT)) { // Will be dereferenced argExprT = argExprT.memberType(); } if (Types.isUnion(argExprT)) { List<Map<String, Type>> possible = new ArrayList<Map<String,Type>>(); for (Type alt: UnionType.getAlternatives(argExprT)) { possible.add(formalArgT.matchTypeVars(alt)); } // Sanity check: ensure that all bind the same type variables for (Map<String, Type> m: possible) { assert(m.keySet().equals(possible.get(0).keySet())); } for (String boundVar: possible.get(0).keySet()) { List<Type> choices = new ArrayList<Type>(); for (Map<String, Type> m: possible) { Type t = m.get(boundVar); assert(!Types.isUnion(t)); // Shouldn't be union inside union choices.add(t); } tvConstraints.put(boundVar, UnionType.makeUnion(choices)); } } else { Map<String, Type> matchedTypeVars = formalArgT.matchTypeVars(argExprT); if (matchedTypeVars == null) { throw new TypeMismatchException(context, "Could not match type " + "variables for formal arg type " + formalArgT + " and argument " + " expression type: " + argExprT); } tvConstraints.putAll(matchedTypeVars); } // Leave type var return formalArgT; } private static List<FunctionType> findPossibleFunctionTypes(Context context, String function, FunctionType abstractType, List<Type> specificInputs, Map<String, List<Type>> bindings) throws TypeMismatchException { List<String> typeVars = new ArrayList<String>(abstractType.getTypeVars()); // Handle case where type variables are unbound for (ListIterator<String> it = typeVars.listIterator(); it.hasNext(); ) { if (!bindings.containsKey(it.next())) { it.remove(); } } int currChoices[] = new int[typeVars.size()]; // initialized to zero List<FunctionType> possibilities = new ArrayList<FunctionType>(); while (true) { Map<String, Type> currBinding = new HashMap<String, Type>(); for (int i = 0; i < currChoices.length; i++) { String tv = typeVars.get(i); currBinding.put(tv, bindings.get(tv).get(currChoices[i])); } possibilities.add(constructFunctionType(abstractType, specificInputs, currBinding)); int pos = currChoices.length - 1; while (pos >= 0 && currChoices[pos] >= bindings.get(typeVars.get(pos)).size() - 1) { pos--; } if (pos < 0) { break; } else { currChoices[pos]++; for (int i = pos + 1; i < currChoices.length; i++) { currChoices[i] = 0; } } } return possibilities; } private static FunctionType constructFunctionType(FunctionType abstractType, List<Type> inputs, Map<String, Type> binding) { List<Type> concreteInputs = bindTypeVariables(inputs, binding); List<Type> concreteOutputs = bindTypeVariables( abstractType.getOutputs(), binding); return new FunctionType(concreteInputs, concreteOutputs, false); } private static List<Type> expandVarargs(Context context, FunctionType abstractType, String function, int numArgs) throws TypeMismatchException { List<Type> abstractInputs = abstractType.getInputs(); if (abstractType.hasVarargs()) { if (numArgs < abstractInputs.size() - 1) { throw new TypeMismatchException(context, "Too few arguments in " + "call to function " + function + ": expected >= " + (abstractInputs.size() - 1) + " but got " + numArgs); } } else if (abstractInputs.size() != numArgs) { throw new TypeMismatchException(context, "Wrong number of arguments in " + "call to function " + function + ": expected " + abstractInputs.size() + " but got " + numArgs); } if (abstractType.hasVarargs()) { List<Type> expandedInputs; expandedInputs = new ArrayList<Type>(); expandedInputs.addAll(abstractInputs.subList(0, abstractInputs.size() - 1)); Type varArgType = abstractInputs.get(abstractInputs.size() - 1); for (int i = abstractInputs.size() - 1; i < numArgs; i++) { expandedInputs.add(varArgType); } return expandedInputs; } else { return abstractInputs; } } private static List<Type> bindTypeVariables(List<Type> types, Map<String, Type> binding) { List<Type> res = new ArrayList<Type>(types.size()); for (Type type: types) { res.add(type.bindTypeVars(binding)); } return res; } public static void checkCopy(Context context, Type srctype, Type dsttype) throws TypeMismatchException { if (!(srctype.assignableTo(dsttype) && srctype.getImplType().equals(dsttype.getImplType()))) { new Exception().printStackTrace(); throw new TypeMismatchException(context, "Type mismatch: copying from " + srctype.toString() + " to " + dsttype.toString()); } } public static Type checkAssignment(Context context, Type rValType, Type lValType, String lValName) throws TypeMismatchException { return checkAssignment(context, AssignOp.ASSIGN, rValType, lValType, lValName); } /** * Checks whether rValType can be assigned to lValType * @param context * @param op * @param rValType * @param lValType * @param lValName * @return returns rValType, or if rValType is a union, return chosen * member of union * @throws TypeMismatchException */ public static Type checkAssignment(Context context, AssignOp op, Type rValType, Type lValType, String lValName) throws TypeMismatchException { Type targetLValType; if (op == AssignOp.ASSIGN) { targetLValType = lValType; } else { assert(op == AssignOp.APPEND); targetLValType = Types.containerElemType(lValType); } for (Type altRValType: UnionType.getAlternatives(rValType)) { if (altRValType.assignableTo(targetLValType) || (Types.isRef(targetLValType) && altRValType.assignableTo(targetLValType.memberType())) || (Types.isRef(altRValType) && altRValType.memberType().assignableTo(targetLValType))) { return altRValType; } } throw new TypeMismatchException(context, "Cannot " + op.toString().toLowerCase() + " to " + lValName + ": LVal has type " + lValType.toString() + " but RVal has type " + rValType.toString()); } /** * Create dictionary with null type var bindings * @param ftype * @return */ public static MultiMap<String, Type> typeVarBindings(FunctionType ftype) { return new MultiMap<String, Type>(); } /** * @param candidates MultiMap, with possible bindings for each type variable * @return map of type variable name to possible types. If list is null, * this means no constraint on type variable * @throws TypeMismatchException if no viable binding */ public static Map<String, List<Type>> unifyTypeVarConstraints( Context context, String function, List<String> typeVars, MultiMap<String, Type> candidates, boolean noWarn) throws TypeMismatchException { Map<String, List<Type>> possible = new HashMap<String, List<Type>>(); /* Check whether type variables were left unbound */ for (String typeVar: typeVars) { List<Type> cands = candidates.get(typeVar); if (cands == null || cands.size() == 0) { if (!noWarn) { LogHelper.warn(context, "Type variable " + typeVar + " for call to " + "function " + function + " was unbound"); } } else { List<Type> intersection = Types.typeIntersection(cands); if (intersection.size() == 0) { throw new TypeMismatchException(context, "Type variable " + typeVar + " for call to function " + function + " could not be bound to concrete type: no " + "intersection between types: " + cands); } possible.put(typeVar, intersection); } } return possible; } }
code/src/exm/stc/frontend/TypeChecker.java
/* * Copyright 2013 University of Chicago and Argonne National Laboratory * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package exm.stc.frontend; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import exm.stc.ast.SwiftAST; import exm.stc.ast.antlr.ExMParser; import exm.stc.common.Logging; import exm.stc.common.exceptions.STCRuntimeError; import exm.stc.common.exceptions.TypeMismatchException; import exm.stc.common.exceptions.UndefinedFunctionException; import exm.stc.common.exceptions.UndefinedOperatorException; import exm.stc.common.exceptions.UserException; import exm.stc.common.lang.ForeignFunctions; import exm.stc.common.lang.Operators; import exm.stc.common.lang.Operators.Op; import exm.stc.common.lang.Operators.OpType; import exm.stc.common.lang.Types; import exm.stc.common.lang.Types.ArrayType; import exm.stc.common.lang.Types.ExprType; import exm.stc.common.lang.Types.FunctionType; import exm.stc.common.lang.Types.RefType; import exm.stc.common.lang.Types.ScalarFutureType; import exm.stc.common.lang.Types.ScalarUpdateableType; import exm.stc.common.lang.Types.StructType; import exm.stc.common.lang.Types.Type; import exm.stc.common.lang.Types.UnionType; import exm.stc.common.lang.Var; import exm.stc.common.util.MultiMap; import exm.stc.common.util.Pair; import exm.stc.common.util.TernaryLogic.Ternary; import exm.stc.frontend.tree.ArrayElems; import exm.stc.frontend.tree.ArrayRange; import exm.stc.frontend.tree.Assignment.AssignOp; import exm.stc.frontend.tree.FunctionCall; /** * This module handles checking the internal consistency of expressions, * and inferring the types of expressions in the SwiftScript AST */ public class TypeChecker { /** * Determine the expected type of an expression. If the expression is valid, * then this will return the type of the expression. If it is invalid, * it will throw an exception. * * @param context * the context in which the expression resides * @param tree * the expression tree * @return * @throws UserException */ public static ExprType findExprType(Context context, SwiftAST tree) throws UserException { // Memoize this function to avoid recalculating type ExprType cached = tree.getExprType(); if (cached != null) { LogHelper.trace(context, "Expr has cached type " + cached.toString()); return cached; } else { ExprType calcedType = uncachedFindExprType(context, tree); tree.setType(calcedType); LogHelper.trace(context, "Expr found type " + calcedType.toString()); return calcedType; } } private static ExprType uncachedFindExprType(Context context, SwiftAST tree) throws UserException { int token = tree.getType(); switch (token) { case ExMParser.CALL_FUNCTION: { return callFunction(context, tree, true); } case ExMParser.VARIABLE: { Var var = context.lookupVarUser(tree.child(0).getText()); Type exprType = var.type(); if (Types.isScalarUpdateable(exprType)) { // Can coerce to future return new ExprType(UnionType.createUnionType(exprType, ScalarUpdateableType.asScalarFuture(exprType))); } return new ExprType(exprType); } case ExMParser.INT_LITERAL: // interpret as float return new ExprType(UnionType.createUnionType(Types.F_INT, Types.F_FLOAT)); case ExMParser.FLOAT_LITERAL: return new ExprType(Types.F_FLOAT); case ExMParser.STRING_LITERAL: return new ExprType(Types.F_STRING); case ExMParser.BOOL_LITERAL: return new ExprType(Types.F_BOOL); case ExMParser.OPERATOR: return findOperatorResultType(context, tree); case ExMParser.STRUCT_LOAD: ExprType structTypeL = findExprType(context, tree.child(0)); String fieldName = tree.child(1).getText(); if (structTypeL.elems() != 1) { throw new TypeMismatchException(context, "Trying to lookup field on return value of function with" + " zero or multiple return values"); } Type structType = structTypeL.get(0); Type fieldType; fieldType = findStructFieldType(context, fieldName, structType); if (fieldType == null) { throw new TypeMismatchException(context, "No field called " + fieldName + " in structure type " + ((StructType) structType).getTypeName()); } if (Types.isStruct(structType)) { return new ExprType(fieldType); } else { assert(Types.isStructRef(structType)); return new ExprType(dereferenceResultType(fieldType)); } case ExMParser.ARRAY_LOAD: Type arrType = findSingleExprType(context, tree.child(0)); List<Type> resultAlts = new ArrayList<Type>(); for (Type arrAlt: UnionType.getAlternatives(arrType)) { if (Types.isArray(arrAlt) || Types.isArrayRef(arrAlt)) { Type memberType = Types.containerElemType(arrAlt); // Depending on the member type of the array, the result type might be // the actual member type, or a reference to the member type resultAlts.add(dereferenceResultType(memberType)); } else { throw new TypeMismatchException(context, "Trying to index into non-array expression of type " + arrType.toString()); } } return new ExprType(UnionType.makeUnion(resultAlts)); case ExMParser.ARRAY_RANGE: { // Check the arguments for type validity ArrayRange ar = ArrayRange.fromAST(context, tree); ar.typeCheck(context); // Type is always the same: an array of integers return new ExprType(ArrayType.sharedArray(Types.F_INT, Types.F_INT)); } case ExMParser.ARRAY_ELEMS: case ExMParser.ARRAY_KV_ELEMS: { return ArrayElems.fromAST(context, tree).getType(context); } default: throw new STCRuntimeError("Unexpected token type in expression context: " + LogHelper.tokName(token)); } } /** * Find the type of a particular field * @param context * @param fieldName * @param type a struct or a reference to a struct * @return * @throws TypeMismatchException if the type isn't a struct or struct ref, * or the field doesn't exist in the type */ public static Type findStructFieldType(Context context, String fieldName, Type type) throws TypeMismatchException { StructType structType; if (Types.isStruct(type)) { structType = ((StructType) type); } else if (Types.isStructRef(type)) { structType = ((StructType) (type.memberType())); } else { throw new TypeMismatchException(context, "Trying to access named field " + fieldName + " on non-struct expression of type " + type.toString()); } Type fieldType = structType.getFieldTypeByName(fieldName); if (fieldType == null) { throw new TypeMismatchException(context, "Field named " + fieldName + " does not exist in structure type " + structType.typeName()); } return fieldType; } /** * Same as findExprType, but check that we don't have a multiple * value type * @param context * @param tree * @return * @throws UserException */ public static Type findSingleExprType(Context context, SwiftAST tree) throws UserException { ExprType typeL = findExprType(context, tree); if (typeL.elems() != 1) { throw new TypeMismatchException(context, "Expected expression to have " + "a single value, instead had " + typeL.elems() + " values"); } return typeL.get(0); } private static String extractOpName(SwiftAST opTree) { int tok = opTree.child(0).getType(); try { return ExMParser.tokenNames[tok].toLowerCase(); } catch (IndexOutOfBoundsException ex) { throw new STCRuntimeError("Out of range token number: " + tok); } } private static ExprType findOperatorResultType(Context context, SwiftAST tree) throws TypeMismatchException, UserException { ArrayList<Type> argTypes = new ArrayList<Type>(); List<Op> ops = getOpsFromTree(context, tree, argTypes); assert(ops != null); assert(ops.size() > 0); // Handle possibility of multiple return types List<Type> alternatives = new ArrayList<Type>(ops.size()); for (Op op: ops) { alternatives.add(new ScalarFutureType(op.type.out)); } return new ExprType(UnionType.makeUnion(alternatives)); } /** * Get a list of possible matches * @param context * @param tree * @param argTypes * @return * @throws UserException */ public static List<Op> getOpsFromTree(Context context, SwiftAST tree, List<Type> argTypes) throws UserException { return getOpsFromTree(context, tree, null, argTypes, false); } /** * Get the final operator match using output argument info * @param context * @param tree * @param outType * @return * @throws UserException */ public static Op getOpFromTree(Context context, SwiftAST tree, Type outType) throws UserException { List<Op> matches = getOpsFromTree(context, tree, outType, null, true); assert(matches.size() > 0); return matches.get(0); } /** * * @param context * @param tree * @param expectedResult * @param outType if not null, only return operators with this output type * @param outArgTypes Put the argument types of the operator in this list if not null * @param expectUnambig at this stage, expect operator not to be ambiguous - log * debug message if it is * @return at least one builtin operator * @throws TypeMismatchException if no matches possible */ private static List<Op> getOpsFromTree(Context context, SwiftAST tree, Type outType, List<Type> outArgTypes, boolean expectUnambig) throws UserException { assert(tree.getType() == ExMParser.OPERATOR); assert(tree.getChildCount() >= 1); int opTok = tree.child(0).getType(); String opName = extractOpName(tree); List<Type> argTypes = findOperatorArgTypes(context, tree, opName); if (outArgTypes != null) { // Store for caller outArgTypes.clear(); outArgTypes.addAll(argTypes); } // Track operators that matched List<Op> matched = new ArrayList<Op>(); for (Op candidate: Operators.getOps(opTok)) { // TODO: check input types OpType opType = candidate.type; if (opOutputMatches(outType, opType) && opInputsMatch(argTypes, opType)) { matched.add(candidate); } } if (matched.size() > 1) { // Hope to match exactly one operator List<String> typeNames = new ArrayList<String>(); for (Type argType: argTypes) { typeNames.add(argType.typeName()); } if (matched.size() == 0) { // Error - no matches String msg = "Operator " + opName + " not supported for these input " + "types : " + typeNames.toString(); if (outType != null) { msg += " and output type " + outType; } throw new UndefinedOperatorException(context, msg); } else if (expectUnambig) { // Ambiguous operator - might be of interest assert(matched.size() > 1); Logging.getSTCLogger().debug("Ambiguous operator " + opName + " for arg types " + typeNames + ". Matched: " + matched.toString()); } } return matched; } private static boolean opInputsMatch(List<Type> argTypes, OpType opType) { if (argTypes.size() != opType.in.size()) { return false; } for (int i = 0; i < argTypes.size(); i++) { ScalarFutureType inFT = new ScalarFutureType(opType.in.get(i)); if (!argTypes.get(i).assignableTo(inFT)) { return false; } } return true; } private static boolean opOutputMatches(Type outType, OpType opType) { return outType == null || (opType.out != null && new ScalarFutureType(opType.out).assignableTo(outType)); } /** * Find the argument type of the operators to a function * assuming all operators take all the same argument types. * Preference order of types determined by first expression's * union type order * @param context * @param tree * @param opName * @param argTypes used to return arg types of function, null for no return * @return * @throws TypeMismatchException * @throws UserException */ private static List<Type> findOperatorArgTypes(Context context, SwiftAST tree, String opName) throws TypeMismatchException, UserException { int argcount = tree.getChildCount() - 1; if (argcount == 0) { throw new TypeMismatchException(context, "provided no arguments to operator " + opName); } List<Type> argTypes = new ArrayList<Type>(argcount); for (SwiftAST argTree: tree.children(1)) { argTypes.add(findSingleExprType(context, argTree)); } return argTypes; } /** * The type of the internal variable that will be created from an array * dereference * * @param memberType * the type of array memebrs for the array being dereferenced * @return */ public static Type dereferenceResultType(Type memberType) { Type resultType; if (Types.isPrimFuture(memberType)) { resultType = memberType; } else if (Types.isContainer(memberType) || Types.isStruct(memberType)) { resultType = new RefType(memberType); } else { throw new STCRuntimeError("Unexpected array member type" + memberType.toString()); } return resultType; } private static TypeMismatchException argumentTypeException(Context context, int argPos, Type expType, Type actType, String errContext) { return new TypeMismatchException(context, "Expected argument " + (argPos + 1) + " to have one of the following types: " + expType.typeName() + ", but had type: " + actType.typeName() + errContext); } /** * * @param formalArgT * @param argExprT * @return (selected type of argument, selected type of variable) */ public static Pair<Type, Type> whichAlternativeType(Type formalArgT, Type argExprT) { /* * Handles cases where both function formal argument type and expression type * are union types. In case of multiple possibilities prefers picking first * alternative in expression type, followed by first formal argument alternative */ for (Type argExprAlt: UnionType.getAlternatives(argExprT)) { // Handle if argument type is union. for (Type formalArgAlt: UnionType.getAlternatives(formalArgT)) { Type concreteArgType = compatibleArgTypes(formalArgAlt, argExprAlt); if (concreteArgType != null) { return Pair.create(formalArgAlt, concreteArgType); } } } return null; // if no alternatives } /** * Check if an expression type can be used for function argument * @param argType non-polymorphic function argument type * @param exprType type of argument expression * @return concretized argType if compatible, null if incompatible */ public static Type compatibleArgTypes(Type argType, Type exprType) { if (exprType.assignableTo(argType)) { // Obviously ok if types are exactly the same return exprType.concretize(argType); } else if (Types.isAssignableRefTo(exprType, argType)) { // We can block on reference, so we can transform type here return exprType.concretize(new RefType(argType)); } else { return null; } } private static ExprType callFunction(Context context, SwiftAST tree, boolean noWarn) throws UndefinedFunctionException, UserException { FunctionCall f = FunctionCall.fromAST(context, tree, false); List<FunctionType> alts = concretiseFunctionCall(context, f.function(), f.type(), f.args(), noWarn); if (alts.size() == 1) { // Function type determined entirely by input type return new ExprType(alts.get(0).getOutputs()); } else { // Ambiguous type variable binding (based on inputs) assert(alts.size() >= 2); int numOutputs = f.type().getOutputs().size(); if (numOutputs == 0) { return new ExprType(Collections.<Type>emptyList()); } else { // Turn into a list of UnionTypes List<Type> altOutputs = new ArrayList<Type>(); for (int out = 0; out < numOutputs; out++) { List<Type> altOutput = new ArrayList<Type>(); for (FunctionType ft: alts) { altOutput.add(ft.getOutputs().get(out)); } altOutputs.add(UnionType.makeUnion(altOutput)); } return new ExprType(altOutputs); } } } public static FunctionType concretiseFunctionCall(Context context, String function, FunctionType abstractType, List<SwiftAST> args, List<Var> outputs, boolean firstCall) throws UserException { List<Type> outTs = new ArrayList<Type>(outputs.size()); for (Var output: outputs) { checkFunctionOutputValid(context, function, output); outTs.add(output.type()); } List<FunctionType> alts = concretiseFunctionCall(context, function, abstractType, args, firstCall); assert(alts.size() > 0); for (FunctionType alt: alts) { assert(alt.getOutputs().size() == outputs.size()); boolean match = true; for (int i = 0; i < outTs.size(); i++) { if (!alt.getOutputs().get(i).assignableTo(outTs.get(i))) { match = false; break; } } LogHelper.trace(context, "Call " + function + " alternative " + "function type " + alt + " match: " + match); // Choose first viable alternative if (match) { return alt; } } throw new TypeMismatchException(context, "Could not find consistent " + "binding for type variables. Viable function signatures based on " + "input arguments were: " + alts + " but output types were " + outTs); } /** * Check that function output var is valid * @param output * @throws TypeMismatchException */ private static void checkFunctionOutputValid(Context context, String function, Var output) throws TypeMismatchException { if (Types.isFile(output) && output.isMapped() == Ternary.FALSE && !output.type().fileKind().supportsTmpImmediate() && !ForeignFunctions.initsOutputMapping(function)) { /* * We can't create temporary files for this type. If we detect any * where a definitely unmapped var is an output to a function, then * we can avoid generating code where this happens. Why? * Suppose that write a program where a leaf function is called with * an unmapped output file. There are two cases: * 1. The unmapped input file is declared in the same scope as * the leaf function => isMapped() == false and we're done. * 2. The unmapped input file is a function output argument => * backtrack through the caller hierarchy until we reach the * function where the unmapped variable was declared. In that * function we called a composite function with the (definitely) * unmapped variable for which isMapped() == false. * So by this simple check we can prevent leaf functions being called * with unmapped output files. * The exception to this is a special function that will initialize an * unmapped variable on its own */ throw new TypeMismatchException(context, "Type " + output.type().typeName() + " does not support creating temporary files. Unmapped var " + output.name() + " cannot be used as function output variable."); } } /** * @param context * @param abstractType function type with varargs, typevars, union types * @param args input argument expressions * @param noWarn don't issue warnings * @return list of possible concrete function types with varargs, typevars * and union type args removed * @throws UserException */ public static List<FunctionType> concretiseFunctionCall(Context context, String func, FunctionType abstractType, List<SwiftAST> args, boolean noWarn) throws UserException { List<Type> argTypes = new ArrayList<Type>(args.size()); for (SwiftAST arg: args) { argTypes.add(findSingleExprType(context, arg)); } // Expand varargs List<Type> expandedInputs = expandVarargs(context, abstractType, func, args.size()); // Narrow down possible bindings - choose union types // find possible typevar bindings List<Type> specificInputs = new ArrayList<Type>(args.size()); MultiMap<String, Type> tvConstraints = new MultiMap<String, Type>(); for (int i = 0; i < args.size(); i++) { Type exp = expandedInputs.get(i); Type act = argTypes.get(i); // a more specific type than expected Type exp2; exp2 = narrowArgType(context, func, i, exp, act, tvConstraints); specificInputs.add(exp2); } LogHelper.trace(context, "Call " + func + " specificInputs: " + specificInputs + " possible bindings: " + tvConstraints); // Narrow down type variable bindings depending on constraints Map<String, List<Type>> bindings = unifyTypeVarConstraints(context, func, abstractType.getTypeVars(), tvConstraints, noWarn); LogHelper.trace(context, "Call " + func + " unified bindings: " + tvConstraints); List<FunctionType> possibilities = findPossibleFunctionTypes(context, func, abstractType, specificInputs, bindings); LogHelper.trace(context, "Call " + func + " possible concrete types: " + possibilities); if (possibilities.size() == 0) { throw new TypeMismatchException(context, "Arguments for call to " + "function " + func + " were incompatible with function " + "type. Function input types were: " + abstractType.getInputs() + ", argument types were " + argTypes); } return possibilities; } /** * Narrow down the possible argument types for a function call * @param context * @param func * @param arg number of argument * @param formalArgT Formal argument type from abstract function type * @param argExprT Type of argument expression for function * @param tvConstrains Filled in with constraints for each type variable * @return * @throws TypeMismatchException */ private static Type narrowArgType(Context context, String func, int arg, Type formalArgT, Type argExprT, MultiMap<String, Type> tvConstrains) throws TypeMismatchException { if (formalArgT.hasTypeVar()) { return checkFunArgTV(context, func, arg, formalArgT, argExprT, tvConstrains); } else { return checkFunArg(context, func, arg, formalArgT, argExprT).val1; } } /** * Check function argument type * Returns a tuple indicating which formal argument type is selected and * what type the input argument expression should be interpreted as having. * Does not handle type variables * @param context * @param function * @param argNum * @param formalArgT * @param argExprT * @return (selected formal argument type, selected argument expression type) * @throws TypeMismatchException */ public static Pair<Type, Type> checkFunArg(Context context, String function, int argNum, Type formalArgT, Type argExprT) throws TypeMismatchException { assert(!formalArgT.hasTypeVar()); Pair<Type, Type> res = whichAlternativeType(formalArgT, argExprT); if (res == null) { throw argumentTypeException(context, argNum, formalArgT, argExprT, " in call to function " + function); } assert(res.val1.isConcrete()) : "Non-concrete arg type: " + res.val1; assert(res.val2.isConcrete()) : "Non-concrete arg type: " + res.val2; return res; } /** * Check function argument type * Returns which formal argument type is selected. * Only handles case where formalArgT has a type variable * @param context * @param func * @param arg * @param formalArgT * @param argExprT * @param tvConstraints fill in constraints for type variables * @return * @throws TypeMismatchException */ private static Type checkFunArgTV(Context context, String func, int arg, Type formalArgT, Type argExprT, MultiMap<String, Type> tvConstraints) throws TypeMismatchException { if (Types.isUnion(formalArgT)) { throw new TypeMismatchException(context, "Union type " + formalArgT + " with type variable is not supported"); } if (Types.isRef(argExprT)) { // Will be dereferenced argExprT = argExprT.memberType(); } if (Types.isUnion(argExprT)) { List<Map<String, Type>> possible = new ArrayList<Map<String,Type>>(); for (Type alt: UnionType.getAlternatives(argExprT)) { possible.add(formalArgT.matchTypeVars(alt)); } // Sanity check: ensure that all bind the same type variables for (Map<String, Type> m: possible) { assert(m.keySet().equals(possible.get(0).keySet())); } for (String boundVar: possible.get(0).keySet()) { List<Type> choices = new ArrayList<Type>(); for (Map<String, Type> m: possible) { Type t = m.get(boundVar); assert(!Types.isUnion(t)); // Shouldn't be union inside union choices.add(t); } tvConstraints.put(boundVar, UnionType.makeUnion(choices)); } } else { Map<String, Type> matchedTypeVars = formalArgT.matchTypeVars(argExprT); if (matchedTypeVars == null) { throw new TypeMismatchException(context, "Could not match type " + "variables for formal arg type " + formalArgT + " and argument " + " expression type: " + argExprT); } tvConstraints.putAll(matchedTypeVars); } // Leave type var return formalArgT; } private static List<FunctionType> findPossibleFunctionTypes(Context context, String function, FunctionType abstractType, List<Type> specificInputs, Map<String, List<Type>> bindings) throws TypeMismatchException { List<String> typeVars = new ArrayList<String>(abstractType.getTypeVars()); // Handle case where type variables are unbound for (ListIterator<String> it = typeVars.listIterator(); it.hasNext(); ) { if (!bindings.containsKey(it.next())) { it.remove(); } } int currChoices[] = new int[typeVars.size()]; // initialized to zero List<FunctionType> possibilities = new ArrayList<FunctionType>(); while (true) { Map<String, Type> currBinding = new HashMap<String, Type>(); for (int i = 0; i < currChoices.length; i++) { String tv = typeVars.get(i); currBinding.put(tv, bindings.get(tv).get(currChoices[i])); } possibilities.add(constructFunctionType(abstractType, specificInputs, currBinding)); int pos = currChoices.length - 1; while (pos >= 0 && currChoices[pos] >= bindings.get(typeVars.get(pos)).size() - 1) { pos--; } if (pos < 0) { break; } else { currChoices[pos]++; for (int i = pos + 1; i < currChoices.length; i++) { currChoices[i] = 0; } } } return possibilities; } private static FunctionType constructFunctionType(FunctionType abstractType, List<Type> inputs, Map<String, Type> binding) { List<Type> concreteInputs = bindTypeVariables(inputs, binding); List<Type> concreteOutputs = bindTypeVariables( abstractType.getOutputs(), binding); return new FunctionType(concreteInputs, concreteOutputs, false); } private static List<Type> expandVarargs(Context context, FunctionType abstractType, String function, int numArgs) throws TypeMismatchException { List<Type> abstractInputs = abstractType.getInputs(); if (abstractType.hasVarargs()) { if (numArgs < abstractInputs.size() - 1) { throw new TypeMismatchException(context, "Too few arguments in " + "call to function " + function + ": expected >= " + (abstractInputs.size() - 1) + " but got " + numArgs); } } else if (abstractInputs.size() != numArgs) { throw new TypeMismatchException(context, "Wrong number of arguments in " + "call to function " + function + ": expected " + abstractInputs.size() + " but got " + numArgs); } if (abstractType.hasVarargs()) { List<Type> expandedInputs; expandedInputs = new ArrayList<Type>(); expandedInputs.addAll(abstractInputs.subList(0, abstractInputs.size() - 1)); Type varArgType = abstractInputs.get(abstractInputs.size() - 1); for (int i = abstractInputs.size() - 1; i < numArgs; i++) { expandedInputs.add(varArgType); } return expandedInputs; } else { return abstractInputs; } } private static List<Type> bindTypeVariables(List<Type> types, Map<String, Type> binding) { List<Type> res = new ArrayList<Type>(types.size()); for (Type type: types) { res.add(type.bindTypeVars(binding)); } return res; } public static void checkCopy(Context context, Type srctype, Type dsttype) throws TypeMismatchException { if (!(srctype.assignableTo(dsttype) && srctype.getImplType().equals(dsttype.getImplType()))) { new Exception().printStackTrace(); throw new TypeMismatchException(context, "Type mismatch: copying from " + srctype.toString() + " to " + dsttype.toString()); } } public static Type checkAssignment(Context context, Type rValType, Type lValType, String lValName) throws TypeMismatchException { return checkAssignment(context, AssignOp.ASSIGN, rValType, lValType, lValName); } /** * Checks whether rValType can be assigned to lValType * @param context * @param op * @param rValType * @param lValType * @param lValName * @return returns rValType, or if rValType is a union, return chosen * member of union * @throws TypeMismatchException */ public static Type checkAssignment(Context context, AssignOp op, Type rValType, Type lValType, String lValName) throws TypeMismatchException { Type targetLValType; if (op == AssignOp.ASSIGN) { targetLValType = lValType; } else { assert(op == AssignOp.APPEND); targetLValType = Types.containerElemType(lValType); } for (Type altRValType: UnionType.getAlternatives(rValType)) { if (altRValType.assignableTo(targetLValType) || (Types.isRef(targetLValType) && altRValType.assignableTo(targetLValType.memberType())) || (Types.isRef(altRValType) && altRValType.memberType().assignableTo(targetLValType))) { return altRValType; } } throw new TypeMismatchException(context, "Cannot " + op.toString().toLowerCase() + " to " + lValName + ": LVal has type " + lValType.toString() + " but RVal has type " + rValType.toString()); } /** * Create dictionary with null type var bindings * @param ftype * @return */ public static MultiMap<String, Type> typeVarBindings(FunctionType ftype) { return new MultiMap<String, Type>(); } /** * @param candidates MultiMap, with possible bindings for each type variable * @return map of type variable name to possible types. If list is null, * this means no constraint on type variable * @throws TypeMismatchException if no viable binding */ public static Map<String, List<Type>> unifyTypeVarConstraints( Context context, String function, List<String> typeVars, MultiMap<String, Type> candidates, boolean noWarn) throws TypeMismatchException { Map<String, List<Type>> possible = new HashMap<String, List<Type>>(); /* Check whether type variables were left unbound */ for (String typeVar: typeVars) { List<Type> cands = candidates.get(typeVar); if (cands == null || cands.size() == 0) { if (!noWarn) { LogHelper.warn(context, "Type variable " + typeVar + " for call to " + "function " + function + " was unbound"); } } else { List<Type> intersection = Types.typeIntersection(cands); if (intersection.size() == 0) { throw new TypeMismatchException(context, "Type variable " + typeVar + " for call to function " + function + " could not be bound to concrete type: no " + "intersection between types: " + cands); } possible.put(typeVar, intersection); } } return possible; } }
Fix internal error on 822 typechecking failure - now throw correct user-facing error git-svn-id: 47705994653588c662f4ea400dfe88107361c0e2@10184 dc4e9af1-7f46-4ead-bba6-71afc04862de
code/src/exm/stc/frontend/TypeChecker.java
Fix internal error on 822 typechecking failure - now throw correct user-facing error
Java
apache-2.0
cd73b39ad7f712f442e9735e6fd9d1d8604895b3
0
nidi3/android-goodies
package guru.nidi.android.support; import android.net.http.AndroidHttpClient; import android.os.Build; import guru.nidi.android.ApplicationContextHolder; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.params.HttpConnectionParams; import org.apache.http.util.EntityUtils; import java.io.IOException; /** * */ public class HttpConnector { private static HttpConnector defaultConnector; private final AndroidHttpClient client; public HttpConnector(int soTimeout, int connectionTimeout) { client = AndroidHttpClient.newInstance(userAgent()); HttpConnectionParams.setSoTimeout(client.getParams(), soTimeout); HttpConnectionParams.setConnectionTimeout(client.getParams(), connectionTimeout); } public static HttpConnector setDefault(int soTimeout, int connectionTimeout) { return defaultConnector = new HttpConnector(soTimeout, connectionTimeout); } public static HttpConnector getDefault() { return defaultConnector; } public static void close(HttpResponse response) { if (response != null && response.getEntity() != null) { try { response.getEntity().consumeContent(); } catch (IOException e) { //give up } } } public static String toString(HttpResponse response) throws IOException { try { return EntityUtils.toString(response.getEntity()); } finally { close(response); } } public static byte[] toByteArray(HttpResponse response) throws IOException { try { return EntityUtils.toByteArray(response.getEntity()); } finally { close(response); } } public HttpResponse send(HttpRequestBase request) throws IOException { return client.execute(request); } public HttpResponse sendAndClose(HttpRequestBase request) throws IOException { HttpResponse response = null; try { response = send(request); return response; } finally { close(response); } } private String userAgent() { StringBuilder result = new StringBuilder(64) .append("Dalvik/") .append(System.getProperty("java.vm.version")) .append(" (Linux; U; Android "); String version = Build.VERSION.RELEASE; result.append(version.length() > 0 ? version : "1.0"); if ("REL".equals(Build.VERSION.CODENAME)) { String model = Build.MODEL; if (model.length() > 0) { result.append("; ").append(model); } } String id = Build.ID; if (id.length() > 0) { result.append(" Build/").append(id); } result.append(") ") .append(ApplicationContextHolder.basePackage()) .append('/') .append(ApplicationContextHolder.appVersion()); return result.toString(); } public void close() { client.close(); } }
src/main/java/guru/nidi/android/support/HttpConnector.java
package guru.nidi.android.support; import android.net.http.AndroidHttpClient; import android.os.Build; import guru.nidi.android.ApplicationContextHolder; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.params.HttpConnectionParams; import java.io.IOException; /** * */ public class HttpConnector { private static HttpConnector defaultConnector; private final AndroidHttpClient client; public HttpConnector(int soTimeout, int connectionTimeout) { client = AndroidHttpClient.newInstance(userAgent()); HttpConnectionParams.setSoTimeout(client.getParams(), soTimeout); HttpConnectionParams.setConnectionTimeout(client.getParams(), connectionTimeout); } public static HttpConnector setDefault(int soTimeout, int connectionTimeout) { return defaultConnector = new HttpConnector(soTimeout, connectionTimeout); } public static HttpConnector getDefault() { return defaultConnector; } public static void close(HttpResponse response) { if (response != null && response.getEntity() != null) { try { response.getEntity().consumeContent(); } catch (IOException e) { //give up } } } public HttpResponse send(HttpRequestBase request) throws IOException { return client.execute(request); } public HttpResponse sendAndClose(HttpRequestBase request) throws IOException { HttpResponse response = null; try { return send(request); } finally { close(response); } } private String userAgent() { StringBuilder result = new StringBuilder(64) .append("Dalvik/") .append(System.getProperty("java.vm.version")) .append(" (Linux; U; Android "); String version = Build.VERSION.RELEASE; result.append(version.length() > 0 ? version : "1.0"); if ("REL".equals(Build.VERSION.CODENAME)) { String model = Build.MODEL; if (model.length() > 0) { result.append("; ").append(model); } } String id = Build.ID; if (id.length() > 0) { result.append(" Build/").append(id); } result.append(") ") .append(ApplicationContextHolder.basePackage()) .append('/') .append(ApplicationContextHolder.appVersion()); return result.toString(); } public void close() { client.close(); } }
close http responses
src/main/java/guru/nidi/android/support/HttpConnector.java
close http responses
Java
apache-2.0
be4f655c832098ba1a36a965925c4dd0e4125bdd
0
mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp,mohanaraosv/commons-dbcp
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.dbcp2.cpdsadapter; import java.util.Arrays; import org.apache.commons.dbcp2.PStmtKey; /** * A key uniquely identifying a {@link java.sql.PreparedStatement PreparedStatement}. */ public class PStmtKeyCPDS extends PStmtKey { private final Integer _autoGeneratedKeys; private final Integer _resultSetHoldability; private final int _columnIndexes[]; private final String _columnNames[]; public PStmtKeyCPDS(String sql) { super(sql); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int autoGeneratedKeys) { super(sql); _autoGeneratedKeys = Integer.valueOf(autoGeneratedKeys); _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int resultSetType, int resultSetConcurrency) { super(sql, resultSetType, resultSetConcurrency); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { super(sql, resultSetType, resultSetConcurrency); _resultSetHoldability = Integer.valueOf(resultSetHoldability); _autoGeneratedKeys = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int columnIndexes[]) { super(sql); _columnIndexes = Arrays.copyOf(columnIndexes, columnIndexes.length); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnNames = null; } public PStmtKeyCPDS(String sql, String columnNames[]) { super(sql); _columnNames = Arrays.copyOf(columnNames, columnNames.length); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; } public Integer getAutoGeneratedKeys() { return _autoGeneratedKeys; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } PStmtKeyCPDS other = (PStmtKeyCPDS) obj; if (_autoGeneratedKeys == null) { if (other._autoGeneratedKeys != null) { return false; } } else if (!_autoGeneratedKeys.equals(other._autoGeneratedKeys)) { return false; } if (!Arrays.equals(_columnIndexes, other._columnIndexes)) { return false; } if (!Arrays.equals(_columnNames, other._columnNames)) { return false; } if (_resultSetHoldability == null) { if (other._resultSetHoldability != null) { return false; } } else if (!_resultSetHoldability.equals(other._resultSetHoldability)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((_autoGeneratedKeys == null) ? 0 : _autoGeneratedKeys.hashCode()); result = prime * result + Arrays.hashCode(_columnIndexes); result = prime * result + Arrays.hashCode(_columnNames); result = prime * result + ((_resultSetHoldability == null) ? 0 : _resultSetHoldability.hashCode()); return result; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("PStmtKey: sql="); buf.append(getSql()); buf.append(", catalog="); buf.append(getCatalog()); buf.append(", resultSetType="); buf.append(getResultSetType()); buf.append(", resultSetConcurrency="); buf.append(getResultSetConcurrency()); buf.append(", statmentType="); buf.append(getStmtType()); buf.append(", autoGeneratedKeys="); buf.append(_autoGeneratedKeys); buf.append(", resultSetHoldability="); buf.append(_resultSetHoldability); buf.append(", columnIndexes="); buf.append(Arrays.toString(_columnIndexes)); buf.append(", columnNames="); buf.append(Arrays.toString(_columnNames)); return buf.toString(); } }
src/java/org/apache/commons/dbcp2/cpdsadapter/PStmtKeyCPDS.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.dbcp2.cpdsadapter; import java.util.Arrays; import org.apache.commons.dbcp2.PStmtKey; /** * A key uniquely identifying a {@link java.sql.PreparedStatement PreparedStatement}. */ public class PStmtKeyCPDS extends PStmtKey { private final Integer _autoGeneratedKeys; private final Integer _resultSetHoldability; private final int _columnIndexes[]; private final String _columnNames[]; public PStmtKeyCPDS(String sql) { super(sql); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int autoGeneratedKeys) { super(sql); _autoGeneratedKeys = Integer.valueOf(autoGeneratedKeys); _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int resultSetType, int resultSetConcurrency) { super(sql, resultSetType, resultSetConcurrency); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) { super(sql, resultSetType, resultSetConcurrency); _resultSetHoldability = Integer.valueOf(resultSetHoldability); _autoGeneratedKeys = null; _columnIndexes = null; _columnNames = null; } public PStmtKeyCPDS(String sql, int columnIndexes[]) { super(sql); _columnIndexes = Arrays.copyOf(columnIndexes, columnIndexes.length); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnNames = null; } public PStmtKeyCPDS(String sql, String columnNames[]) { super(sql); _columnNames = Arrays.copyOf(columnNames, columnNames.length); _autoGeneratedKeys = null; _resultSetHoldability = null; _columnIndexes = null; } public Integer getAutoGeneratedKeys() { return _autoGeneratedKeys; } @Override public boolean equals(Object that) { try { PStmtKeyCPDS key = (PStmtKeyCPDS) that; return(((null == getSql() && null == key.getSql()) || getSql().equals(key.getSql())) && ((null == getCatalog() && null == key.getCatalog()) || getCatalog().equals(key.getCatalog())) && ((null == getResultSetType() && null == key.getResultSetType()) || getResultSetType().equals(key.getResultSetType())) && ((null == getResultSetConcurrency() && null == key.getResultSetConcurrency()) || getResultSetConcurrency().equals(key.getResultSetConcurrency())) && (getStmtType() == key.getStmtType()) && ((null == _autoGeneratedKeys && null == key._autoGeneratedKeys) || _autoGeneratedKeys.equals(key._autoGeneratedKeys)) && ((null == _resultSetHoldability && null == key._resultSetHoldability) || _resultSetHoldability.equals(key._resultSetHoldability)) && ((null == _columnIndexes && null == key._columnIndexes) || Arrays.equals(_columnIndexes, key._columnIndexes)) && ((null == _columnNames && null == key._columnNames) || Arrays.equals(_columnNames, key._columnNames)) ); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("PStmtKey: sql="); buf.append(getSql()); buf.append(", catalog="); buf.append(getCatalog()); buf.append(", resultSetType="); buf.append(getResultSetType()); buf.append(", resultSetConcurrency="); buf.append(getResultSetConcurrency()); buf.append(", statmentType="); buf.append(getStmtType()); buf.append(", autoGeneratedKeys="); buf.append(_autoGeneratedKeys); buf.append(", resultSetHoldability="); buf.append(_resultSetHoldability); buf.append(", columnIndexes="); buf.append(Arrays.toString(_columnIndexes)); buf.append(", columnNames="); buf.append(Arrays.toString(_columnNames)); return buf.toString(); } }
Reduce FindBugs warnings (equals() but no hashCode()) (using Eclipse's generated code for equals() and hashCode() with just formatting changes) git-svn-id: ad951d5a084f562764370c7a59da74380db26404@1557684 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/commons/dbcp2/cpdsadapter/PStmtKeyCPDS.java
Reduce FindBugs warnings (equals() but no hashCode()) (using Eclipse's generated code for equals() and hashCode() with just formatting changes)
Java
apache-2.0
760d7a6724b7ba8adf44c4b721b1a71f94ce3af2
0
hubme/WorkHelperApp,hubme/WorkHelperApp,hubme/WorkHelperApp,hubme/WorkHelperApp
package com.king.app.workhelper; import android.content.Context; import androidx.annotation.NonNull; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.Registry; import com.bumptech.glide.annotation.GlideModule; import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader; import com.bumptech.glide.load.DecodeFormat; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.module.AppGlideModule; import com.bumptech.glide.request.RequestOptions; import java.io.InputStream; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.OkHttpClient; /** * @author VanceKing * @since 19-8-27. */ @GlideModule public class CustomGlideModule extends AppGlideModule { @Override public void registerComponents(@NonNull Context context, Glide glide, @NonNull Registry registry) { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build(); OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory((Call.Factory) client); glide.getRegistry().replace(GlideUrl.class, InputStream.class, factory); } @Override public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) { super.applyOptions(context, builder); //在Glide内部,会读取原始图片的EXIF头信息,获取当前图片的格式。若当前格式的图片支持alpha通道,则还是会设置为ARGB_8888的格式。 builder.setDefaultRequestOptions(new RequestOptions().format(DecodeFormat.PREFER_RGB_565)); } @Override public boolean isManifestParsingEnabled() { return false; } }
app/src/main/java/com/king/app/workhelper/CustomGlideModule.java
package com.king.app.workhelper; import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.Registry; import com.bumptech.glide.annotation.GlideModule; import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader; import com.bumptech.glide.load.model.GlideUrl; import com.bumptech.glide.module.AppGlideModule; import org.jetbrains.annotations.NotNull; import java.io.InputStream; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.OkHttpClient; /** * @author VanceKing * @since 19-8-27. */ @GlideModule public class CustomGlideModule extends AppGlideModule { @Override public void registerComponents(@NotNull Context context, Glide glide, @NotNull Registry registry) { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(15, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build(); OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory((Call.Factory) client); glide.getRegistry().replace(GlideUrl.class, InputStream.class, factory); } @Override public boolean isManifestParsingEnabled() { return false; } }
设置 Glide 使用 RGB_565 模式加载图片
app/src/main/java/com/king/app/workhelper/CustomGlideModule.java
设置 Glide 使用 RGB_565 模式加载图片
Java
apache-2.0
ee043266cc91a2c3819c76226f1d2f7d0d03417d
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.engine.resource; import android.content.Context; import android.os.Handler; import android.util.Log; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.logging.analytics.UpdateStats; import org.commcare.preferences.HiddenPreferences; import org.commcare.resources.ResourceManager; import org.commcare.resources.model.InstallCancelled; import org.commcare.resources.model.InstallCancelledException; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.TableStateListener; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.tasks.UpdateTask; import org.commcare.util.CommCarePlatform; import org.commcare.util.LogTypes; import org.commcare.utils.AndroidCommCarePlatform; import org.commcare.utils.AndroidResourceInstallerFactory; import org.commcare.utils.SessionUnavailableException; import org.javarosa.core.reference.ReleasedOnTimeSupportedReference; import org.javarosa.core.reference.Reference; import org.javarosa.core.services.Logger; import org.javarosa.xml.util.UnfullfilledRequirementsException; import java.text.ParseException; import java.util.Date; /** * Manages app installations and updates. Extends the ResourceManager with the * ability to stage but not apply updates. * * @author Phillip Mates ([email protected]) */ public class AndroidResourceManager extends ResourceManager { private final static String TAG = AndroidResourceManager.class.getSimpleName(); public final static String TEMP_UPGRADE_TABLE_KEY = "TEMP_UPGRADE_RESOURCE_TABLE"; // 60 minutes private final static long MAX_UPDATE_RETRY_DELAY_IN_MS = 1000 * 60 * 60; private final CommCareApp app; private final UpdateStats updateStats; private final ResourceTable tempUpgradeTable; private String profileRef; public AndroidResourceManager(AndroidCommCarePlatform platform) { super(platform, platform.getGlobalResourceTable(), platform.getUpgradeResourceTable(), platform.getRecoveryTable()); app = CommCareApplication.instance().getCurrentApp(); tempUpgradeTable = new AndroidResourceTable(app.getStorage(TEMP_UPGRADE_TABLE_KEY, Resource.class), new AndroidResourceInstallerFactory()); updateStats = UpdateStats.loadUpdateStats(app); upgradeTable.setInstallStatsLogger(updateStats); tempUpgradeTable.setInstallStatsLogger(updateStats); } /** * Download the latest profile; if it is new, download and stage the entire * update. * * @param profileRef Reference that resolves to the profile file used to * seed the update * @param profileAuthority The authority from which the app resources for the update are * coming (local vs. remote) * @return UpdateStaged upon update download, UpToDate if no new update, * otherwise an error status. */ public AppInstallStatus checkAndPrepareUpgradeResources(String profileRef, int profileAuthority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { synchronized (platform) { this.profileRef = profileRef; instantiateLatestUpgradeProfile(profileAuthority); if (isUpgradeTableStaged()) { return AppInstallStatus.UpdateStaged; } if (updateNotNewer(getMasterProfile())) { Logger.log(LogTypes.TYPE_RESOURCES, "App Resources up to Date"); clearUpgrade(); return AppInstallStatus.UpToDate; } prepareUpgradeResources(); return AppInstallStatus.UpdateStaged; } } /** * Load the latest profile into the upgrade table. Clears the upgrade table * if it's partially populated with an out-of-date version. */ private void instantiateLatestUpgradeProfile(int authority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { ensureMasterTableValid(); if (updateStats.isUpgradeStale()) { Log.i(TAG, "Clearing upgrade table because resource downloads " + "failed too many times or started too long ago"); upgradeTable.destroy(); updateStats.resetStats(app); } Resource upgradeProfile = upgradeTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); if (upgradeProfile == null) { loadProfileIntoTable(upgradeTable, profileRef, authority); } else { loadProfileViaTemp(upgradeProfile, authority); } } /** * Download the latest profile into the temporary table and if the version * higher than the upgrade table's profile, copy it into the upgrade table. * * @param upgradeProfile the profile currently in the upgrade table. */ private void loadProfileViaTemp(Resource upgradeProfile, int profileAuthority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { tempUpgradeTable.destroy(); loadProfileIntoTable(tempUpgradeTable, profileRef, profileAuthority); Resource tempProfile = tempUpgradeTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); if (tempProfile != null && tempProfile.isNewer(upgradeProfile)) { upgradeTable.destroy(); tempUpgradeTable.copyToTable(upgradeTable); } tempUpgradeTable.destroy(); } /** * Set listeners and checkers that enable communication between low-level * resource installation and top-level app update/installation process. * * @param tableListener allows resource table to report its progress to the * launching process * @param cancelCheckker allows resource installers to check if the * launching process was cancelled */ @Override public void setUpgradeListeners(TableStateListener tableListener, InstallCancelled cancelCheckker) { super.setUpgradeListeners(tableListener, cancelCheckker); tempUpgradeTable.setStateListener(tableListener); tempUpgradeTable.setInstallCancellationChecker(cancelCheckker); } /** * Save upgrade stats if the upgrade was cancelled and wasn't complete at * that time. */ public void upgradeCancelled() { if (!isUpgradeTableStaged()) { UpdateStats.saveStatsPersistently(app, updateStats); } else { Log.i(TAG, "Upgrade cancelled, but already finished with these stats"); Log.i(TAG, updateStats.toString()); } } public void incrementUpdateAttempts() { updateStats.registerStagingAttempt(); } /** * Log update failure that occurs while trying to install the staged update table */ public void recordUpdateInstallFailure(Exception exception) { updateStats.registerUpdateException(exception); } public void recordUpdateInstallFailure(AppInstallStatus result) { updateStats.registerUpdateException(new Exception(result.toString())); } /** * Clear update table, log failure with update stats, * and, if appropriate, schedule a update retry * * @param result update attempt result * @param ctx Used for showing pinned notification of update task retry * @param isAutoUpdate When set keep retrying update with delay and max retry count */ public void processUpdateFailure(AppInstallStatus result, Context ctx, boolean isAutoUpdate) { updateStats.registerUpdateException(new Exception(result.toString())); if (!result.canReusePartialUpdateTable()) { clearUpgrade(); } retryUpdateOrGiveUp(ctx, isAutoUpdate); } private void retryUpdateOrGiveUp(Context ctx, boolean isAutoUpdate) { if (updateStats.isUpgradeStale()) { Logger.log(LogTypes.TYPE_RESOURCES, "Update was stale, stopped trying to download update. Update Stats: " + updateStats.toString()); UpdateStats.clearPersistedStats(app); if (isAutoUpdate) { ResourceInstallUtils.recordAutoUpdateCompletion(app); } clearUpgrade(); } else { Logger.log(LogTypes.TYPE_RESOURCES, "Retrying auto-update"); UpdateStats.saveStatsPersistently(app, updateStats); if (isAutoUpdate) { scheduleUpdateTaskRetry(ctx, updateStats.getRestartCount()); } } } private void scheduleUpdateTaskRetry(final Context ctx, int numberOfRestarts) { final Handler handler = new Handler(); handler.postDelayed(() -> launchRetryTask(ctx), exponentionalRetryDelay(numberOfRestarts)); } private void launchRetryTask(Context ctx) { String ref = ResourceInstallUtils.getDefaultProfileRef(); try { if (canUpdateRetryRun()) { UpdateTask updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(ctx); updateTask.setAsAutoUpdate(); updateTask.executeParallel(ref); } } catch (IllegalStateException e) { // The user may have started the update process in the meantime Log.w(TAG, "Trying trigger an auto-update retry when it is already running"); } } /** * @return Logged into an app that has begun the auto-update process */ private static boolean canUpdateRetryRun() { try { CommCareApp currentApp = CommCareApplication.instance().getCurrentApp(); // NOTE PLM: Doesn't distinguish between two apps currently in the // auto-update process. return CommCareApplication.instance().getSession().isActive() && ResourceInstallUtils.shouldAutoUpdateResume(currentApp); } catch (SessionUnavailableException e) { return false; } } /** * Retry delay that ranges between 30 seconds and 60 minutes. * At 3 retries the delay is 35 seconds, at 5 retries it is at 30 minutes. * * @param numberOfRestarts used as the exponent for the delay calculation * @return delay in MS, which grows exponentially over the number of restarts. */ private long exponentionalRetryDelay(int numberOfRestarts) { final Double base = 10 * (1.78); final long thirtySeconds = 30 * 1000; long exponentialDelay = thirtySeconds + (long)Math.pow(base, numberOfRestarts); return Math.min(exponentialDelay, MAX_UPDATE_RETRY_DELAY_IN_MS); } @Override public void clearUpgrade() { super.clearUpgrade(); HiddenPreferences.setReleasedOnTimeForOngoingAppDownload((AndroidCommCarePlatform)platform, 0); } }
app/src/org/commcare/engine/resource/AndroidResourceManager.java
package org.commcare.engine.resource; import android.content.Context; import android.os.Handler; import android.util.Log; import org.commcare.CommCareApp; import org.commcare.CommCareApplication; import org.commcare.logging.analytics.UpdateStats; import org.commcare.resources.ResourceManager; import org.commcare.resources.model.InstallCancelled; import org.commcare.resources.model.InstallCancelledException; import org.commcare.resources.model.Resource; import org.commcare.resources.model.ResourceTable; import org.commcare.resources.model.TableStateListener; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.tasks.UpdateTask; import org.commcare.util.CommCarePlatform; import org.commcare.util.LogTypes; import org.commcare.utils.AndroidCommCarePlatform; import org.commcare.utils.AndroidResourceInstallerFactory; import org.commcare.utils.SessionUnavailableException; import org.javarosa.core.services.Logger; import org.javarosa.xml.util.UnfullfilledRequirementsException; /** * Manages app installations and updates. Extends the ResourceManager with the * ability to stage but not apply updates. * * @author Phillip Mates ([email protected]) */ public class AndroidResourceManager extends ResourceManager { private final static String TAG = AndroidResourceManager.class.getSimpleName(); public final static String TEMP_UPGRADE_TABLE_KEY = "TEMP_UPGRADE_RESOURCE_TABLE"; // 60 minutes private final static long MAX_UPDATE_RETRY_DELAY_IN_MS = 1000 * 60 * 60; private final CommCareApp app; private final UpdateStats updateStats; private final ResourceTable tempUpgradeTable; private String profileRef; public AndroidResourceManager(AndroidCommCarePlatform platform) { super(platform, platform.getGlobalResourceTable(), platform.getUpgradeResourceTable(), platform.getRecoveryTable()); app = CommCareApplication.instance().getCurrentApp(); tempUpgradeTable = new AndroidResourceTable(app.getStorage(TEMP_UPGRADE_TABLE_KEY, Resource.class), new AndroidResourceInstallerFactory()); updateStats = UpdateStats.loadUpdateStats(app); upgradeTable.setInstallStatsLogger(updateStats); tempUpgradeTable.setInstallStatsLogger(updateStats); } /** * Download the latest profile; if it is new, download and stage the entire * update. * * @param profileRef Reference that resolves to the profile file used to * seed the update * @param profileAuthority The authority from which the app resources for the update are * coming (local vs. remote) * @return UpdateStaged upon update download, UpToDate if no new update, * otherwise an error status. */ public AppInstallStatus checkAndPrepareUpgradeResources(String profileRef, int profileAuthority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { synchronized (platform) { this.profileRef = profileRef; instantiateLatestUpgradeProfile(profileAuthority); if (isUpgradeTableStaged()) { return AppInstallStatus.UpdateStaged; } if (updateNotNewer(getMasterProfile())) { Logger.log(LogTypes.TYPE_RESOURCES, "App Resources up to Date"); clearUpgrade(); return AppInstallStatus.UpToDate; } prepareUpgradeResources(); return AppInstallStatus.UpdateStaged; } } /** * Load the latest profile into the upgrade table. Clears the upgrade table * if it's partially populated with an out-of-date version. */ private void instantiateLatestUpgradeProfile(int authority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { ensureMasterTableValid(); if (updateStats.isUpgradeStale()) { Log.i(TAG, "Clearing upgrade table because resource downloads " + "failed too many times or started too long ago"); upgradeTable.destroy(); updateStats.resetStats(app); } Resource upgradeProfile = upgradeTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); if (upgradeProfile == null) { loadProfileIntoTable(upgradeTable, profileRef, authority); } else { loadProfileViaTemp(upgradeProfile, authority); } } /** * Download the latest profile into the temporary table and if the version * higher than the upgrade table's profile, copy it into the upgrade table. * * @param upgradeProfile the profile currently in the upgrade table. */ private void loadProfileViaTemp(Resource upgradeProfile, int profileAuthority) throws UnfullfilledRequirementsException, UnresolvedResourceException, InstallCancelledException { tempUpgradeTable.destroy(); loadProfileIntoTable(tempUpgradeTable, profileRef, profileAuthority); Resource tempProfile = tempUpgradeTable.getResourceWithId(CommCarePlatform.APP_PROFILE_RESOURCE_ID); if (tempProfile != null && tempProfile.isNewer(upgradeProfile)) { upgradeTable.destroy(); tempUpgradeTable.copyToTable(upgradeTable); } tempUpgradeTable.destroy(); } /** * Set listeners and checkers that enable communication between low-level * resource installation and top-level app update/installation process. * * @param tableListener allows resource table to report its progress to the * launching process * @param cancelCheckker allows resource installers to check if the * launching process was cancelled */ @Override public void setUpgradeListeners(TableStateListener tableListener, InstallCancelled cancelCheckker) { super.setUpgradeListeners(tableListener, cancelCheckker); tempUpgradeTable.setStateListener(tableListener); tempUpgradeTable.setInstallCancellationChecker(cancelCheckker); } /** * Save upgrade stats if the upgrade was cancelled and wasn't complete at * that time. */ public void upgradeCancelled() { if (!isUpgradeTableStaged()) { UpdateStats.saveStatsPersistently(app, updateStats); } else { Log.i(TAG, "Upgrade cancelled, but already finished with these stats"); Log.i(TAG, updateStats.toString()); } } public void incrementUpdateAttempts() { updateStats.registerStagingAttempt(); } /** * Log update failure that occurs while trying to install the staged update table */ public void recordUpdateInstallFailure(Exception exception) { updateStats.registerUpdateException(exception); } public void recordUpdateInstallFailure(AppInstallStatus result) { updateStats.registerUpdateException(new Exception(result.toString())); } /** * Clear update table, log failure with update stats, * and, if appropriate, schedule a update retry * * @param result update attempt result * @param ctx Used for showing pinned notification of update task retry * @param isAutoUpdate When set keep retrying update with delay and max retry count */ public void processUpdateFailure(AppInstallStatus result, Context ctx, boolean isAutoUpdate) { updateStats.registerUpdateException(new Exception(result.toString())); if (!result.canReusePartialUpdateTable()) { clearUpgrade(); } retryUpdateOrGiveUp(ctx, isAutoUpdate); } private void retryUpdateOrGiveUp(Context ctx, boolean isAutoUpdate) { if (updateStats.isUpgradeStale()) { Logger.log(LogTypes.TYPE_RESOURCES, "Update was stale, stopped trying to download update. Update Stats: " + updateStats.toString()); UpdateStats.clearPersistedStats(app); if (isAutoUpdate) { ResourceInstallUtils.recordAutoUpdateCompletion(app); } clearUpgrade(); } else { Logger.log(LogTypes.TYPE_RESOURCES, "Retrying auto-update"); UpdateStats.saveStatsPersistently(app, updateStats); if (isAutoUpdate) { scheduleUpdateTaskRetry(ctx, updateStats.getRestartCount()); } } } private void scheduleUpdateTaskRetry(final Context ctx, int numberOfRestarts) { final Handler handler = new Handler(); handler.postDelayed(() -> launchRetryTask(ctx), exponentionalRetryDelay(numberOfRestarts)); } private void launchRetryTask(Context ctx) { String ref = ResourceInstallUtils.getDefaultProfileRef(); try { if (canUpdateRetryRun()) { UpdateTask updateTask = UpdateTask.getNewInstance(); updateTask.startPinnedNotification(ctx); updateTask.setAsAutoUpdate(); updateTask.executeParallel(ref); } } catch (IllegalStateException e) { // The user may have started the update process in the meantime Log.w(TAG, "Trying trigger an auto-update retry when it is already running"); } } /** * @return Logged into an app that has begun the auto-update process */ private static boolean canUpdateRetryRun() { try { CommCareApp currentApp = CommCareApplication.instance().getCurrentApp(); // NOTE PLM: Doesn't distinguish between two apps currently in the // auto-update process. return CommCareApplication.instance().getSession().isActive() && ResourceInstallUtils.shouldAutoUpdateResume(currentApp); } catch (SessionUnavailableException e) { return false; } } /** * Retry delay that ranges between 30 seconds and 60 minutes. * At 3 retries the delay is 35 seconds, at 5 retries it is at 30 minutes. * * @param numberOfRestarts used as the exponent for the delay calculation * @return delay in MS, which grows exponentially over the number of restarts. */ private long exponentionalRetryDelay(int numberOfRestarts) { final Double base = 10 * (1.78); final long thirtySeconds = 30 * 1000; long exponentialDelay = thirtySeconds + (long)Math.pow(base, numberOfRestarts); return Math.min(exponentialDelay, MAX_UPDATE_RETRY_DELAY_IN_MS); } }
Clears the released on time preference on clearing upgrade
app/src/org/commcare/engine/resource/AndroidResourceManager.java
Clears the released on time preference on clearing upgrade
Java
apache-2.0
d037227f558b4b92f6ab1e7c1bc04429a0dfe6d6
0
StevenLeRoux/warp10-platform,cityzendata/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform,StevenLeRoux/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,StevenLeRoux/warp10-platform,hbs/warp10-platform,cityzendata/warp10-platform
// // Copyright 2016 Cityzen Data // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.script; import io.warp10.continuum.Configuration; import io.warp10.continuum.sensision.SensisionConstants; import io.warp10.sensision.Sensision; import io.warp10.warp.sdk.WarpScriptJavaFunction; import io.warp10.warp.sdk.WarpScriptJavaFunctionException; import io.warp10.warp.sdk.WarpScriptRawJavaFunction; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.bouncycastle.util.encoders.Hex; import com.google.common.base.Charsets; /** * Class which manages Einstein functions stored in jar files from a directory */ public class WarpScriptJarRepository extends Thread { /** * Default refresh delay is 60 minutes */ private static final long DEFAULT_DELAY = 3600000L; private static final String JAR_EXTENSION = ".jar"; /** * Directory where the '.jar' files are */ private final String directory; /** * How often to check for changes */ private final long delay; /** * Active Class Loaders and their associated fingerprint. */ private final static Map<ClassLoader,String> classLoadersFingerprints = new LinkedHashMap<ClassLoader,String>(); private static ClassLoader classPathClassLoader = null; private final static Map<String,WarpScriptJavaFunction> cachedUDFs = new HashMap<String, WarpScriptJavaFunction>(); public WarpScriptJarRepository(String directory, long delay) { this.directory = directory; this.delay = delay; if (null != directory) { this.setName("[Warp Jar Repository (" + directory + ")"); this.setDaemon(true); this.start(); } } @Override public void run() { while(true) { String rootdir = new File(this.directory).getAbsolutePath(); // // Open directory // File[] files = new File(rootdir).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.endsWith(JAR_EXTENSION)) { return false; } else { return true; } } }); // // Loop over the files, creating the class loaders // // Map of CL to fingerprint Map<ClassLoader,String> newClassLoadersFingerprints = new LinkedHashMap<ClassLoader,String>(); byte[] buf = new byte[8192]; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); for (File file: files) { // // Compute hash of content // FileInputStream in = new FileInputStream(file); while(true) { int len = in.read(buf); if (len < 0) { break; } md.update(buf, 0, len); } in.close(); String hash = new String(Hex.encode(md.digest()), Charsets.US_ASCII); if (classLoadersFingerprints.containsValue(hash) && !newClassLoadersFingerprints.containsValue(hash)) { // Reuse existing class loader, so we keep the created objets for (Entry<ClassLoader,String> entry: classLoadersFingerprints.entrySet()) { if (entry.getValue().equals(hash)) { newClassLoadersFingerprints.put(entry.getKey(), entry.getValue()); } } } else if (!newClassLoadersFingerprints.containsKey(hash)){ // Create new classloader with filtering so caller cannot access the io.warp10 classes, except those needed ClassLoader filteringCL = this.getClass().getClassLoader(); // ClassLoader filteringCL = new ClassLoader(this.getClass().getClassLoader()) { // @Override // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // if (name.startsWith("io.warp10") && !name.startsWith("io.warp10.warp.sdk.")) { // throw new ClassNotFoundException(); // } else { // return this.getParent().loadClass(name); // } // } // }; URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); newClassLoadersFingerprints.put(new URLClassLoader(urls, filteringCL), hash); } } } catch (NoSuchAlgorithmException nsae) { } catch (IOException ioe) { } // // Replace the previous classLoaders // synchronized(classLoadersFingerprints) { classLoadersFingerprints.clear(); classLoadersFingerprints.putAll(newClassLoadersFingerprints); // Add the class path class loader too if (null != classPathClassLoader) { classLoadersFingerprints.put(classPathClassLoader, ""); } } // // Update jar count // Sensision.set(SensisionConstants.SENSISION_CLASS_EINSTEIN_REPOSITORY_JARS, Sensision.EMPTY_LABELS, classLoadersFingerprints.size()); // // Sleep a while // try { Thread.sleep(this.delay); } catch (InterruptedException ie) { } } } /** * Load an instance of a UDF, possibly checking the cache. * * @param name * @param cached * @return * @throws WarpScriptException */ public static WarpScriptJavaFunction load(String name, boolean cached) throws WarpScriptException { WarpScriptJavaFunction udf = null; if (cached) { udf = cachedUDFs.get(name); if (null != udf && validate(udf)) { return udf; } else { // Clear from cache cachedUDFs.remove(name); udf = null; } } for (Entry<ClassLoader,String> entry: classLoadersFingerprints.entrySet()) { try { ClassLoader cl = entry.getKey(); Class cls = cl.loadClass(name); Object o = cls.newInstance(); if (!(o instanceof WarpScriptJavaFunction)) { throw new WarpScriptException(name + " does not appear to be of type " + WarpScriptJavaFunction.class.getCanonicalName()); } udf = (WarpScriptJavaFunction) o; // // If the UDF was loaded from the class path class loader, wrap it so it is unprotected // if (cl.equals(classPathClassLoader)) { final WarpScriptJavaFunction innerUDF = udf; if (udf instanceof WarpScriptRawJavaFunction) { udf = new WarpScriptRawJavaFunction() { @Override public boolean isProtected() { return false; } @Override public int argDepth() { return innerUDF.argDepth(); } @Override public List<Object> apply(List<Object> args) throws WarpScriptJavaFunctionException { return innerUDF.apply(args); } }; } else { udf = new WarpScriptJavaFunction() { @Override public boolean isProtected() { return false; } @Override public int argDepth() { return innerUDF.argDepth(); } @Override public List<Object> apply(List<Object> args) throws WarpScriptJavaFunctionException { return innerUDF.apply(args); } }; } } break; } catch (Exception e) { continue; } } if (cached && null != udf) { cachedUDFs.put(name, udf); } if (null == udf) { throw new WarpScriptException("Class '" + name + "' was not found in any of the current WarpScript jars."); } return udf; } /** * Validates an instance of EinsteinJavaFunction by checking that its class loader is still active * @param func Instance to check * @return */ private static boolean validate(WarpScriptJavaFunction func) { if (null == func) { return true; } return classLoadersFingerprints.containsKey(func.getClass().getClassLoader()); } public static void init(Properties properties) { // // Extract root directory // String dir = properties.getProperty(Configuration.JARS_DIRECTORY); if (null == dir && !"true".equals(properties.getProperty(Configuration.JARS_FROMCLASSPATH))) { return; } // // Simply add a class loader to access the current classpath // if (null == dir) { classPathClassLoader = WarpScriptJarRepository.class.getClassLoader(); // classPathClassLoader = new ClassLoader(WarpScriptJarRepository.class.getClassLoader()) { // @Override // protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // if (name.startsWith("io.warp10") && !name.startsWith("io.warp10.warp.sdk.")) { // throw new ClassNotFoundException(); // } else { // return this.getParent().loadClass(name); // } // } // }; classLoadersFingerprints.put(classPathClassLoader, ""); } // // Extract refresh interval // long delay = DEFAULT_DELAY; String refresh = properties.getProperty(Configuration.JARS_REFRESH); if (null != refresh) { try { delay = Long.parseLong(refresh.toString()); } catch (Exception e) { } } new WarpScriptJarRepository(dir, delay); } }
warp10/src/main/java/io/warp10/script/WarpScriptJarRepository.java
// // Copyright 2016 Cityzen Data // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.script; import io.warp10.continuum.Configuration; import io.warp10.continuum.sensision.SensisionConstants; import io.warp10.sensision.Sensision; import io.warp10.warp.sdk.WarpScriptJavaFunction; import io.warp10.warp.sdk.WarpScriptJavaFunctionException; import io.warp10.warp.sdk.WarpScriptRawJavaFunction; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.bouncycastle.util.encoders.Hex; import com.google.common.base.Charsets; /** * Class which manages Einstein functions stored in jar files from a directory */ public class WarpScriptJarRepository extends Thread { /** * Default refresh delay is 60 minutes */ private static final long DEFAULT_DELAY = 3600000L; private static final String JAR_EXTENSION = ".jar"; /** * Directory where the '.jar' files are */ private final String directory; /** * How often to check for changes */ private final long delay; /** * Active Class Loaders and their associated fingerprint. */ private final static Map<ClassLoader,String> classLoadersFingerprints = new LinkedHashMap<ClassLoader,String>(); private static ClassLoader classPathClassLoader = null; private final static Map<String,WarpScriptJavaFunction> cachedUDFs = new HashMap<String, WarpScriptJavaFunction>(); public WarpScriptJarRepository(String directory, long delay) { this.directory = directory; this.delay = delay; if (null != directory) { this.setName("[Warp Jar Repository (" + directory + ")"); this.setDaemon(true); this.start(); } } @Override public void run() { while(true) { String rootdir = new File(this.directory).getAbsolutePath(); // // Open directory // File[] files = new File(rootdir).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.endsWith(JAR_EXTENSION)) { return false; } else { return true; } } }); // // Loop over the files, creating the class loaders // // Map of CL to fingerprint Map<ClassLoader,String> newClassLoadersFingerprints = new LinkedHashMap<ClassLoader,String>(); byte[] buf = new byte[8192]; try { MessageDigest md = MessageDigest.getInstance("SHA-1"); for (File file: files) { // // Compute hash of content // FileInputStream in = new FileInputStream(file); while(true) { int len = in.read(buf); if (len < 0) { break; } md.update(buf, 0, len); } in.close(); String hash = new String(Hex.encode(md.digest()), Charsets.US_ASCII); if (classLoadersFingerprints.containsValue(hash) && !newClassLoadersFingerprints.containsValue(hash)) { // Reuse existing class loader, so we keep the created objets for (Entry<ClassLoader,String> entry: classLoadersFingerprints.entrySet()) { if (entry.getValue().equals(hash)) { newClassLoadersFingerprints.put(entry.getKey(), entry.getValue()); } } } else if (!newClassLoadersFingerprints.containsKey(hash)){ // Create new classloader with filtering so caller cannot access the io.warp10 classes, except those needed ClassLoader filteringCL = new ClassLoader(this.getClass().getClassLoader()) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("io.warp10") && !name.startsWith("io.warp10.warp.sdk.")) { throw new ClassNotFoundException(); } else { return this.getParent().loadClass(name); } } }; URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); newClassLoadersFingerprints.put(new URLClassLoader(urls, filteringCL), hash); } } } catch (NoSuchAlgorithmException nsae) { } catch (IOException ioe) { } // // Replace the previous classLoaders // synchronized(classLoadersFingerprints) { classLoadersFingerprints.clear(); classLoadersFingerprints.putAll(newClassLoadersFingerprints); // Add the class path class loader too if (null != classPathClassLoader) { classLoadersFingerprints.put(classPathClassLoader, ""); } } // // Update jar count // Sensision.set(SensisionConstants.SENSISION_CLASS_EINSTEIN_REPOSITORY_JARS, Sensision.EMPTY_LABELS, classLoadersFingerprints.size()); // // Sleep a while // try { Thread.sleep(this.delay); } catch (InterruptedException ie) { } } } /** * Load an instance of a UDF, possibly checking the cache. * * @param name * @param cached * @return * @throws WarpScriptException */ public static WarpScriptJavaFunction load(String name, boolean cached) throws WarpScriptException { WarpScriptJavaFunction udf = null; if (cached) { udf = cachedUDFs.get(name); if (null != udf && validate(udf)) { return udf; } else { // Clear from cache cachedUDFs.remove(name); udf = null; } } for (Entry<ClassLoader,String> entry: classLoadersFingerprints.entrySet()) { try { ClassLoader cl = entry.getKey(); Class cls = cl.loadClass(name); Object o = cls.newInstance(); if (!(o instanceof WarpScriptJavaFunction)) { throw new WarpScriptException(name + " does not appear to be of type " + WarpScriptJavaFunction.class.getCanonicalName()); } udf = (WarpScriptJavaFunction) o; // // If the UDF was loaded from the class path class loader, wrap it so it is unprotected // if (cl.equals(classPathClassLoader)) { final WarpScriptJavaFunction innerUDF = udf; if (udf instanceof WarpScriptRawJavaFunction) { udf = new WarpScriptRawJavaFunction() { @Override public boolean isProtected() { return false; } @Override public int argDepth() { return innerUDF.argDepth(); } @Override public List<Object> apply(List<Object> args) throws WarpScriptJavaFunctionException { return innerUDF.apply(args); } }; } else { udf = new WarpScriptJavaFunction() { @Override public boolean isProtected() { return false; } @Override public int argDepth() { return innerUDF.argDepth(); } @Override public List<Object> apply(List<Object> args) throws WarpScriptJavaFunctionException { return innerUDF.apply(args); } }; } } break; } catch (Exception e) { continue; } } if (cached && null != udf) { cachedUDFs.put(name, udf); } if (null == udf) { throw new WarpScriptException("Class '" + name + "' was not found in any of the current WarpScript jars."); } return udf; } /** * Validates an instance of EinsteinJavaFunction by checking that its class loader is still active * @param func Instance to check * @return */ private static boolean validate(WarpScriptJavaFunction func) { if (null == func) { return true; } return classLoadersFingerprints.containsKey(func.getClass().getClassLoader()); } public static void init(Properties properties) { // // Extract root directory // String dir = properties.getProperty(Configuration.JARS_DIRECTORY); if (null == dir && !"true".equals(properties.getProperty(Configuration.JARS_FROMCLASSPATH))) { return; } // // Simply add a class loader to access the current classpath // if (null == dir) { classPathClassLoader = new ClassLoader(WarpScriptJarRepository.class.getClassLoader()) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (name.startsWith("io.warp10") && !name.startsWith("io.warp10.warp.sdk.")) { throw new ClassNotFoundException(); } else { return this.getParent().loadClass(name); } } }; classLoadersFingerprints.put(classPathClassLoader, ""); } // // Extract refresh interval // long delay = DEFAULT_DELAY; String refresh = properties.getProperty(Configuration.JARS_REFRESH); if (null != refresh) { try { delay = Long.parseLong(refresh.toString()); } catch (Exception e) { } } new WarpScriptJarRepository(dir, delay); } }
Removed class loading restrictions, they were a residue of the time when Warp was distributed as a protected jar
warp10/src/main/java/io/warp10/script/WarpScriptJarRepository.java
Removed class loading restrictions, they were a residue of the time when Warp was distributed as a protected jar
Java
apache-2.0
c7316e390a1ee4c345c67edb13abb4df93569b66
0
facebook/presto,zhenxiao/presto,sunchao/presto,cberner/presto,xiangel/presto,ArturGajowy/presto,EvilMcJerkface/presto,hulu/presto,gcnonato/presto,fiedukow/presto,ocono-tech/presto,Jimexist/presto,martint/presto,nezihyigitbasi/presto,denizdemir/presto,prestodb/presto,Jimexist/presto,dongjoon-hyun/presto,chrisunder/presto,stewartpark/presto,treasure-data/presto,elonazoulay/presto,treasure-data/presto,smartnews/presto,ebyhr/presto,facebook/presto,jekey/presto,fipar/presto,nileema/presto,fengshao0907/presto,kined/presto,jekey/presto,twitter-forks/presto,Teradata/presto,lingochamp/presto,Zoomdata/presto,zzhao0/presto,soz-fb/presto,nezihyigitbasi/presto,kingland/presto,denizdemir/presto,haozhun/presto,gcnonato/presto,mode/presto,cosinequanon/presto,martint/presto,ipros-team/presto,propene/presto,mbeitchman/presto,yu-yamada/presto,smartnews/presto,dongjoon-hyun/presto,tellproject/presto,propene/presto,avasilevskiy/presto,jacobgao/presto,deciament/presto,haozhun/presto,haitaoyao/presto,tomz/presto,jf367/presto,vishalsan/presto,haitaoyao/presto,wangcan2014/presto,deciament/presto,ocono-tech/presto,svstanev/presto,toyama0919/presto,idemura/presto,wrmsr/presto,miquelruiz/presto,saidalaoui/presto,DanielTing/presto,damiencarol/presto,denizdemir/presto,siddhartharay007/presto,rockerbox/presto,Yaliang/presto,electrum/presto,avasilevskiy/presto,toxeh/presto,soz-fb/presto,jxiang/presto,zhenyuy-fb/presto,youngwookim/presto,EvilMcJerkface/presto,twitter-forks/presto,pwz3n0/presto,nvoron23/presto,totticarter/presto,lingochamp/presto,bloomberg/presto,miquelruiz/presto,joy-yao/presto,ptkool/presto,jf367/presto,kingland/presto,nsabharwal/presto,wangcan2014/presto,aramesh117/presto,aramesh117/presto,Zoomdata/presto,shixuan-fan/presto,smartpcr/presto,stewartpark/presto,EvilMcJerkface/presto,sumanth232/presto,kaschaeffer/presto,martint/presto,ptkool/presto,ajoabraham/presto,toxeh/presto,y-lan/presto,prestodb/presto,cosinequanon/presto,raghavsethi/presto,EvilMcJerkface/presto,electrum/presto,jxiang/presto,ebyhr/presto,mugglmenzel/presto,vermaravikant/presto,Praveen2112/presto,idemura/presto,jf367/presto,toyama0919/presto,ArturGajowy/presto,CHINA-JD/presto,hgschmie/presto,mugglmenzel/presto,lingochamp/presto,11xor6/presto,ajoabraham/presto,mbeitchman/presto,sunchao/presto,cberner/presto,miniway/presto,11xor6/presto,toxeh/presto,jacobgao/presto,jiangyifangh/presto,haitaoyao/presto,yuananf/presto,wrmsr/presto,saidalaoui/presto,aleph-zero/presto,hgschmie/presto,elonazoulay/presto,jf367/presto,miniway/presto,pwz3n0/presto,zofuthan/presto,RobinUS2/presto,jiangyifangh/presto,sumanth232/presto,arhimondr/presto,kaschaeffer/presto,zhenyuy-fb/presto,dabaitu/presto,wagnermarkd/presto,zzhao0/presto,pnowojski/presto,CHINA-JD/presto,jiangyifangh/presto,Nasdaq/presto,chrisunder/presto,Teradata/presto,jxiang/presto,aglne/presto,gcnonato/presto,nezihyigitbasi/presto,avasilevskiy/presto,ptkool/presto,wrmsr/presto,springning/presto,gh351135612/presto,smartnews/presto,shubham166/presto,wagnermarkd/presto,rockerbox/presto,mvp/presto,suyucs/presto,yuananf/presto,nileema/presto,troels/nz-presto,erichwang/presto,Nasdaq/presto,CHINA-JD/presto,prateek1306/presto,arhimondr/presto,dain/presto,cosinequanon/presto,aglne/presto,electrum/presto,miquelruiz/presto,zhenyuy-fb/presto,Myrthan/presto,albertocsm/presto,joshk/presto,treasure-data/presto,Zoomdata/presto,soz-fb/presto,mono-plane/presto,smartpcr/presto,dongjoon-hyun/presto,losipiuk/presto,zhenxiao/presto,sumitkgec/presto,geraint0923/presto,fiedukow/presto,vermaravikant/presto,kaschaeffer/presto,zhenyuy-fb/presto,pnowojski/presto,mode/presto,totticarter/presto,twitter-forks/presto,youngwookim/presto,mandusm/presto,saidalaoui/presto,takari/presto,Yaliang/presto,Svjard/presto,miquelruiz/presto,Teradata/presto,kuzemchik/presto,toyama0919/presto,miniway/presto,facebook/presto,dabaitu/presto,Teradata/presto,mattyb149/presto,11xor6/presto,gcnonato/presto,Teradata/presto,aglne/presto,yuananf/presto,zofuthan/presto,prestodb/presto,mcanthony/presto,hulu/presto,frsyuki/presto,pnowojski/presto,fipar/presto,mandusm/presto,wrmsr/presto,twitter-forks/presto,Svjard/presto,springning/presto,Praveen2112/presto,vermaravikant/presto,dongjoon-hyun/presto,jietang3/test,martint/presto,harunurhan/presto,mvp/presto,erichwang/presto,sdgdsffdsfff/presto,dabaitu/presto,XiaominZhang/presto,elonazoulay/presto,dain/presto,kingland/presto,zzhao0/presto,joy-yao/presto,facebook/presto,damiencarol/presto,avasilevskiy/presto,wyukawa/presto,zjshen/presto,mpilman/presto,DanielTing/presto,tomz/presto,idemura/presto,lingochamp/presto,ipros-team/presto,ajoabraham/presto,kuzemchik/presto,ocono-tech/presto,mono-plane/presto,fipar/presto,albertocsm/presto,sopel39/presto,aleph-zero/presto,Svjard/presto,takari/presto,Myrthan/presto,XiaominZhang/presto,ebd2/presto,deciament/presto,cawallin/presto,RobinUS2/presto,youngwookim/presto,Praveen2112/presto,cberner/presto,kietly/presto,yu-yamada/presto,damiencarol/presto,Yaliang/presto,wangcan2014/presto,sunchao/presto,y-lan/presto,sumitkgec/presto,saidalaoui/presto,idemura/presto,tellproject/presto,stagraqubole/presto,aramesh117/presto,miniway/presto,Zoomdata/presto,zofuthan/presto,stewartpark/presto,raghavsethi/presto,jiekechoo/presto,wangcan2014/presto,Svjard/presto,yu-yamada/presto,miquelruiz/presto,TeradataCenterForHadoop/bootcamp,mpilman/presto,ajoabraham/presto,aleph-zero/presto,gh351135612/presto,siddhartharay007/presto,mugglmenzel/presto,ipros-team/presto,nakajijiji/presto,fiedukow/presto,XiaominZhang/presto,mattyb149/presto,troels/nz-presto,sumanth232/presto,pwz3n0/presto,ebd2/presto,wagnermarkd/presto,hulu/presto,shixuan-fan/presto,jiangyifangh/presto,siddhartharay007/presto,jxiang/presto,mode/presto,DanielTing/presto,albertocsm/presto,sumanth232/presto,aramesh117/presto,losipiuk/presto,damiencarol/presto,jiekechoo/presto,mpilman/presto,bloomberg/presto,tellproject/presto,vermaravikant/presto,sopel39/presto,totticarter/presto,svstanev/presto,sumitkgec/presto,Nasdaq/presto,denizdemir/presto,Myrthan/presto,gh351135612/presto,troels/nz-presto,wyukawa/presto,Svjard/presto,harunurhan/presto,arhimondr/presto,cawallin/presto,treasure-data/presto,joy-yao/presto,fengshao0907/presto,haozhun/presto,toyama0919/presto,jekey/presto,svstanev/presto,ArturGajowy/presto,Nasdaq/presto,svstanev/presto,losipiuk/presto,fipar/presto,harunurhan/presto,mandusm/presto,HackShare/Presto,prestodb/presto,ebd2/presto,zhenxiao/presto,smartpcr/presto,facebook/presto,ebd2/presto,losipiuk/presto,stewartpark/presto,wyukawa/presto,wrmsr/presto,mono-plane/presto,RobinUS2/presto,nsabharwal/presto,tomz/presto,fipar/presto,miniway/presto,nakajijiji/presto,prateek1306/presto,propene/presto,toyama0919/presto,CHINA-JD/presto,yu-yamada/presto,rockerbox/presto,kietly/presto,mandusm/presto,ArturGajowy/presto,ebyhr/presto,mattyb149/presto,nakajijiji/presto,nakajijiji/presto,kingland/presto,yu-yamada/presto,albertocsm/presto,soz-fb/presto,zjshen/presto,smartpcr/presto,totticarter/presto,losipiuk/presto,prestodb/presto,jiekechoo/presto,stagraqubole/presto,electrum/presto,electrum/presto,cosinequanon/presto,y-lan/presto,siddhartharay007/presto,Jimexist/presto,albertocsm/presto,shubham166/presto,springning/presto,fengshao0907/presto,Praveen2112/presto,fiedukow/presto,stewartpark/presto,zzhao0/presto,lingochamp/presto,kuzemchik/presto,kaschaeffer/presto,jxiang/presto,Jimexist/presto,dongjoon-hyun/presto,harunurhan/presto,chrisunder/presto,prateek1306/presto,jf367/presto,fiedukow/presto,Myrthan/presto,raghavsethi/presto,aleph-zero/presto,elonazoulay/presto,deciament/presto,smartnews/presto,mandusm/presto,bloomberg/presto,haitaoyao/presto,bloomberg/presto,dain/presto,jekey/presto,chrisunder/presto,nileema/presto,raghavsethi/presto,arhimondr/presto,mugglmenzel/presto,xiangel/presto,TeradataCenterForHadoop/bootcamp,aglne/presto,HackShare/Presto,mode/presto,suyucs/presto,sumitkgec/presto,fengshao0907/presto,jiekechoo/presto,RobinUS2/presto,mvp/presto,zjshen/presto,geraint0923/presto,jekey/presto,kietly/presto,Myrthan/presto,tellproject/presto,wrmsr/presto,raghavsethi/presto,kined/presto,springning/presto,haozhun/presto,jacobgao/presto,ocono-tech/presto,nakajijiji/presto,jietang3/test,CHINA-JD/presto,mcanthony/presto,deciament/presto,prestodb/presto,ipros-team/presto,prateek1306/presto,mpilman/presto,mcanthony/presto,kined/presto,haozhun/presto,zjshen/presto,11xor6/presto,dabaitu/presto,pwz3n0/presto,dabaitu/presto,propene/presto,XiaominZhang/presto,zjshen/presto,mono-plane/presto,mpilman/presto,EvilMcJerkface/presto,prateek1306/presto,joy-yao/presto,Praveen2112/presto,toxeh/presto,bloomberg/presto,tomz/presto,tellproject/presto,troels/nz-presto,mattyb149/presto,soz-fb/presto,totticarter/presto,y-lan/presto,TeradataCenterForHadoop/bootcamp,chrisunder/presto,yuananf/presto,joshk/presto,frsyuki/presto,takari/presto,harunurhan/presto,ptkool/presto,nsabharwal/presto,tomz/presto,twitter-forks/presto,shixuan-fan/presto,wyukawa/presto,takari/presto,yuananf/presto,sunchao/presto,idemura/presto,mpilman/presto,aglne/presto,haitaoyao/presto,nvoron23/presto,kietly/presto,aleph-zero/presto,ajoabraham/presto,suyucs/presto,nvoron23/presto,hulu/presto,jiangyifangh/presto,shubham166/presto,shixuan-fan/presto,zhenyuy-fb/presto,Nasdaq/presto,jiekechoo/presto,sopel39/presto,DanielTing/presto,ptkool/presto,gh351135612/presto,nsabharwal/presto,propene/presto,troels/nz-presto,xiangel/presto,mugglmenzel/presto,nsabharwal/presto,elonazoulay/presto,springning/presto,geraint0923/presto,mvp/presto,shixuan-fan/presto,fengshao0907/presto,erichwang/presto,ebyhr/presto,Zoomdata/presto,treasure-data/presto,youngwookim/presto,zofuthan/presto,wagnermarkd/presto,smartnews/presto,wangcan2014/presto,kuzemchik/presto,sopel39/presto,kuzemchik/presto,erichwang/presto,suyucs/presto,Yaliang/presto,arhimondr/presto,kaschaeffer/presto,avasilevskiy/presto,dain/presto,vishalsan/presto,aramesh117/presto,HackShare/Presto,hulu/presto,mbeitchman/presto,ArturGajowy/presto,smartpcr/presto,nileema/presto,sdgdsffdsfff/presto,rockerbox/presto,wyukawa/presto,xiangel/presto,wagnermarkd/presto,geraint0923/presto,sumanth232/presto,damiencarol/presto,jacobgao/presto,TeradataCenterForHadoop/bootcamp,nileema/presto,cawallin/presto,kingland/presto,ebyhr/presto,cawallin/presto,zofuthan/presto,sumitkgec/presto,dain/presto,kined/presto,sopel39/presto,takari/presto,rockerbox/presto,nezihyigitbasi/presto,ipros-team/presto,suyucs/presto,cawallin/presto,mbeitchman/presto,RobinUS2/presto,pwz3n0/presto,sdgdsffdsfff/presto,sunchao/presto,joy-yao/presto,mcanthony/presto,hgschmie/presto,cberner/presto,gh351135612/presto,tellproject/presto,erichwang/presto,zzhao0/presto,Jimexist/presto,cberner/presto,ocono-tech/presto,11xor6/presto,cosinequanon/presto,geraint0923/presto,mcanthony/presto,hgschmie/presto,zhenxiao/presto,nvoron23/presto,mattyb149/presto,TeradataCenterForHadoop/bootcamp,Yaliang/presto,martint/presto,XiaominZhang/presto,treasure-data/presto,toxeh/presto,vermaravikant/presto,mode/presto,siddhartharay007/presto,kietly/presto,ebd2/presto,saidalaoui/presto,pnowojski/presto,vishalsan/presto,mbeitchman/presto,mvp/presto,y-lan/presto,hgschmie/presto,DanielTing/presto,joshk/presto,youngwookim/presto,joshk/presto,kined/presto,nezihyigitbasi/presto,svstanev/presto,shubham166/presto,xiangel/presto
package com.facebook.presto; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.split.DataStreamProvider; import com.facebook.presto.sql.analyzer.Session; import com.facebook.presto.util.LocalQueryRunner; import com.facebook.presto.util.MaterializedResult; import org.intellij.lang.annotations.Language; public class TestLocalQueries extends AbstractTestQueries { private String catalog; private String schema; private DataStreamProvider dataStreamProvider; private Metadata metadata; @Override protected void setUpQueryFramework(String catalog, String schema, DataStreamProvider dataStreamProvider, Metadata metadata) throws Exception { this.catalog = catalog; this.schema = schema; this.dataStreamProvider = dataStreamProvider; this.metadata = metadata; } @Override protected MaterializedResult computeActual(@Language("SQL") String sql) { Session session = new Session(null, catalog, schema); LocalQueryRunner runner = new LocalQueryRunner(dataStreamProvider, metadata, session); return runner.execute(sql); } }
presto-main/src/test/java/com/facebook/presto/TestLocalQueries.java
package com.facebook.presto; import com.facebook.presto.execution.ExchangePlanFragmentSource; import com.facebook.presto.execution.QueryManagerConfig; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.operator.Operator; import com.facebook.presto.operator.OperatorStats; import com.facebook.presto.operator.SourceHashProviderFactory; import com.facebook.presto.operator.HackPlanFragmentSourceProvider; import com.facebook.presto.split.DataStreamProvider; import com.facebook.presto.sql.analyzer.AnalysisResult; import com.facebook.presto.sql.analyzer.Analyzer; import com.facebook.presto.sql.analyzer.Session; import com.facebook.presto.sql.parser.SqlParser; import com.facebook.presto.sql.planner.DistributedLogicalPlanner; import com.facebook.presto.sql.planner.LocalExecutionPlanner; import com.facebook.presto.sql.planner.LogicalPlanner; import com.facebook.presto.sql.planner.PlanNodeIdAllocator; import com.facebook.presto.sql.planner.PlanPrinter; import com.facebook.presto.sql.planner.SubPlan; import com.facebook.presto.sql.planner.TableScanPlanFragmentSource; import com.facebook.presto.sql.planner.plan.PlanNode; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.facebook.presto.sql.planner.plan.TableScanNode; import com.facebook.presto.sql.tree.Statement; import com.facebook.presto.tpch.TpchSplit; import com.facebook.presto.tpch.TpchTableHandle; import com.facebook.presto.util.MaterializedResult; import com.google.common.collect.ImmutableMap; import io.airlift.units.DataSize; import org.intellij.lang.annotations.Language; import static com.facebook.presto.util.MaterializedResult.materialize; import static io.airlift.units.DataSize.Unit.MEGABYTE; import static org.testng.Assert.assertTrue; public class TestLocalQueries extends AbstractTestQueries { private String catalog; private String schema; private DataStreamProvider dataStreamProvider; private Metadata metadata; @Override protected void setUpQueryFramework(String catalog, String schema, DataStreamProvider dataStreamProvider, Metadata metadata) throws Exception { this.catalog = catalog; this.schema = schema; this.dataStreamProvider = dataStreamProvider; this.metadata = metadata; } @Override protected MaterializedResult computeActual(@Language("SQL") String sql) { Statement statement = SqlParser.createStatement(sql); Session session = new Session(null, catalog, schema); Analyzer analyzer = new Analyzer(session, metadata); AnalysisResult analysis = analyzer.analyze(statement); PlanNodeIdAllocator idAllocator = new PlanNodeIdAllocator(); PlanNode plan = new LogicalPlanner(session, metadata, idAllocator).plan(analysis); new PlanPrinter().print(plan, analysis.getTypes()); SubPlan subplan = new DistributedLogicalPlanner(metadata, idAllocator).createSubplans(plan, analysis.getSymbolAllocator(), true); assertTrue(subplan.getChildren().isEmpty(), "Expected subplan to have no children"); ImmutableMap.Builder<PlanNodeId, TableScanPlanFragmentSource> builder = ImmutableMap.builder(); for (PlanNode source : subplan.getFragment().getSources()) { TableScanNode tableScan = (TableScanNode) source; TpchTableHandle handle = (TpchTableHandle) tableScan.getTable(); builder.put(tableScan.getId(), new TableScanPlanFragmentSource(new TpchSplit(handle))); } DataSize maxOperatorMemoryUsage = new DataSize(50, MEGABYTE); LocalExecutionPlanner executionPlanner = new LocalExecutionPlanner(session, metadata, new HackPlanFragmentSourceProvider(dataStreamProvider, null, new QueryManagerConfig()), analysis.getTypes(), null, builder.build(), ImmutableMap.<PlanNodeId, ExchangePlanFragmentSource>of(), new OperatorStats(), new SourceHashProviderFactory(maxOperatorMemoryUsage), maxOperatorMemoryUsage ); Operator operator = executionPlanner.plan(plan); return materialize(operator); } }
Make TestLocalQueries use LocalQueryRunner
presto-main/src/test/java/com/facebook/presto/TestLocalQueries.java
Make TestLocalQueries use LocalQueryRunner
Java
bsd-3-clause
d5a3d88a0eaf5d0c2fbf676bf73b5e71a46e22f8
0
plotters/wobmail,plotters/wobmail,plotters/wobmail
package net.xytra.wobmail.manager; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import net.xytra.wobmail.misc.MessageRow; import com.webobjects.eocontrol.EOSortOrdering; import com.webobjects.foundation.NSArray; import com.webobjects.foundation.NSDictionary; import com.webobjects.foundation.NSMutableArray; import com.webobjects.foundation.NSMutableDictionary; import er.extensions.foundation.ERXArrayUtilities; public class Pop3MailSession extends AbstractMailSession { private Folder inboxFolder = null; public Pop3MailSession(String username, String password) { super(username, password); } // Folders synchronized protected Folder obtainOpenInboxFolder() throws MessagingException { if (inboxFolder == null) { inboxFolder = getOpenStore().getFolder("INBOX"); } inboxFolder = obtainOpenFolder(inboxFolder); return (inboxFolder); } @Override protected String getMailProtocolName() { return ("pop3"); } @Override protected void forgetOpenFolders() { inboxFolder = null; } @Override protected NSArray<Folder> getOpenFolders() { if (inboxFolder == null) { return (NSArray.EmptyArray); } else { return (new NSArray<Folder>(inboxFolder)); } } // Folder contents private NSDictionary<Integer, MessageRow> cachedInboxMessageRows = null; private NSArray<Integer> cachedSortedInboxMessageNumbers = null; private NSArray<MessageRow> cachedSortedInboxMessageRows = null; /* (non-Javadoc) * @see net.xytra.wobmail.manager.MailSession#getMessageRowsForFolder(java.lang.String, boolean) * Return an array of MessageRow objects by using the cached ordered message numbers. */ public NSArray<MessageRow> getMessageRowsForFolder(String folderName, boolean forceReload) throws MessagingException { if (!INBOX_FOLDER_NAME.equals(folderName)) { throw (new MailSessionException("Cannot get MessageRow objects for specified folderName as such a folder does not exist")); } // forceReload == true means that we have to invalidate the message numbers and rows if (forceReload) { cachedSortedInboxMessageNumbers = null; cachedSortedInboxMessageRows = null; } if ((cachedSortedInboxMessageNumbers == null) || (cachedSortedInboxMessageRows == null)) { NSDictionary<Integer, MessageRow> messageRowsDictionary = getMessageRowDictionaryForFolder(folderName, forceReload); if (cachedSortedInboxMessageNumbers == null) { cachedSortedInboxMessageNumbers = getMessageNumbersSortedForFolder(messageRowsDictionary, folderName); // Invalidate cached inbox rows cachedSortedInboxMessageRows = null; } if (cachedSortedInboxMessageRows == null) { cachedSortedInboxMessageRows = getOrderedMessageRows(messageRowsDictionary, cachedSortedInboxMessageNumbers); } } return (cachedSortedInboxMessageRows); } protected NSArray<MessageRow> getOrderedMessageRows(NSDictionary<Integer, MessageRow> messageRows, NSArray<Integer> messageNumbers) { NSMutableArray<MessageRow> orderedMessageRows = new NSMutableArray<MessageRow>(); Enumeration en1 = messageNumbers.objectEnumerator(); while (en1.hasMoreElements()) { orderedMessageRows.addObject(messageRows.objectForKey(en1.nextElement())); } return (orderedMessageRows); } protected NSArray<Integer> getMessageNumbersSortedForFolder(NSDictionary<Integer, MessageRow> messageRows, String folderName) { return ((NSArray<Integer>)ERXArrayUtilities.sortedArraySortedWithKey( messageRows.allValues(), sortKeyForFolder(folderName), isReverseSortForFolder(folderName) ? EOSortOrdering.CompareCaseInsensitiveDescending : EOSortOrdering.CompareCaseInsensitiveAscending).valueForKey("messageNumber")); } protected NSDictionary<Integer, MessageRow> getMessageRowDictionaryForFolder(String folderName, boolean forceReload) throws MessagingException { NSDictionary<Integer, MessageRow> dict = getCachedMessageRowDictionaryForFolder(folderName); if (forceReload || (dict == null)) { NSMutableDictionary<Integer, MessageRow> newMessageRowDict = new NSMutableDictionary<Integer, MessageRow>(); Enumeration<MessageRow> en1 = getFreshUnsortedMessageRowsForInbox().objectEnumerator(); while (en1.hasMoreElements()) { MessageRow mr = en1.nextElement(); newMessageRowDict.setObjectForKey(mr, mr.getMessageNumber()); } // Set the return value dict = newMessageRowDict; // Save our new dictionary setCachedMessageRowDictionaryForFolder(dict, folderName); } return (dict); } protected NSArray<MessageRow> getFreshUnsortedMessageRowsForInbox() throws MessagingException { NSArray unsortedMessageRows; // Only allow one such access at a time through this session synchronized (this) { // Get all messages from INBOX Message[] messages = obtainOpenInboxFolder().getMessages(); NSMutableArray<MessageRow> messageRowsArray = new NSMutableArray<MessageRow>(); // Let's get each message in a wrapper and keep it all for future use: for (int i=0; i<messages.length; i++) { messageRowsArray.addObject(new MessageRow(messages[i])); } unsortedMessageRows = messageRowsArray.immutableClone(); } return (unsortedMessageRows); } protected NSDictionary<Integer, MessageRow> getCachedMessageRowDictionaryForFolder(String folderName) { if (MailSession.INBOX_FOLDER_NAME.equals(folderName)) { return (cachedInboxMessageRows); } else { throw (new MailSessionException("Cannot set MessageRow objects for specified folderName as such a folder does not exist")); } } protected void setCachedMessageRowDictionaryForFolder(NSDictionary<Integer, MessageRow> messageRows, String folderName) { if (MailSession.INBOX_FOLDER_NAME.equals(folderName)) { cachedInboxMessageRows = messageRows; } else { throw (new MailSessionException("Cannot set MessageRow objects for specified folderName as such a folder does not exist")); } } /** * Sort the specified folder's message list and return the newly sorted list. * Sort the specified folder's message list using specified sorting key; do * a reverse sort if reverseSort is true. * * @param folderName Name of the folder whose messages will be sorted. * @param sortKey Key representing which message property by which to sort. * @param reverseSort Whether to reverse sort. */ public void sortMessageRowsForFolderSortedWithKey(String folderName, String sortKey, boolean reverseSort) throws MessagingException { String currentSortKey = sortKeyForFolder(folderName); boolean currentReverseSort = isReverseSortForFolder(folderName); // Set the new parameters: setSortKeyForFolder(sortKey, folderName); setReverseSortForFolder(reverseSort, folderName); if (!currentSortKey.equals(sortKey)) { // Sort key has changed, just invalidate cache cachedSortedInboxMessageNumbers = null; cachedSortedInboxMessageRows = null; } else if (reverseSort != currentReverseSort) { // Sort key hasn't changed; only reverse the order: cachedSortedInboxMessageNumbers = ERXArrayUtilities.reverse(cachedSortedInboxMessageNumbers); cachedSortedInboxMessageRows = ERXArrayUtilities.reverse(cachedSortedInboxMessageRows); } } private Map folderNameToSortKeyMap = Collections.synchronizedMap(new HashMap<String, String>()); private Map folderNameToReverseSortMap = Collections.synchronizedMap(new HashMap<String, Boolean>()); public String sortKeyForFolder(String folderName) { String sortKey = (String)folderNameToSortKeyMap.get(folderName); if (sortKey == null) { // Set sort column to Date Sent as default: sortKey = MessageRow.DATE_SENT_SORT_FIELD; folderNameToSortKeyMap.put(folderName, sortKey); } return (sortKey); } protected void setSortKeyForFolder(String sortKey, String folderName) { folderNameToSortKeyMap.put(folderName, sortKey); } public boolean isReverseSortForFolder(String folderName) { Boolean isReverseSort = (Boolean)folderNameToReverseSortMap.get(folderName); if (isReverseSort == null) { // Set reverse to false as default: isReverseSort = Boolean.FALSE; folderNameToReverseSortMap.put(folderName, isReverseSort); } return (isReverseSort.booleanValue()); } protected void setReverseSortForFolder(boolean reverse, String folderName) { folderNameToReverseSortMap.put(folderName, Boolean.valueOf(reverse)); } // Messages public void moveMessageRowsToFolder(NSArray<MessageRow> messageRows, String folderName) throws MessagingException { if (!MailSession.TRASH_FOLDER_NAME.equals(folderName)) { throw (new MailSessionException("Can only move to Trash in POP3. Not allowed to use folderName="+folderName)); } moveMessageRowsToTrash(messageRows); } protected void moveMessageRowsToTrash(NSArray<MessageRow> messageRows) throws MessagingException { deleteMessageRows(messageRows); } synchronized protected void deleteMessageRows(NSArray<MessageRow> messageRows) throws MessagingException { Enumeration<MessageRow> en1 = messageRows.objectEnumerator(); while (en1.hasMoreElements()) { deleteMessageRow(en1.nextElement()); } } protected void deleteMessageRow(MessageRow messageRow) throws MessagingException { messageRow.setIsDeleted(true); cachedInboxMessageRows.remove(messageRow.getMessageNumber()); cachedSortedInboxMessageNumbers.remove(messageRow.getMessageNumber()); cachedSortedInboxMessageRows.remove(messageRow); } }
src/net/xytra/wobmail/manager/Pop3MailSession.java
package net.xytra.wobmail.manager; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import net.xytra.wobmail.misc.MessageRow; import com.webobjects.eocontrol.EOSortOrdering; import com.webobjects.foundation.NSArray; import com.webobjects.foundation.NSDictionary; import com.webobjects.foundation.NSMutableArray; import com.webobjects.foundation.NSMutableDictionary; import er.extensions.foundation.ERXArrayUtilities; public class Pop3MailSession extends AbstractMailSession { private Folder inboxFolder = null; public Pop3MailSession(String username, String password) { super(username, password); } // Folders synchronized protected Folder obtainOpenInboxFolder() throws MessagingException { if (inboxFolder == null) { inboxFolder = getOpenStore().getFolder("INBOX"); } inboxFolder = obtainOpenFolder(inboxFolder); return (inboxFolder); } @Override protected String getMailProtocolName() { return ("pop3"); } @Override protected void forgetOpenFolders() { inboxFolder = null; } @Override protected NSArray<Folder> getOpenFolders() { if (inboxFolder == null) { return (NSArray.EmptyArray); } else { return (new NSArray<Folder>(inboxFolder)); } } // Folder contents private NSDictionary<Integer, MessageRow> cachedInboxMessageRows = null; private NSArray<Integer> cachedSortedInboxMessageNumbers = null; private NSArray<MessageRow> cachedSortedInboxMessageRows = null; /* (non-Javadoc) * @see net.xytra.wobmail.manager.MailSession#getMessageRowsForFolder(java.lang.String, boolean) * Return an array of MessageRow objects by using the cached ordered message numbers. */ public NSArray<MessageRow> getMessageRowsForFolder(String folderName, boolean forceReload) throws MessagingException { if (!INBOX_FOLDER_NAME.equals(folderName)) { throw (new MailSessionException("Cannot get MessageRow objects for specified folderName as such a folder does not exist")); } if (forceReload || (cachedSortedInboxMessageNumbers == null) || (cachedSortedInboxMessageRows == null)) { NSDictionary<Integer, MessageRow> messageRowsDictionary = getMessageRowDictionaryForFolder(folderName, forceReload); if (cachedSortedInboxMessageNumbers == null) { cachedSortedInboxMessageNumbers = getMessageNumbersSortedForFolder(messageRowsDictionary, folderName); // Invalidate cached inbox rows cachedSortedInboxMessageRows = null; } if (cachedSortedInboxMessageRows == null) { cachedSortedInboxMessageRows = getOrderedMessageRows(messageRowsDictionary, cachedSortedInboxMessageNumbers); } } return (cachedSortedInboxMessageRows); } protected NSArray<MessageRow> getOrderedMessageRows(NSDictionary<Integer, MessageRow> messageRows, NSArray<Integer> messageNumbers) { NSMutableArray<MessageRow> orderedMessageRows = new NSMutableArray<MessageRow>(); Enumeration en1 = messageNumbers.objectEnumerator(); while (en1.hasMoreElements()) { orderedMessageRows.addObject(messageRows.objectForKey(en1.nextElement())); } return (orderedMessageRows); } protected NSArray<Integer> getMessageNumbersSortedForFolder(NSDictionary<Integer, MessageRow> messageRows, String folderName) { return ((NSArray<Integer>)ERXArrayUtilities.sortedArraySortedWithKey( messageRows.allValues(), sortKeyForFolder(folderName), isReverseSortForFolder(folderName) ? EOSortOrdering.CompareCaseInsensitiveDescending : EOSortOrdering.CompareCaseInsensitiveAscending).valueForKey("messageNumber")); } protected NSDictionary<Integer, MessageRow> getMessageRowDictionaryForFolder(String folderName, boolean forceReload) throws MessagingException { NSDictionary<Integer, MessageRow> dict = getCachedMessageRowDictionaryForFolder(folderName); if (forceReload || (dict == null)) { NSMutableDictionary<Integer, MessageRow> newMessageRowDict = new NSMutableDictionary<Integer, MessageRow>(); Enumeration<MessageRow> en1 = getFreshUnsortedMessageRowsForInbox().objectEnumerator(); while (en1.hasMoreElements()) { MessageRow mr = en1.nextElement(); newMessageRowDict.setObjectForKey(mr, mr.getMessageNumber()); } // Set the return value dict = newMessageRowDict; // Save our new dictionary setCachedMessageRowDictionaryForFolder(dict, folderName); } return (dict); } protected NSArray<MessageRow> getFreshUnsortedMessageRowsForInbox() throws MessagingException { NSArray unsortedMessageRows; // Only allow one such access at a time through this session synchronized (this) { // Get all messages from INBOX Message[] messages = obtainOpenInboxFolder().getMessages(); NSMutableArray<MessageRow> messageRowsArray = new NSMutableArray<MessageRow>(); // Let's get each message in a wrapper and keep it all for future use: for (int i=0; i<messages.length; i++) { messageRowsArray.addObject(new MessageRow(messages[i])); } unsortedMessageRows = messageRowsArray.immutableClone(); } return (unsortedMessageRows); } protected NSDictionary<Integer, MessageRow> getCachedMessageRowDictionaryForFolder(String folderName) { if (MailSession.INBOX_FOLDER_NAME.equals(folderName)) { return (cachedInboxMessageRows); } else { throw (new MailSessionException("Cannot set MessageRow objects for specified folderName as such a folder does not exist")); } } protected void setCachedMessageRowDictionaryForFolder(NSDictionary<Integer, MessageRow> messageRows, String folderName) { if (MailSession.INBOX_FOLDER_NAME.equals(folderName)) { cachedInboxMessageRows = messageRows; } else { throw (new MailSessionException("Cannot set MessageRow objects for specified folderName as such a folder does not exist")); } } /** * Sort the specified folder's message list and return the newly sorted list. * Sort the specified folder's message list using specified sorting key; do * a reverse sort if reverseSort is true. * * @param folderName Name of the folder whose messages will be sorted. * @param sortKey Key representing which message property by which to sort. * @param reverseSort Whether to reverse sort. */ public void sortMessageRowsForFolderSortedWithKey(String folderName, String sortKey, boolean reverseSort) throws MessagingException { String currentSortKey = sortKeyForFolder(folderName); boolean currentReverseSort = isReverseSortForFolder(folderName); // Set the new parameters: setSortKeyForFolder(sortKey, folderName); setReverseSortForFolder(reverseSort, folderName); if (!currentSortKey.equals(sortKey)) { // Sort key has changed, just invalidate cache cachedSortedInboxMessageNumbers = null; cachedSortedInboxMessageRows = null; } else if (reverseSort != currentReverseSort) { // Sort key hasn't changed; only reverse the order: cachedSortedInboxMessageNumbers = ERXArrayUtilities.reverse(cachedSortedInboxMessageNumbers); cachedSortedInboxMessageRows = ERXArrayUtilities.reverse(cachedSortedInboxMessageRows); } } private Map folderNameToSortKeyMap = Collections.synchronizedMap(new HashMap<String, String>()); private Map folderNameToReverseSortMap = Collections.synchronizedMap(new HashMap<String, Boolean>()); public String sortKeyForFolder(String folderName) { String sortKey = (String)folderNameToSortKeyMap.get(folderName); if (sortKey == null) { // Set sort column to Date Sent as default: sortKey = MessageRow.DATE_SENT_SORT_FIELD; folderNameToSortKeyMap.put(folderName, sortKey); } return (sortKey); } protected void setSortKeyForFolder(String sortKey, String folderName) { folderNameToSortKeyMap.put(folderName, sortKey); } public boolean isReverseSortForFolder(String folderName) { Boolean isReverseSort = (Boolean)folderNameToReverseSortMap.get(folderName); if (isReverseSort == null) { // Set reverse to false as default: isReverseSort = Boolean.FALSE; folderNameToReverseSortMap.put(folderName, isReverseSort); } return (isReverseSort.booleanValue()); } protected void setReverseSortForFolder(boolean reverse, String folderName) { folderNameToReverseSortMap.put(folderName, Boolean.valueOf(reverse)); } // Messages public void moveMessageRowsToFolder(NSArray<MessageRow> messageRows, String folderName) throws MessagingException { if (!MailSession.TRASH_FOLDER_NAME.equals(folderName)) { throw (new MailSessionException("Can only move to Trash in POP3. Not allowed to use folderName="+folderName)); } moveMessageRowsToTrash(messageRows); } protected void moveMessageRowsToTrash(NSArray<MessageRow> messageRows) throws MessagingException { deleteMessageRows(messageRows); } synchronized protected void deleteMessageRows(NSArray<MessageRow> messageRows) throws MessagingException { Enumeration<MessageRow> en1 = messageRows.objectEnumerator(); while (en1.hasMoreElements()) { deleteMessageRow(en1.nextElement()); } } protected void deleteMessageRow(MessageRow messageRow) throws MessagingException { messageRow.setIsDeleted(true); cachedInboxMessageRows.remove(messageRow.getMessageNumber()); cachedSortedInboxMessageNumbers.remove(messageRow.getMessageNumber()); cachedSortedInboxMessageRows.remove(messageRow); } }
Issue #28; Fixing cached invalidation issue when forcing reload in Pop3SessionManager.
src/net/xytra/wobmail/manager/Pop3MailSession.java
Issue #28; Fixing cached invalidation issue when forcing reload in Pop3SessionManager.
Java
bsd-3-clause
a0b0d70929793eb61d2d312e8539b51bb709de48
0
NighatYasmin/RESOLVE,mikekab/RESOLVE,mikekab/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE,NighatYasmin/RESOLVE,yushan87/RESOLVE,ClemsonRSRG/RESOLVE,NighatYasmin/RESOLVE,ClemsonRSRG/RESOLVE,yushan87/RESOLVE
/** * VCGenerator.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.ResolveCompiler; import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.init.CompileEnvironment; import edu.clemson.cs.r2jt.misc.SourceErrorException; import edu.clemson.cs.r2jt.rewriteprover.VC; import edu.clemson.cs.r2jt.treewalk.TreeWalker; import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typeandpopulate.query.EntryTypeQuery; import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery; import edu.clemson.cs.r2jt.typereasoning.TypeGraph; import edu.clemson.cs.r2jt.misc.Flag; import edu.clemson.cs.r2jt.misc.FlagDependencies; import edu.clemson.cs.r2jt.vcgeneration.treewalkers.NestedFuncWalker; import java.io.File; import java.util.*; import java.util.List; /** * TODO: Write a description of this module */ public class VCGenerator extends TreeWalkerVisitor { // =========================================================== // Global Variables // =========================================================== // Symbol table related items private final MathSymbolTableBuilder mySymbolTable; private final TypeGraph myTypeGraph; private final MTType BOOLEAN; private final MTType MTYPE; private MTType Z; private ModuleScope myCurrentModuleScope; // Module level global variables private Exp myGlobalRequiresExp; private Exp myGlobalConstraintExp; // Operation/Procedure level global variables private OperationEntry myCurrentOperationEntry; private OperationProfileEntry myCurrentOperationProfileEntry; private Exp myOperationDecreasingExp; /** * <p>The current assertion we are applying * VC rules to.</p> */ private AssertiveCode myCurrentAssertiveCode; /** * <p>A map of facility instantiated types to a list of formal and actual constraints.</p> */ private final Map<VarExp, FacilityFormalToActuals> myInstantiatedFacilityArgMap; /** * <p>A list that will be built up with <code>AssertiveCode</code> * objects, each representing a VC or group of VCs that must be * satisfied to verify a parsed program.</p> */ private Collection<AssertiveCode> myFinalAssertiveCodeList; /** * <p>A stack that is used to keep track of the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<AssertiveCode> myIncAssertiveCodeStack; /** * <p>A stack that is used to keep track of the information that we * haven't printed for the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<String> myIncAssertiveCodeStackInfo; /** * <p>The current compile environment used throughout * the compiler.</p> */ private CompileEnvironment myInstanceEnvironment; /** * <p>A map from representation types to their constraints.</p> */ private final Map<VarExp, Exp> myRepresentationConstraintMap; /** * <p>A map from representation types to their conventions.</p> */ private final Map<VarExp, Exp> myRepresentationConventionsMap; /** * <p>A map from representation types to their correspondence.</p> */ private final Map<VarExp, Exp> myRepresentationCorrespondenceMap; /** * <p>This object creates the different VC outputs.</p> */ private OutputVCs myOutputGenerator; /** * <p>This string buffer holds all the steps * the VC generator takes to generate VCs.</p> */ private StringBuffer myVCBuffer; // =========================================================== // Flag Strings // =========================================================== private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; private static final String FLAG_DESC_ATTPVCS_VC = "Generate Performance VCs"; // =========================================================== // Flags // =========================================================== public static final Flag FLAG_ALTVERIFY_VC = new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); public static final Flag FLAG_ALTPVCS_VC = new Flag(FLAG_ALTSECTION_NAME, "PVCs", FLAG_DESC_ATTPVCS_VC); public static final void setUpFlags() { FlagDependencies.addImplies(FLAG_ALTPVCS_VC, FLAG_ALTVERIFY_VC); } // =========================================================== // Constructors // =========================================================== public VCGenerator(ScopeRepository table, final CompileEnvironment env) { // Symbol table items mySymbolTable = (MathSymbolTableBuilder) table; myTypeGraph = mySymbolTable.getTypeGraph(); BOOLEAN = myTypeGraph.BOOLEAN; MTYPE = myTypeGraph.CLS; Z = null; // Current items myCurrentModuleScope = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; myOperationDecreasingExp = null; // Instance Environment myInstanceEnvironment = env; // VCs + Debugging String myCurrentAssertiveCode = null; myFinalAssertiveCodeList = new LinkedList<AssertiveCode>(); myIncAssertiveCodeStack = new Stack<AssertiveCode>(); myIncAssertiveCodeStackInfo = new Stack<String>(); myInstantiatedFacilityArgMap = new HashMap<VarExp, FacilityFormalToActuals>(); myRepresentationConstraintMap = new HashMap<VarExp, Exp>(); myRepresentationConventionsMap = new HashMap<VarExp, Exp>(); myRepresentationCorrespondenceMap = new HashMap<VarExp, Exp>(); myOutputGenerator = null; myVCBuffer = new StringBuffer(); } // =========================================================== // Visitor Methods // =========================================================== // ----------------------------------------------------------- // ConceptBodyModuleDec // ----------------------------------------------------------- @Override public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Concept Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Obtain the global type constraints from the module parameters Exp typeConstraints = getModuleTypeConstraint(dec.getLocation(), dec.getParameters()); if (!typeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = typeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(typeConstraints, myGlobalConstraintExp); } } // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); try { // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global type constraints from the Concept module parameters Exp conceptTypeConstraints = getModuleTypeConstraint(conceptModuleDec.getLocation(), conceptModuleDec.getParameters()); if (!conceptTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = conceptTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(conceptTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getConceptName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getConceptName().getLocation()); } } // ----------------------------------------------------------- // EnhancementBodyModuleDec // ----------------------------------------------------------- @Override public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Enhancement Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Enhancement Name:\t"); myVCBuffer.append(dec.getEnhancementName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Obtain the global type constraints from the module parameters Exp typeConstraints = getModuleTypeConstraint(dec.getLocation(), dec.getParameters()); if (!typeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = typeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(typeConstraints, myGlobalConstraintExp); } } // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); try { // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global type constraints from the Concept module parameters Exp conceptTypeConstraints = getModuleTypeConstraint(conceptModuleDec.getLocation(), conceptModuleDec.getParameters()); if (!conceptTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = conceptTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(conceptTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getConceptName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getConceptName().getLocation()); } try { // Obtain the global requires clause from the Enhancement EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getEnhancementName() .getName())).getDefiningElement(); Exp enhancementRequires = getRequiresClause(enhancementModuleDec.getLocation(), enhancementModuleDec); if (!enhancementRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = enhancementRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, enhancementRequires); } } // Obtain the global type constraints from the Concept module parameters Exp enhancementTypeConstraints = getModuleTypeConstraint(enhancementModuleDec.getLocation(), enhancementModuleDec.getParameters()); if (!enhancementTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = enhancementTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct( enhancementTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getEnhancementName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getEnhancementName().getLocation()); } } // ----------------------------------------------------------- // FacilityDec // ----------------------------------------------------------- @Override public void postFacilityDec(FacilityDec dec) { // Applies the facility declaration rule. // Since this is a local facility, we will need to add // it to our incomplete assertive code stack. applyFacilityDeclRule(dec, true); // Loop through assertive code stack loopAssertiveCodeStack(); } // ----------------------------------------------------------- // FacilityModuleDec // ----------------------------------------------------------- @Override public void preFacilityModuleDec(FacilityModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Facility Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); } // ----------------------------------------------------------- // FacilityOperationDec // ----------------------------------------------------------- @Override public void preFacilityOperationDec(FacilityOperationDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postFacilityOperationDec(FacilityOperationDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation Location loc = dec.getLocation(); String name = dec.getName().getName(); OperationDec opDec = new OperationDec(dec.getName(), dec.getParameters(), dec .getReturnTy(), dec.getStateVars(), dec.getRequires(), dec.getEnsures()); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, dec), loc, myCurrentAssertiveCode, opDec, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, dec), loc, opDec, isLocal); List<Statement> statementList = dec.getStatements(); List<ParameterVarDec> parameterVarList = dec.getParameters(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, parameterVarList, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // ModuleDec // ----------------------------------------------------------- @Override public void preModuleDec(ModuleDec dec) { // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // Apply the facility declaration rule to imported facility declarations. List<SymbolTableEntry> results = myCurrentModuleScope .query(new EntryTypeQuery<SymbolTableEntry>( FacilityEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE)); for (SymbolTableEntry s : results) { if (s.getSourceModuleIdentifier().compareTo( myCurrentModuleScope.getModuleIdentifier()) != 0) { // Do all the facility declaration logic, but don't add this // to our incomplete assertive code stack. We shouldn't need to // verify facility declarations that are imported. FacilityDec facDec = (FacilityDec) s.toFacilityEntry(dec.getLocation()) .getDefiningElement(); applyFacilityDeclRule(facDec, false); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postModuleDec(ModuleDec dec) { // Create the output generator and finalize output myOutputGenerator = new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, myVCBuffer); // Check if it is generating VCs for WebIDE or not. if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { myOutputGenerator.outputToJSON(); } else { // Print to file if we are in debug mode // TODO: Add debug flag here String filename; if (myInstanceEnvironment.getOutputFilename() != null) { filename = myInstanceEnvironment.getOutputFilename(); } else { filename = createVCFileName(); } myOutputGenerator.outputToFile(filename); } // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // ProcedureDec // ----------------------------------------------------------- @Override public void preProcedureDec(ProcedureDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postProcedureDec(ProcedureDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation OperationDec opDec = (OperationDec) myCurrentOperationEntry.getDefiningElement(); Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, opDec), loc, myCurrentAssertiveCode, opDec, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, opDec), loc, opDec, isLocal); List<Statement> statementList = dec.getStatements(); List<ParameterVarDec> parameterVarList = dec.getParameters(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, BOOLEAN); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, parameterVarList, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // RepresentationDec // ----------------------------------------------------------- @Override public void postRepresentationDec(RepresentationDec dec) { // Applies the initialization rule applyInitializationRule(dec); // Applies the correspondence rule applyCorrespondenceRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Prover Mode // ----------------------------------------------------------- /** * <p>The set of immmutable VCs that the in house provers can use.</p> * * @return VCs to be proved. */ public List<VC> proverOutput() { return myOutputGenerator.getProverOutput(); } // =========================================================== // Private Methods // =========================================================== /** * <p>Loop through the list of <code>VarDec</code>, search * for their corresponding <code>ProgramVariableEntry</code> * and add the result to the list of free variables.</p> * * @param variableList List of the all variables as * <code>VarDec</code>. */ private void addVarDecsAsFreeVars(List<VarDec> variableList) { // Loop through the variable list for (VarDec v : variableList) { myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(v .getLocation(), null, v.getName(), v.getTy() .getMathTypeValue(), null)); } } /** * <p>Converts each actual programming expression into their mathematical * counterparts. It is possible that the passed in programming expression * contains nested function calls, therefore we will need to obtain all the * requires clauses from the different calls and add it as a confirm statement * in our current assertive code.</p> * * @param assertiveCode Current assertive code. * @param actualParams The list of actual parameter arguments. * * @return A list containing the newly created mathematical expression. */ private List<Exp> createModuleActualArgExpList(AssertiveCode assertiveCode, List<ModuleArgumentItem> actualParams) { List<Exp> retExpList = new ArrayList<Exp>(); for (ModuleArgumentItem item : actualParams) { // Obtain the math type for the module argument item MTType type; if (item.getProgramTypeValue() != null) { type = item.getProgramTypeValue().toMath(); } else { type = item.getMathType(); } // Convert the module argument items into math expressions Exp expToUse; if (item.getName() != null) { expToUse = Utilities.createVarExp(item.getLocation(), item .getQualifier(), item.getName(), type, null); } else { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. ProgramExp p = item.getEvalExp(); if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(null, null, mySymbolTable, myCurrentModuleScope, assertiveCode, myInstantiatedFacilityArgMap); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { assertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Use the modified ensures clause as the new expression we want // to replace. expToUse = nfw.getEnsuresClause(); } // For all other types of arguments, simply convert it to a // math expression. else { expToUse = Utilities.convertExp(p, myCurrentModuleScope); } } // Add this to our return list retExpList.add(expToUse); } return retExpList; } /** * <p>Converts each module's formal argument into variable expressions. This is only * possible if the argument is of type <code>ConstantParamDec</code>. All other types * are simply ignored and has mapped value of <code>null</code>.</p> * * @param formalParams The formal parameter list for a <code>ModuleDec</code>. * * @return A list containing the newly created variable expression. */ private List<Exp> createModuleFormalArgExpList( List<ModuleParameterDec> formalParams) { List<Exp> retExpList = new ArrayList<Exp>(); // Create a variable expression for each of the module arguments // and put it in our map. for (ModuleParameterDec dec : formalParams) { Dec wrappedDec = dec.getWrappedDec(); // Only do this for constant parameter and operation declarations // We don't really care about type declarations or definitions. Exp newExp; if (wrappedDec instanceof ConstantParamDec || wrappedDec instanceof ConceptTypeParamDec) { newExp = Utilities.createVarExp(wrappedDec.getLocation(), null, wrappedDec.getName(), wrappedDec.getMathType(), null); } else if (wrappedDec instanceof OperationDec) { OperationDec opDec = (OperationDec) wrappedDec; newExp = Utilities.createVarExp(wrappedDec.getLocation(), null, opDec.getName(), dec.getMathType(), null); } else { newExp = null; } // Store the result retExpList.add(newExp); } return retExpList; } /** * <p>Creates the name of the output file.</p> * * @return Name of the file */ private String createVCFileName() { File file = myInstanceEnvironment.getTargetFile(); ModuleID cid = myInstanceEnvironment.getModuleID(file); file = myInstanceEnvironment.getFile(cid); String filename = file.toString(); int temp = filename.indexOf("."); String tempfile = filename.substring(0, temp); String mainFileName; mainFileName = tempfile + ".asrt_new"; return mainFileName; } /** * <p>This is a helper method that checks to see if the given assume expression * can be used to prove our confirm expression. This is done by finding the * intersection between the set of symbols in the assume expression and * the set of symbols in the confirm expression.</p> * * <p>If the assume expressions are part of a stipulate assume clause, * then we keep all the assume expressions no matter what.</p> * * <p>If it is not a stipulate assume clause, we loop though keep looping through * all the assume expressions until we can't form another implies.</p> * * @param confirmExp The current confirm expression. * @param remAssumeExpList The list of remaining assume expressions. * @param isStipulate Whether or not the assume expression is an stipulate assume expression. * * @return The modified confirm expression. */ private Exp formImplies(Exp confirmExp, List<Exp> remAssumeExpList, boolean isStipulate) { // If it is stipulate clause, keep it no matter what if (isStipulate) { for (Exp assumeExp : remAssumeExpList) { confirmExp = myTypeGraph.formImplies(Exp.copy(assumeExp), Exp .copy(confirmExp)); } } else { boolean checkList = false; if (remAssumeExpList.size() > 0) { checkList = true; } // Loop until we no longer add more expressions or we have added all // expressions in the remaining assume expression list. while (checkList) { List<Exp> tmpExpList = new ArrayList<Exp>(); boolean formedImplies = false; for (Exp assumeExp : remAssumeExpList) { // Create a new implies expression if there are common symbols // in the assume and in the confirm. (Parsimonious step) Set<String> intersection = Utilities.getSymbols(confirmExp); intersection.retainAll(Utilities.getSymbols(assumeExp)); if (!intersection.isEmpty()) { // Don't form implies if we have "Assume true" if (!assumeExp.isLiteralTrue()) { confirmExp = myTypeGraph.formImplies( Exp.copy(assumeExp), Exp .copy(confirmExp)); formedImplies = true; } } else { // Form implies if we have "Assume false" if (assumeExp.isLiteralFalse()) { confirmExp = myTypeGraph.formImplies( Exp.copy(assumeExp), Exp .copy(confirmExp)); formedImplies = true; } else { tmpExpList.add(assumeExp); } } } remAssumeExpList = tmpExpList; if (remAssumeExpList.size() > 0) { // Check to see if we formed an implication if (formedImplies) { // Loop again to see if we can form any more implications checkList = true; } else { // If no implications are formed, then none of the remaining // expressions will be helpful. checkList = false; } } else { // Since we are done with all assume expressions, we can quit // out of the loop. checkList = false; } } } return confirmExp; } /** * <p>A helper method to deal with operations as parameters.</p> * * @param loc Location of some facility declaration. * @param assertiveCode The current assertive code. * @param formalParams The formal parameters. * @param actualParams The actual parameters. * @param conceptFormalParamExp The concept formal parameter expression. * @param conceptActualParamExp The concept actual parameter expression. * @param conceptRealizFormalParamExp The concept realization formal parameter expression. * @param conceptRealizActualParamExp The concept realization actual parameter expression. * @param enhancementFormalParamExp The enhancement formal parameter expression. * @param enhancementActualParamExp The enhancement actual parameter expression. * @param enhancementRealizFormalParamExp The enhancement realization formal parameter expression. * @param enhancementRealizActualParamExp The enhancement realization actual parameter expression. * @return */ private AssertiveCode facilityDeclOperationParamHelper(Location loc, AssertiveCode assertiveCode, List<ModuleParameterDec> formalParams, List<ModuleArgumentItem> actualParams, List<Exp> conceptFormalParamExp, List<Exp> conceptActualParamExp, List<Exp> conceptRealizFormalParamExp, List<Exp> conceptRealizActualParamExp, List<Exp> enhancementFormalParamExp, List<Exp> enhancementActualParamExp, List<Exp> enhancementRealizFormalParamExp, List<Exp> enhancementRealizActualParamExp) { AssertiveCode copyAssertiveCode = new AssertiveCode(assertiveCode); Iterator<ModuleParameterDec> realizParameterIt = formalParams.iterator(); Iterator<ModuleArgumentItem> realizArgumentItemIt = actualParams.iterator(); while (realizParameterIt.hasNext() && realizArgumentItemIt.hasNext()) { ModuleParameterDec moduleParameterDec = realizParameterIt.next(); ModuleArgumentItem moduleArgumentItem = realizArgumentItemIt.next(); if (moduleParameterDec.getWrappedDec() instanceof OperationDec) { // Formal operation OperationDec formalOperationDec = (OperationDec) moduleParameterDec.getWrappedDec(); boolean isFormalOpDecLocal = Utilities.isLocationOperation(formalOperationDec .getName().getName(), myCurrentModuleScope); Exp formalOperationRequires = getRequiresClause(formalOperationDec.getLocation(), formalOperationDec); Exp formalOperationEnsures = getEnsuresClause(formalOperationDec.getLocation(), formalOperationDec); // Construct a list of formal parameters as expressions // for substitution purposes. List<ParameterVarDec> formalParameterVarDecs = formalOperationDec.getParameters(); List<Exp> formalParamAsExp = new ArrayList<Exp>(); for (ParameterVarDec varDec : formalParameterVarDecs) { Ty varDecTy = varDec.getTy(); // varDec as VarExp VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), varDecTy.getMathType(), null); formalParamAsExp.add(varDecExp); // #varDec as OldExp OldExp oldVarDecExp = new OldExp(varDec.getLocation(), Exp .copy(varDecExp)); formalParamAsExp.add(oldVarDecExp); } if (formalOperationDec.getReturnTy() != null) { Ty varDecTy = formalOperationDec.getReturnTy(); formalParamAsExp.add(Utilities.createVarExp(varDecTy .getLocation(), null, formalOperationDec.getName(), varDecTy.getMathType(), null)); } // Locate the corresponding actual operation OperationDec actualOperationDec = null; List<Exp> actualParamAsExp = new ArrayList<Exp>(); try { OperationEntry op = myCurrentModuleScope .queryForOne( new NameQuery( moduleArgumentItem .getQualifier(), moduleArgumentItem .getName(), MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE, true)) .toOperationEntry(loc); if (op.getDefiningElement() instanceof OperationDec) { actualOperationDec = (OperationDec) op.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) op.getDefiningElement(); actualOperationDec = new OperationDec(fOpDec.getName(), fOpDec .getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec .getEnsures()); } // Construct a list of actual parameters as expressions // for substitution purposes. List<ParameterVarDec> parameterVarDecs = actualOperationDec.getParameters(); for (ParameterVarDec varDec : parameterVarDecs) { Ty varDecTy = varDec.getTy(); // varDec as VarExp VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), varDecTy .getMathType(), null); actualParamAsExp.add(varDecExp); // #varDec as OldExp OldExp oldVarDecExp = new OldExp(varDec.getLocation(), Exp .copy(varDecExp)); actualParamAsExp.add(oldVarDecExp); } // TODO: Move this to the populator opAsParameterSanityCheck(moduleArgumentItem.getLocation(), formalParameterVarDecs, parameterVarDecs); // Add any return types as something we need to replace if (actualOperationDec.getReturnTy() != null) { Ty varDecTy = actualOperationDec.getReturnTy(); actualParamAsExp.add(Utilities.createVarExp(varDecTy .getLocation(), null, actualOperationDec .getName(), varDecTy.getMathType(), null)); } } catch (NoSuchSymbolException nsse) { Utilities.noSuchSymbol(moduleArgumentItem.getQualifier(), moduleArgumentItem.getName().getName(), loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate operation is //created throw new RuntimeException(dse); } Exp actualOperationRequires = getRequiresClause(moduleArgumentItem.getLocation(), actualOperationDec); Exp actualOperationEnsures = getEnsuresClause(moduleArgumentItem.getLocation(), actualOperationDec); // Facility Decl Rule (Operations as Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP Exp formalRequires = modifyRequiresClause(formalOperationRequires, moduleParameterDec.getLocation(), copyAssertiveCode, formalOperationDec, isFormalOpDecLocal); formalRequires = replaceFacilityDeclarationVariables(formalRequires, conceptFormalParamExp, conceptActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, conceptRealizFormalParamExp, conceptRealizActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, enhancementFormalParamExp, enhancementActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, enhancementRealizFormalParamExp, enhancementRealizActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, formalParamAsExp, actualParamAsExp); if (!actualOperationRequires .equals(myTypeGraph.getTrueVarExp())) { Location newLoc = (Location) actualOperationRequires.getLocation() .clone(); newLoc.setDetails("Requires Clause of " + formalOperationDec.getName().getName() + " implies the Requires Clause of " + actualOperationDec.getName().getName() + " in Facility Instantiation Rule"); Exp newConfirmExp; if (!formalRequires.equals(myTypeGraph.getTrueVarExp())) { newConfirmExp = myTypeGraph.formImplies(formalRequires, actualOperationRequires); } else { newConfirmExp = actualOperationRequires; } Utilities.setLocation(newConfirmExp, newLoc); copyAssertiveCode.addConfirm(newLoc, newConfirmExp, false); } // Facility Decl Rule (Operations as Parameters): // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] Exp formalEnsures = modifyEnsuresClause(formalOperationEnsures, moduleParameterDec.getLocation(), formalOperationDec, isFormalOpDecLocal); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, conceptFormalParamExp, conceptActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, conceptRealizFormalParamExp, conceptRealizActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, enhancementFormalParamExp, enhancementActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, enhancementRealizFormalParamExp, enhancementRealizActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, formalParamAsExp, actualParamAsExp); if (!formalEnsures.equals(myTypeGraph.getTrueVarExp())) { Location newLoc = (Location) actualOperationEnsures.getLocation() .clone(); newLoc.setDetails("Ensures Clause of " + actualOperationDec.getName().getName() + " implies the Ensures Clause of " + formalOperationDec.getName().getName() + " in Facility Instantiation Rule"); Exp newConfirmExp; if (!actualOperationEnsures.equals(myTypeGraph .getTrueVarExp())) { newConfirmExp = myTypeGraph.formImplies(actualOperationEnsures, formalEnsures); } else { newConfirmExp = formalEnsures; } Utilities.setLocation(newConfirmExp, newLoc); copyAssertiveCode.addConfirm(newLoc, newConfirmExp, false); } } } return copyAssertiveCode; } /** * <p>This method iterates through each of the assume expressions. * If the expression is a replaceable equals expression, it will substitute * all instances of the expression in the rest of the assume expression * list and in the confirm expression list.</p> * * <p>When it is not a replaceable expression, we apply a step to generate * parsimonious VCs.</p> * * @param confirmExpList The list of conjunct confirm expressions. * @param assumeExpList The list of conjunct assume expressions. * @param isStipulate Boolean to indicate whether it is a stipulate assume * clause and we need to keep the assume statement. * * @return The modified confirm statement expression in <code>Exp/code> form. */ private Exp formParsimoniousVC(List<Exp> confirmExpList, List<Exp> assumeExpList, boolean isStipulate) { // Loop through each confirm expression for (int i = 0; i < confirmExpList.size(); i++) { Exp currentConfirmExp = confirmExpList.get(i); // Make a deep copy of the assume expression list List<Exp> assumeExpCopyList = new ArrayList<Exp>(); for (Exp assumeExp : assumeExpList) { assumeExpCopyList.add(Exp.copy(assumeExp)); } // Stores the remaining assume expressions // we have not substituted. Note that if the expression // is part of a stipulate assume statement, we keep // the assume no matter what. List<Exp> remAssumeExpList = new ArrayList<Exp>(); // Loop through each assume expression for (int j = 0; j < assumeExpCopyList.size(); j++) { Exp currentAssumeExp = assumeExpCopyList.get(j); Exp tmp; boolean hasVerificationVar = false; boolean isConceptualVar = false; boolean doneReplacement = false; // Attempts to simplify equality expressions if (currentAssumeExp instanceof EqualsExp && ((EqualsExp) currentAssumeExp).getOperator() == EqualsExp.EQUAL) { EqualsExp equalsExp = (EqualsExp) currentAssumeExp; boolean isLeftReplaceable = Utilities.containsReplaceableExp(equalsExp .getLeft()); boolean isRightReplaceable = Utilities.containsReplaceableExp(equalsExp .getRight()); // Check to see if we have P_val or Cum_Dur if (equalsExp.getLeft() instanceof VarExp) { if (((VarExp) equalsExp.getLeft()).getName().getName() .matches("\\?*P_val") || ((VarExp) equalsExp.getLeft()).getName() .getName().matches("\\?*Cum_Dur")) { hasVerificationVar = true; } } // Check to see if we have Conc.[expression] else if (equalsExp.getLeft() instanceof DotExp) { DotExp tempLeft = (DotExp) equalsExp.getLeft(); isConceptualVar = tempLeft.containsVar("Conc", false); } // Check if both the left and right are replaceable if (isLeftReplaceable && isRightReplaceable) { // Only check for verification variable on the left // hand side. If that is the case, we know the // right hand side is the only one that makes sense // in the current context, therefore we do the // substitution. if (hasVerificationVar || isConceptualVar) { tmp = Utilities.replace(currentConfirmExp, equalsExp.getLeft(), equalsExp .getRight()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { // Replace all instances of the left side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList .get(k), equalsExp .getLeft(), equalsExp .getRight()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the left side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList .size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList .get(k), equalsExp .getLeft(), equalsExp .getRight()); assumeExpCopyList.set(k, newAssumeExp); } doneReplacement = true; } } else { // Don't do any substitutions, we don't know // which makes sense in the current context. tmp = currentConfirmExp; } } // Check if left hand side is replaceable else if (isLeftReplaceable) { // Create a temp expression where left is replaced with the right tmp = Utilities.replace(currentConfirmExp, equalsExp .getLeft(), equalsExp.getRight()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { doneReplacement = true; } // Replace all instances of the left side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList.get(k), equalsExp.getLeft(), equalsExp .getRight()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the left side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList.size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList.get(k), equalsExp.getLeft(), equalsExp .getRight()); assumeExpCopyList.set(k, newAssumeExp); } } // Only right hand side is replaceable else if (isRightReplaceable) { // Create a temp expression where right is replaced with the left tmp = Utilities.replace(currentConfirmExp, equalsExp .getRight(), equalsExp.getLeft()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { doneReplacement = true; } // Replace all instances of the right side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList.get(k), equalsExp.getRight(), equalsExp .getLeft()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the right side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList.size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList.get(k), equalsExp.getRight(), equalsExp .getLeft()); assumeExpCopyList.set(k, newAssumeExp); } } // Both sides are not replaceable else { tmp = currentConfirmExp; } } else { tmp = currentConfirmExp; } // Check to see if this is a stipulate assume clause // If yes, we keep a copy of the current // assume expression. if (isStipulate) { remAssumeExpList.add(Exp.copy(currentAssumeExp)); } else { // Update the current confirm expression // if we did a replacement. if (doneReplacement) { currentConfirmExp = tmp; } else { // Check to see if this a verification // variable. If yes, we don't keep this assume. // Otherwise, we need to store this for the // step that generates the parsimonious vcs. if (!hasVerificationVar) { remAssumeExpList.add(Exp.copy(currentAssumeExp)); } } } } // Use the remaining assume expression list // Create a new implies expression if there are common symbols // in the assume and in the confirm. (Parsimonious step) Exp newConfirmExp = formImplies(currentConfirmExp, remAssumeExpList, isStipulate); confirmExpList.set(i, newConfirmExp); } // Form the return confirm statement Exp retExp = myTypeGraph.getTrueVarExp(); for (Exp e : confirmExpList) { if (retExp.isLiteralTrue()) { retExp = e; } else { retExp = myTypeGraph.formConjunct(retExp, e); } } return retExp; } /** * <p>Returns all the constraint clauses combined together for the * for the current <code>ModuleDec</code>.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param imports The list of imported modules. * * @return The constraint clause <code>Exp</code>. */ private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) { Exp retExp = null; List<String> importedConceptName = new LinkedList<String>(); // Loop for (ModuleIdentifier mi : imports) { try { ModuleDec dec = mySymbolTable.getModuleScope(mi).getDefiningElement(); List<Exp> contraintExpList = null; // Handling for facility imports if (dec instanceof ShortFacilityModuleDec) { FacilityDec facDec = ((ShortFacilityModuleDec) dec).getDec(); dec = mySymbolTable.getModuleScope( new ModuleIdentifier(facDec .getConceptName().getName())) .getDefiningElement(); } if (dec instanceof ConceptModuleDec && !importedConceptName.contains(dec.getName() .getName())) { contraintExpList = ((ConceptModuleDec) dec).getConstraints(); // Copy all the constraints for (Exp e : contraintExpList) { // Deep copy and set the location detail Exp constraint = Exp.copy(e); if (constraint.getLocation() != null) { Location theLoc = constraint.getLocation(); theLoc.setDetails("Constraint of Module: " + dec.getName()); Utilities.setLocation(constraint, theLoc); } // Form conjunct if needed. if (retExp == null) { retExp = Exp.copy(e); } else { retExp = myTypeGraph.formConjunct(retExp, Exp .copy(e)); } } // Avoid importing constraints for the same concept twice importedConceptName.add(dec.getName().getName()); } } catch (NoSuchSymbolException e) { System.err.println("Module " + mi.toString() + " does not exist or is not in scope."); Utilities.noSuchModule(loc); } } return retExp; } /** * <p>Returns the ensures clause for the current <code>Dec</code>.</p> * * @param location The location of the ensures clause. * @param dec The corresponding <code>Dec</code>. * * @return The ensures clause <code>Exp</code>. */ private Exp getEnsuresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp ensures = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { ensures = ((FacilityOperationDec) dec).getEnsures(); } else if (dec instanceof OperationDec) { ensures = ((OperationDec) dec).getEnsures(); } // Deep copy and fill in the details of this location if (ensures != null) { retExp = Exp.copy(ensures); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Ensures Clause of " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Returns all the constraint clauses combined together for the * for the list of module parameters.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param moduleParameterDecs The list of parameter for this module. * * @return The constraint clause <code>Exp</code>. */ private Exp getModuleTypeConstraint(Location loc, List<ModuleParameterDec> moduleParameterDecs) { Exp retVal = myTypeGraph.getTrueVarExp(); for (ModuleParameterDec m : moduleParameterDecs) { Dec wrappedDec = m.getWrappedDec(); if (wrappedDec instanceof ConstantParamDec) { ConstantParamDec dec = (ConstantParamDec) wrappedDec; ProgramTypeEntry typeEntry; if (dec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) dec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(dec.getLocation(), null, dec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type.getExemplar(), typeEntry .getModelType(), null); // Deep copy the original constraint clause Exp constraint = Exp.copy(type.getConstraint()); constraint = Utilities.replace(constraint, exemplar, varDecExp); // Conjunct to our other constraints (if any) if (!constraint.isLiteralTrue()) { if (retVal.isLiteralTrue()) { retVal = constraint; } else { retVal = myTypeGraph.formConjunct(retVal, constraint); } } } } else { Utilities.tyNotHandled(dec.getTy(), loc); } } } return retVal; } /** * <p>Returns the requires clause for the current <code>Dec</code>.</p> * * @param location The location of the requires clause. * @param dec The corresponding <code>Dec</code>. * * @return The requires clause <code>Exp</code>. */ private Exp getRequiresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp requires = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { requires = ((FacilityOperationDec) dec).getRequires(); } else if (dec instanceof OperationDec) { requires = ((OperationDec) dec).getRequires(); } else if (dec instanceof ConceptModuleDec) { requires = ((ConceptModuleDec) dec).getRequirement(); } else if (dec instanceof ConceptBodyModuleDec) { requires = ((ConceptBodyModuleDec) dec).getRequires(); } else if (dec instanceof EnhancementModuleDec) { requires = ((EnhancementModuleDec) dec).getRequirement(); } else if (dec instanceof EnhancementBodyModuleDec) { requires = ((EnhancementBodyModuleDec) dec).getRequires(); } else if (dec instanceof FacilityModuleDec) { requires = ((FacilityModuleDec) dec).getRequirement(); } // Deep copy and fill in the details of this location if (requires != null) { retExp = Exp.copy(requires); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Requires Clause for " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Loop through our stack of incomplete assertive codes.</p> */ private void loopAssertiveCodeStack() { // Loop until our to process assertive code stack is empty while (!myIncAssertiveCodeStack.empty()) { // Set the incoming assertive code as our current assertive // code we are working on. myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Append any information that still needs to be added to our // Debug VC Buffer myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); // Apply proof rules applyRules(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Add it to our list of final assertive codes ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); if (!confirmStmt.getAssertion().isLiteralTrue()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } else { // Only add true if it is a goal we want to show up. if (!confirmStmt.getSimplify()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } } // Set the current assertive code to null myCurrentAssertiveCode = null; } } /** * <p>Modify the argument expression list if we have a * nested function call.</p> * * @param callArgs The original list of arguments. * * @return The modified list of arguments. */ private List<Exp> modifyArgumentList(List<ProgramExp> callArgs) { // Find all the replacements that needs to happen to the requires // and ensures clauses List<Exp> replaceArgs = new ArrayList<Exp>(); for (ProgramExp p : callArgs) { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(myCurrentOperationEntry, myOperationDecreasingExp, mySymbolTable, myCurrentModuleScope, myCurrentAssertiveCode, myInstantiatedFacilityArgMap); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { myCurrentAssertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Add the modified ensures clause as the new expression we want // to replace in the CallStmt's ensures clause. replaceArgs.add(nfw.getEnsuresClause()); } // For all other types of arguments, simply add it to the list to be replaced else { replaceArgs.add(p); } } return replaceArgs; } /** * <p>Modifies the ensures clause based on the parameter mode.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation * @param opName The name of the operation. * @param parameterVarDecList The list of parameter variables for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, String opName, List<ParameterVarDec> parameterVarDecList, boolean isLocal) { // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); // Exp form of the parameter variable VarExp parameterExp = new VarExp(p.getLocation(), null, p.getName().copy()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Create an old exp (#parameterExp) OldExp oldParameterExp = new OldExp(p.getLocation(), Exp.copy(parameterExp)); oldParameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste .toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Restores mode // TODO: Preserves mode needs to be syntaticlly checked. if (p.getMode() == Mode.RESTORES) { // Set the details for the new location Location restoresLoc; if (ensures != null && ensures.getLocation() != null) { Location enLoc = ensures.getLocation(); restoresLoc = ((Location) enLoc.clone()); } else { restoresLoc = ((Location) opLocation.clone()); restoresLoc.setDetails("Ensures Clause of " + opName); } restoresLoc.setDetails(restoresLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); // Need to ensure here that the everything inside the type family // is restored at the end of the operation. Exp restoresConditionExp = null; if (typeEntry.getModelType() instanceof MTCartesian) { MTCartesian cartesian = (MTCartesian) typeEntry.getModelType(); List<MTType> elementTypes = cartesian.getComponentTypes(); for (int i = 0; i < cartesian.size(); i++) { // Retrieve the information on each cartesian product element PosSymbol name = Utilities.createPosSymbol(cartesian .getTag(i)); MTType type = elementTypes.get(i); // Create a list of segments. The first element should be the original // parameterExp and oldParameterExp and the second element the cartesian product element. edu.clemson.cs.r2jt.collections.List<Exp> segments = new edu.clemson.cs.r2jt.collections.List<Exp>(); edu.clemson.cs.r2jt.collections.List<Exp> oldSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); segments.add(Exp.copy(parameterExp)); oldSegments.add(Exp.copy(oldParameterExp)); segments.add(Utilities.createVarExp( (Location) opLocation.clone(), null, name .copy(), type, null)); oldSegments.add(Utilities.createVarExp( (Location) opLocation.clone(), null, name .copy(), type, null)); // Create the dotted expressions DotExp elementDotExp = Utilities.createDotExp( (Location) opLocation.clone(), segments, type); DotExp oldElementDotExp = Utilities.createDotExp( (Location) opLocation.clone(), oldSegments, type); // Create an equality expression EqualsExp equalsExp = new EqualsExp(opLocation, elementDotExp, EqualsExp.EQUAL, oldElementDotExp); equalsExp.setMathType(BOOLEAN); equalsExp.setLocation((Location) restoresLoc .clone()); // Add this to our final equals expression if (restoresConditionExp == null) { restoresConditionExp = equalsExp; } else { restoresConditionExp = myTypeGraph .formConjunct( restoresConditionExp, equalsExp); } } } else { // Construct an expression using the expression and it's // old expression equivalent. restoresConditionExp = new EqualsExp(opLocation, Exp .copy(parameterExp), EqualsExp.EQUAL, Exp.copy(oldParameterExp)); restoresConditionExp.setMathType(BOOLEAN); restoresConditionExp.setLocation(restoresLoc); } // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, restoresConditionExp); ensures.setLocation(newEnsuresLoc); } // Make new expression the ensures clause else { ensures = restoresConditionExp; } } // Clears mode else if (p.getMode() == Mode.CLEARS) { Exp init; if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form VarExp exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // Deep copy the original initialization ensures and the constraint init = Exp.copy(type.getInitialization().getEnsures()); // Replace the formal with the actual init = Utilities.replace(init, exemplar, parameterExp); // Set the details for the new location Location initLoc; if (ensures != null && ensures.getLocation() != null) { Location reqLoc = ensures.getLocation(); initLoc = ((Location) reqLoc.clone()); } else { initLoc = ((Location) opLocation.clone()); initLoc.setDetails("Ensures Clause of " + opName); } initLoc.setDetails(initLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); Utilities.setLocation(init, initLoc); } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = p.getLocation(); // Create an is_initial dot expression init = Utilities.createInitExp(new VarDec(p.getName(), p.getTy()), MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + p.getName().getName()); Utilities.setLocation(init, loc); } } // Create an AND infix expression with the ensures clause if (ensures != null) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, init); ensures.setLocation(newEnsuresLoc); } // Make initialization expression the ensures clause else { ensures = init; } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { Exp conceptualExp = Utilities.createConcVarExp(opLocation, parameterExp, parameterExp.getMathType(), BOOLEAN); OldExp oldConceptualExp = new OldExp(opLocation, Exp.copy(conceptualExp)); ensures = Utilities.replace(ensures, parameterExp, conceptualExp); ensures = Utilities.replace(ensures, oldParameterExp, oldConceptualExp); } } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual(opLocation, ensures, parameterVarDecList, myInstantiatedFacilityArgMap, myCurrentModuleScope); return ensures; } /** * <p>Returns the ensures clause.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation. * @param operationDec The <code>OperationDec</code> that is modifying the ensures clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresClause(Exp ensures, Location opLocation, OperationDec operationDec, boolean isLocal) { // Modifies the existing ensures clause based on // the parameter modes. ensures = modifyEnsuresByParameter(ensures, opLocation, operationDec .getName().getName(), operationDec.getParameters(), isLocal); return ensures; } /** * <p>Modifies the requires clause based on .</p> * * @param requires The <code>Exp</code> containing the requires clause. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByGlobalMode(Exp requires) { return requires; } /** * <p>Modifies the requires clause based on the parameter mode.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param assertiveCode The current assertive code we are currently generating. * @param operationDec The <code>OperationDec</code> that is modifying the requires clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByParameter(Exp requires, Location opLocation, AssertiveCode assertiveCode, OperationDec operationDec, boolean isLocal) { // Obtain the list of parameters List<ParameterVarDec> parameterVarDecList = operationDec.getParameters(); // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { ProgramTypeEntry typeEntry; // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); PTType ptType = pNameTy.getProgramTypeValue(); // Only deal with actual types and don't deal // with entry types passed in to the concept realization if (!(ptType instanceof PTGeneric)) { // Convert p to a VarExp VarExp parameterExp = new VarExp(null, null, p.getName()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST VarExp exemplar = null; Exp constraint = null; if (typeEntry.getDefiningElement() instanceof TypeDec) { TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // If we have a type representation, then there are no initialization // or constraint clauses. if (ste instanceof ProgramTypeEntry) { // Deep copy the constraint if (type.getConstraint() != null) { constraint = Exp.copy(type.getConstraint()); } } } // Other than the replaces mode, constraints for the // other parameter modes needs to be added // to the requires clause as conjuncts. if (p.getMode() != Mode.REPLACES) { if (constraint != null && !constraint.equals(myTypeGraph .getTrueVarExp())) { // Replace the formal with the actual if (exemplar != null) { constraint = Utilities.replace(constraint, exemplar, parameterExp); } // Set the details for the new location if (constraint.getLocation() != null) { Location constLoc; if (requires != null && requires.getLocation() != null) { Location reqLoc = requires.getLocation(); constLoc = ((Location) reqLoc.clone()); } else { // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry .getName(); } constLoc = ((Location) opLocation.clone()); constLoc.setDetails("Requires Clause of " + operationDec.getName().getName() + details); } constLoc.setDetails(constLoc.getDetails() + " (Constraint from \"" + p.getMode().getModeName() + "\" parameter mode)"); constraint.setLocation(constLoc); } // Create an AND infix expression with the requires clause if (requires != null && !requires.equals(myTypeGraph .getTrueVarExp())) { requires = myTypeGraph.formConjunct(requires, constraint); requires.setLocation((Location) opLocation .clone()); } // Make constraint expression the requires clause else { requires = constraint; } } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { requires = Utilities.replace(requires, parameterExp, Utilities .createConcVarExp(opLocation, parameterExp, parameterExp .getMathType(), BOOLEAN)); requires.setLocation((Location) opLocation.clone()); } // If the type is a type representation, then we need to add // all the type constraints from all the variable declarations // in the type representation. if (ste instanceof RepresentationTypeEntry) { Exp repConstraintExp = null; Set<VarExp> keys = myRepresentationConstraintMap.keySet(); for (VarExp varExp : keys) { if (varExp.getQualifier() == null && varExp.getName().getName().equals( pNameTy.getName().getName())) { if (repConstraintExp == null) { repConstraintExp = myRepresentationConstraintMap .get(varExp); } else { Utilities.ambiguousTy(pNameTy, pNameTy .getLocation()); } } } // Only do the following if the expression is not simply true if (!repConstraintExp.isLiteralTrue()) { // Replace the exemplar with the actual parameter variable expression repConstraintExp = Utilities.replace(repConstraintExp, exemplar, parameterExp); // Add this to our requires clause requires = myTypeGraph.formConjunct(requires, repConstraintExp); requires.setLocation((Location) opLocation.clone()); } } } // Add the current variable to our list of free variables assertiveCode.addFreeVar(Utilities.createVarExp( p.getLocation(), null, p.getName(), pNameTy .getMathTypeValue(), null)); } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(opLocation, requires, parameterVarDecList, myInstantiatedFacilityArgMap, myCurrentModuleScope); return requires; } /** * <p>Modifies the requires clause.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param assertiveCode The current assertive code we are currently generating. * @param operationDec The <code>OperationDec</code> that is modifying the requires clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresClause(Exp requires, Location opLocation, AssertiveCode assertiveCode, OperationDec operationDec, boolean isLocal) { // Modifies the existing requires clause based on // the parameter modes. requires = modifyRequiresByParameter(requires, opLocation, assertiveCode, operationDec, isLocal); // Modifies the existing requires clause based on // the parameter modes. // TODO: Ask Murali what this means requires = modifyRequiresByGlobalMode(requires); return requires; } /** * <p>Basic sanity check for operations as parameters.</p> * * @param loc Location of the actual operation as parameter. * @param formalParams Formal parameters. * @param actualParams Actual parameters. */ private void opAsParameterSanityCheck(Location loc, List<ParameterVarDec> formalParams, List<ParameterVarDec> actualParams) { if (formalParams.size() != actualParams.size()) { throw new SourceErrorException( "Actual operation parameter count " + "does not correspond to the formal operation parameter count." + "\n\tExpected count: " + formalParams.size() + "\n\tFound count: " + actualParams.size(), loc); } Iterator<ParameterVarDec> formalIt = formalParams.iterator(); Iterator<ParameterVarDec> actualIt = actualParams.iterator(); ParameterVarDec currFormalParam, currActualParam; while (formalIt.hasNext()) { currFormalParam = formalIt.next(); currActualParam = actualIt.next(); if (!currActualParam.getMode().getModeName().equals( currFormalParam.getMode().getModeName())) { throw new SourceErrorException( "Operation parameter modes are not the same." + "\n\tExpecting: " + currFormalParam.getMode().getModeName() + " " + currFormalParam.getName() + "\n\tFound: " + currActualParam.getMode().getModeName() + " " + currActualParam.getName(), loc); } } } /** * <p>Replace the formal parameter variables with the actual mathematical * expressions passed in.</p> * * @param exp The expression to be replaced. * @param actualParamList The list of actual parameter variables. * @param formalParamList The list of formal parameter variables. * * @return The modified expression. */ private Exp replaceFacilityDeclarationVariables(Exp exp, List<Exp> formalParamList, List<Exp> actualParamList) { Exp retExp = Exp.copy(exp); if (formalParamList.size() == actualParamList.size()) { // Loop through the argument list for (int i = 0; i < formalParamList.size(); i++) { // Concept variable Exp formalExp = formalParamList.get(i); if (formalExp != null) { // Temporary replacement to avoid formal and actuals being the same Exp newFormalExp; if (formalExp instanceof VarExp) { VarExp formalExpAsVarExp = (VarExp) formalExp; newFormalExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + formalExpAsVarExp.getName()), formalExp.getMathType(), formalExp .getMathTypeValue()); } else { VarExp modifiedInnerVarExp = (VarExp) Exp .copy(((OldExp) formalExp).getExp()); modifiedInnerVarExp.setName(Utilities .createPosSymbol("_" + modifiedInnerVarExp.getName() .getName())); newFormalExp = new OldExp(modifiedInnerVarExp.getLocation(), modifiedInnerVarExp); } retExp = Utilities.replace(retExp, formalExp, newFormalExp); // Actually perform the desired replacement Exp actualExp = actualParamList.get(i); retExp = Utilities.replace(retExp, newFormalExp, actualExp); } } } else { throw new RuntimeException("Size not equal!"); } return retExp; } /** * <p>Replace the formal with the actual variables * inside the ensures clause.</p> * * @param ensures The ensures clause. * @param paramList The list of parameter variables. * @param stateVarList The list of state variables. * @param argList The list of arguments from the operation call. * @param isSimple Check if it is a simple replacement. * * @return The ensures clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualEns(Exp ensures, List<ParameterVarDec> paramList, List<AffectsItem> stateVarList, List<Exp> argList, boolean isSimple) { // Current final confirm Exp newConfirm; // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace state variables in the ensures clause // and create new confirm statements if needed. for (int i = 0; i < stateVarList.size(); i++) { ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); AffectsItem stateVar = stateVarList.get(i); // Only deal with Alters/Reassigns/Replaces/Updates modes if (stateVar.getMode() == Mode.ALTERS || stateVar.getMode() == Mode.REASSIGNS || stateVar.getMode() == Mode.REPLACES || stateVar.getMode() == Mode.UPDATES) { // Obtain the variable from our free variable list Exp globalFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true); if (globalFreeVar != null) { VarExp oldNamesVar = new VarExp(); oldNamesVar.setName(stateVar.getName()); // Create a local free variable if it is not there Exp localFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar .getName(), false); if (localFreeVar == null) { // TODO: Don't have a type for state variables? localFreeVar = new VarExp(null, null, stateVar.getName()); localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); myCurrentAssertiveCode.addFreeVar(localFreeVar); } else { localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); } // Creating "#" expressions and replace these in the // ensures clause. OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); OldExp oldNameOSVar = new OldExp(null, Exp.copy(oldNamesVar)); ensures = Utilities.replace(ensures, oldNamesVar, globalFreeVar); ensures = Utilities.replace(ensures, oldNameOSVar, osVar); // If it is not simple replacement, replace all ensures clauses // with the appropriate expressions. if (!isSimple) { ensures = Utilities.replace(ensures, globalFreeVar, localFreeVar); ensures = Utilities .replace(ensures, osVar, globalFreeVar); newConfirm = Utilities.replace(newConfirm, globalFreeVar, localFreeVar); } // Set newConfirm as our new final confirm statement myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // Error: Why isn't it a free variable. else { Utilities.notInFreeVarList(stateVar.getName(), stateVar .getLocation()); } } } // Replace postcondition variables in the ensures clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); PosSymbol VDName = varDec.getName(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); // VarExp form of the parameter variable VarExp oldExp = new VarExp(null, null, VDName); oldExp.setMathType(exp.getMathType()); oldExp.setMathTypeValue(exp.getMathTypeValue()); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp, myCurrentModuleScope); Exp undqRep = null, quesRep = null; OldExp oSpecVar, oRealVar; String replName = null; // Case #1: ProgramIntegerExp // Case #2: ProgramCharExp // Case #3: ProgramStringExp if (exp instanceof ProgramIntegerExp || exp instanceof ProgramCharExp || exp instanceof ProgramStringExp) { Exp convertExp = Utilities.convertExp(exp, myCurrentModuleScope); if (exp instanceof ProgramIntegerExp) { replName = Integer.toString(((IntegerExp) convertExp) .getValue()); } else if (exp instanceof ProgramCharExp) { replName = Character.toString(((CharExp) convertExp) .getValue()); } else { replName = ((StringExp) convertExp).getValue(); } // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #4: VariableDotExp else if (exp instanceof VariableDotExp) { if (repl instanceof DotExp) { Exp pE = ((DotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<Exp> segList = ((DotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((DotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((DotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((DotExp) quesRep).setSegments(segList); } else if (repl instanceof VariableDotExp) { Exp pE = ((VariableDotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<VariableExp> segList = ((VariableDotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((VariableDotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((VariableDotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((VariableDotExp) quesRep).setSegments(segList); } // Error: Case not handled! else { Utilities.expNotHandled(exp, exp.getLocation()); } } // Case #5: VariableNameExp else if (exp instanceof VariableNameExp) { // Name of repl in string form replName = ((VariableNameExp) exp).getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #6: Result from a nested function call else { // Name of repl in string form replName = varDec.getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // "#" versions of oldExp and repl oSpecVar = new OldExp(null, Exp.copy(oldExp)); oRealVar = new OldExp(null, Exp.copy(repl)); // Nothing can be null! if (oldExp != null && quesRep != null && oSpecVar != null && repl != null && oRealVar != null) { // Alters, Clears, Reassigns, Replaces, Updates if (varDec.getMode() == Mode.ALTERS || varDec.getMode() == Mode.CLEARS || varDec.getMode() == Mode.REASSIGNS || varDec.getMode() == Mode.REPLACES || varDec.getMode() == Mode.UPDATES) { Exp quesVar; // Obtain the free variable VarExp freeVar = (VarExp) myCurrentAssertiveCode.getFreeVar( Utilities.createPosSymbol(replName), false); if (freeVar == null) { freeVar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(replName), varDec.getTy() .getMathTypeValue(), null); } // Apply the question mark to the free variable freeVar = Utilities .createQuestionMarkVariable(myTypeGraph .formConjunct(ensures, newConfirm), freeVar); if (exp instanceof ProgramDotExp || exp instanceof VariableDotExp) { // Make a copy from repl quesVar = Exp.copy(repl); // Replace the free variable in the question mark variable as the first element // in the dot expression. VarExp tmpVar = new VarExp(null, null, freeVar.getName()); tmpVar.setMathType(myTypeGraph.BOOLEAN); edu.clemson.cs.r2jt.collections.List<Exp> segs = ((DotExp) quesVar).getSegments(); segs.set(0, tmpVar); ((DotExp) quesVar).setSegments(segs); } else { // Create a variable expression from free variable quesVar = new VarExp(null, null, freeVar.getName()); quesVar.setMathType(freeVar.getMathType()); quesVar.setMathTypeValue(freeVar.getMathTypeValue()); } // Add the new free variable to free variable list myCurrentAssertiveCode.addFreeVar(freeVar); // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, repl); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(quesVar); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, quesRep); ensures = Utilities.replace(ensures, oSpecVar, repl); } // Update our final confirm with the parameter argument newConfirm = Utilities.replace(newConfirm, repl, quesVar); myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // All other modes else { // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, undqRep); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(repl); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, repl); ensures = Utilities.replace(ensures, oSpecVar, repl); } } } } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { ensures = Utilities.replace(ensures, undRepList.get(i), replList .get(i)); } return ensures; } /** * <p>Replace the formal with the actual variables * inside the requires clause.</p> * * @param requires The requires clause. * @param paramList The list of parameter variables. * @param argList The list of arguments from the operation call. * * @return The requires clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualReq(Exp requires, List<ParameterVarDec> paramList, List<Exp> argList) { // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace precondition variables in the requires clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp, myCurrentModuleScope); // VarExp form of the parameter variable VarExp oldExp = Utilities.createVarExp(null, null, varDec.getName(), exp .getMathType(), exp.getMathTypeValue()); // New VarExp VarExp newExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + varDec.getName().getName()), repl.getMathType(), repl.getMathTypeValue()); // Replace the old with the new in the requires clause requires = Utilities.replace(requires, oldExp, newExp); // Add it to our list undRepList.add(newExp); replList.add(repl); } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { requires = Utilities.replace(requires, undRepList.get(i), replList .get(i)); } return requires; } // ----------------------------------------------------------- // Proof Rules // ----------------------------------------------------------- /** * <p>Applies the assume rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>AssumeStmt</code>. */ private void applyAssumeStmtRule(AssumeStmt stmt) { // Check to see if our assertion just has "True" Exp assertion = stmt.getAssertion(); if (assertion instanceof VarExp && assertion.equals(myTypeGraph.getTrueVarExp())) { // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Apply simplification for equals expressions and // apply steps to generate parsimonious vcs. ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); boolean simplify = finalConfirm.getSimplify(); List<Exp> assumeExpList = Utilities.splitConjunctExp(stmt.getAssertion(), new ArrayList<Exp>()); List<Exp> confirmExpList = Utilities.splitConjunctExp(finalConfirm.getAssertion(), new ArrayList<Exp>()); Exp currentFinalConfirm = formParsimoniousVC(confirmExpList, assumeExpList, stmt .getIsStipulate()); // Set this as our new final confirm myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } /** * <p>Applies the change rule.</p> * * @param change The change clause */ private void applyChangeRule(VerificationStatement change) { List<VariableExp> changeList = (List<VariableExp>) change.getAssertion(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = confirmStmt.getAssertion(); // Loop through each variable for (VariableExp v : changeList) { // v is an instance of VariableNameExp if (v instanceof VariableNameExp) { VariableNameExp vNameExp = (VariableNameExp) v; // Create VarExp for vNameExp VarExp vExp = Utilities.createVarExp(vNameExp.getLocation(), vNameExp .getQualifier(), vNameExp.getName(), vNameExp .getMathType(), vNameExp.getMathTypeValue()); // Create a new question mark variable VarExp newV = Utilities .createQuestionMarkVariable(finalConfirm, vExp); // Add this new variable to our list of free variables myCurrentAssertiveCode.addFreeVar(newV); // Replace all instances of vExp with newV finalConfirm = Utilities.replace(finalConfirm, vExp, newV); } } // Set the modified statement as our new final confirm myCurrentAssertiveCode.setFinalConfirm(finalConfirm, confirmStmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nChange Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the call statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>CallStmt</code>. */ private void applyCallStmtRule(CallStmt stmt) { // Call a method to locate the operation dec for this call List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : stmt.getArguments()) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(stmt.getLocation(), stmt .getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); boolean isLocal = Utilities.isLocationOperation(stmt.getName().getName(), myCurrentModuleScope); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures; if (opDec.getEnsures() != null) { ensures = Exp.copy(opDec.getEnsures()); } else { ensures = myTypeGraph.getTrueVarExp(); Location loc; if (opDec.getLocation() != null) { loc = (Location) opDec.getLocation().clone(); } else { loc = (Location) opDec.getEnsures().getLocation().clone(); } ensures.setLocation(loc); } // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals(opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier().equals( opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = stmt.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Modify ensures using the parameter modes ensures = modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec .getName().getName(), opDec.getParameters(), isLocal); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace PostCondition variables in the ensures clause ensures = replaceFormalWithActualEns(ensures, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(stmt.getLocation(), requires, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual(stmt.getLocation(), ensures, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry OperationProfileEntry ope = Utilities.searchOperationProfile(loc, stmt.getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns(profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (stmt.getName().getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc.setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } ensures = myTypeGraph.formConjunct(ensures, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities.createDurCallExp((Location) loc.clone(), Integer .toString(opDec.getParameters().size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = stmt.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities.getVarName(pExp), p.getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities.createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirmExp, finalConfirm.getSimplify()); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (requires != null) { // Obtain the current location // Note: If we don't have a location, we create one Location loc; if (stmt.getName().getLocation() != null) { loc = (Location) stmt.getName().getLocation().clone(); } else { loc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location loc.setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, loc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) loc.clone(), requires, simplify); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (ensures != null) { // Obtain the current location Location loc = null; if (stmt.getName().getLocation() != null) { // Set the details of the current location loc = (Location) stmt.getName().getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Add this to our list of things to assume myCurrentAssertiveCode.addAssume(loc, ensures, false); } // Verbose Mode Debug Messages myVCBuffer.append("\nOperation Call Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies different rules to code statements.</p> * * @param statement The different statements. */ private void applyCodeRules(Statement statement) { // Apply each statement rule here. if (statement instanceof AssumeStmt) { applyAssumeStmtRule((AssumeStmt) statement); } else if (statement instanceof CallStmt) { applyCallStmtRule((CallStmt) statement); } else if (statement instanceof ConfirmStmt) { applyConfirmStmtRule((ConfirmStmt) statement); } else if (statement instanceof FuncAssignStmt) { applyFuncAssignStmtRule((FuncAssignStmt) statement); } else if (statement instanceof IfStmt) { applyIfStmtRule((IfStmt) statement); } else if (statement instanceof MemoryStmt) { // TODO: Deal with Forget if (((MemoryStmt) statement).isRemember()) { applyRememberRule(); } } else if (statement instanceof SwapStmt) { applySwapStmtRule((SwapStmt) statement); } else if (statement instanceof WhileStmt) { applyWhileStmtRule((WhileStmt) statement); } } /** * <p>Applies the confirm rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>ConfirmStmt</code>. */ private void applyConfirmStmtRule(ConfirmStmt stmt) { // Check to see if our assertion can be simplified Exp assertion = stmt.getAssertion(); if (stmt.getSimplify()) { // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Obtain the current final confirm statement ConfirmStmt currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); // Check to see if we can simplify the final confirm if (currentFinalConfirm.getSimplify()) { // Obtain the current location if (assertion.getLocation() != null) { // Set the details of the current location Location loc = (Location) assertion.getLocation().clone(); Utilities.setLocation(assertion, loc); } myCurrentAssertiveCode.setFinalConfirm(assertion, stmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Create a new and expression InfixExp newConf = myTypeGraph.formConjunct(assertion, currentFinalConfirm .getAssertion()); // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(newConf, false); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } } /** * <p>Applies the correspondence rule.</p> * * @param dec Representation declaration object. */ private void applyCorrespondenceRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtain the location for each assume clause Location decLoc = dec.getLocation(); // Add the global constraints as given Location constraintLoc; if (myGlobalConstraintExp.getLocation() != null) { constraintLoc = (Location) myGlobalConstraintExp.getLocation().clone(); } else { constraintLoc = (Location) decLoc.clone(); } constraintLoc.setDetails("Global Constraints from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(constraintLoc, myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add the convention as given assertiveCode.addAssume((Location) decLoc.clone(), dec.getConvention(), false); // Add the type representation constraint Exp repConstraintExp = null; Set<VarExp> keys = myRepresentationConstraintMap.keySet(); for (VarExp varExp : keys) { if (varExp.getQualifier() == null && varExp.getName().getName().equals( dec.getName().getName())) { if (repConstraintExp == null) { repConstraintExp = myRepresentationConstraintMap.get(varExp); } else { Utilities.ambiguousTy(dec.getRepresentation(), dec .getLocation()); } } } assertiveCode.addAssume((Location) decLoc.clone(), repConstraintExp, false); // Add the correspondence as given Exp correspondenceExp = Exp.copy(dec.getCorrespondence()); assertiveCode.addAssume((Location) decLoc.clone(), correspondenceExp, false); // Store the correspondence in our map myRepresentationCorrespondenceMap.put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation().getMathTypeValue(), null), Exp .copy(correspondenceExp)); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, conceptualVar); // Set the location for the constraint Location loc; if (correspondenceExp.getLocation() != null) { loc = (Location) correspondenceExp.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Well Defined Correspondence for " + dec.getName().getName()); Utilities.setLocation(constraint, loc); // We need to make sure the constraints for the type we are // implementing is met. boolean simplify = false; // Simplify if we just have true if (constraint.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(constraint, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nCorrespondence Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the facility declaration rule.</p> * * @param dec Facility declaration object. * @param addToIncAssertiveCodeStack True if the created assertive code needs * to be added to our incomplete assertive code stack. */ private void applyFacilityDeclRule(FacilityDec dec, boolean addToIncAssertiveCodeStack) { // Create a new assertive code to hold the facility declaration VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the current facility dec Location decLoc = dec.getLocation(); // Add the global constraints as given (if any) if (myGlobalConstraintExp != null) { Location gConstraintLoc; if (myGlobalConstraintExp.getLocation() != null) { gConstraintLoc = (Location) myGlobalConstraintExp.getLocation().clone(); } else { gConstraintLoc = (Location) decLoc.clone(); } gConstraintLoc.setDetails("Global Constraints from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(gConstraintLoc, myGlobalConstraintExp, false); } // Add the global require clause as given (if any) if (myGlobalRequiresExp != null) { Location gRequiresLoc; if (myGlobalRequiresExp.getLocation() != null) { gRequiresLoc = (Location) myGlobalRequiresExp.getLocation().clone(); } else { gRequiresLoc = (Location) decLoc.clone(); } gRequiresLoc.setDetails("Global Requires Clause from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(gRequiresLoc, myGlobalRequiresExp, false); } // Add a remember rule assertiveCode.addCode(new MemoryStmt((Location) decLoc.clone(), true)); try { // Obtain the concept module for the facility ConceptModuleDec facConceptDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> conceptFormalArgList = createModuleFormalArgExpList(facConceptDec.getParameters()); List<Exp> conceptActualArgList = createModuleActualArgExpList(assertiveCode, dec .getConceptParams()); // Facility Decl Rule (Concept Requires): CPC[ n ~> n_exp, R ~> IR ] Exp conceptReq = replaceFacilityDeclarationVariables(getRequiresClause( facConceptDec.getLocation(), facConceptDec), conceptFormalArgList, conceptActualArgList); if (!conceptReq.equals(myTypeGraph.getTrueVarExp())) { Location conceptReqLoc = (Location) dec.getConceptName().getLocation().clone(); conceptReqLoc.setDetails("Requires Clause for " + dec.getConceptName().getName() + " in Facility Instantiation Rule"); conceptReq.setLocation(conceptReqLoc); assertiveCode.addConfirm(conceptReqLoc, conceptReq, false); } // Create a mapping from concept formal to actual arguments // for future use. Map<Exp, Exp> conceptArgMap = new HashMap<Exp, Exp>(); for (int i = 0; i < conceptFormalArgList.size(); i++) { conceptArgMap.put(conceptFormalArgList.get(i), conceptActualArgList.get(i)); } // Facility Decl Rule (Concept Realization Requires): // (RPC[ rn ~> rn_exp, RR ~> IRR ])[ n ~> n_exp, R ~> IR ] // // Note: Only apply this part of the rule if the concept realization // is not externally realized. Map<Exp, Exp> conceptRealizArgMap = new HashMap<Exp, Exp>(); if (!dec.getExternallyRealizedFlag()) { ConceptBodyModuleDec facConceptRealizDec = (ConceptBodyModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getBodyName() .getName())).getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> conceptRealizFormalArgList = createModuleFormalArgExpList(facConceptRealizDec .getParameters()); List<Exp> conceptRealizActualArgList = createModuleActualArgExpList(assertiveCode, dec .getBodyParams()); // 1) Replace the concept realization formal with actuals Exp conceptRealizReq = replaceFacilityDeclarationVariables(getRequiresClause( facConceptRealizDec.getLocation(), facConceptRealizDec), conceptRealizFormalArgList, conceptRealizActualArgList); // 2) Replace the concept formal with actuals conceptRealizReq = replaceFacilityDeclarationVariables(conceptRealizReq, conceptFormalArgList, conceptActualArgList); // Add this as a new confirm statement in our assertive code if (!conceptRealizReq.equals(myTypeGraph.getTrueVarExp())) { Location conceptRealizReqLoc = (Location) dec.getBodyName().getLocation().clone(); conceptRealizReqLoc.setDetails("Requires Clause for " + dec.getBodyName().getName() + " in Facility Instantiation Rule"); conceptRealizReq.setLocation(conceptRealizReqLoc); assertiveCode.addConfirm(conceptRealizReqLoc, conceptRealizReq, false); } // Create a mapping from concept realization formal to actual arguments // for future use. for (int i = 0; i < conceptRealizFormalArgList.size(); i++) { conceptRealizArgMap.put(conceptRealizFormalArgList.get(i), conceptRealizActualArgList.get(i)); } // Facility Decl Rule (Operations as Concept Realization Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP and // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] // // Note: We need to pass in empty lists for enhancement/enhancement realization // formal and actuals, because they are not needed here. assertiveCode = facilityDeclOperationParamHelper(decLoc, assertiveCode, facConceptRealizDec.getParameters(), dec .getBodyParams(), conceptFormalArgList, conceptActualArgList, conceptRealizFormalArgList, conceptRealizActualArgList, new ArrayList<Exp>(), new ArrayList<Exp>(), new ArrayList<Exp>(), new ArrayList<Exp>()); } // TODO: Figure out how to apply the rule when there are enhancements for concept realizations List<EnhancementItem> enhancementList = dec.getEnhancements(); for (EnhancementItem e : enhancementList) { // Do something here. } // Apply the facility declaration rules to regular enhancement/enhancement realizations List<EnhancementBodyItem> enhancementBodyList = dec.getEnhancementBodies(); Map<PosSymbol, Map<Exp, Exp>> enhancementArgMaps = new HashMap<PosSymbol, Map<Exp, Exp>>(); for (EnhancementBodyItem ebi : enhancementBodyList) { // Obtain the enhancement module for the facility EnhancementModuleDec facEnhancementDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(ebi.getName().getName())) .getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> enhancementFormalArgList = createModuleFormalArgExpList(facEnhancementDec .getParameters()); List<Exp> enhancementActualArgList = createModuleActualArgExpList(assertiveCode, ebi .getParams()); // Facility Decl Rule (Enhancement Requires): // CPC[ n ~> n_exp, R ~> IR ] (Use the enhancement equivalents) Exp enhancementReq = replaceFacilityDeclarationVariables(getRequiresClause( facEnhancementDec.getLocation(), facEnhancementDec), enhancementFormalArgList, enhancementActualArgList); if (!enhancementReq.equals(myTypeGraph.getTrueVarExp())) { Location enhancementReqLoc = (Location) ebi.getName().getLocation().clone(); enhancementReqLoc.setDetails("Requires Clause for " + ebi.getName().getName() + " in Facility Instantiation Rule"); enhancementReq.setLocation(enhancementReqLoc); assertiveCode.addConfirm(enhancementReqLoc, enhancementReq, false); } // Create a mapping from concept formal to actual arguments // for future use. Map<Exp, Exp> enhancementArgMap = new HashMap<Exp, Exp>(); for (int i = 0; i < enhancementFormalArgList.size(); i++) { enhancementArgMap.put(enhancementFormalArgList.get(i), enhancementActualArgList.get(i)); } enhancementArgMaps.put(facEnhancementDec.getName(), enhancementArgMap); // Facility Decl Rule (Enhancement Realization Requires): // (RPC[ rn ~> rn_exp, RR ~> IRR ])[ n ~> n_exp, R ~> IR ] // (Use the enhancement realization equivalents and // also have to replace enhancement formals with actuals) // // Note: Only apply this part of the rule if the concept realization // is not externally realized. Map<Exp, Exp> enhancementRealizArgMap = new HashMap<Exp, Exp>(); EnhancementBodyModuleDec facEnhancementRealizDec = (EnhancementBodyModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(ebi.getBodyName() .getName())) .getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> enhancementRealizFormalArgList = createModuleFormalArgExpList(facEnhancementRealizDec .getParameters()); List<Exp> enhancementRealizActualArgList = createModuleActualArgExpList(assertiveCode, ebi .getBodyParams()); // 1) Replace the enhancement realization formal with actuals Exp enhancementRealizReq = replaceFacilityDeclarationVariables(getRequiresClause( facEnhancementRealizDec.getLocation(), facEnhancementRealizDec), enhancementRealizFormalArgList, enhancementRealizActualArgList); // 2) Replace the concept formal with actuals enhancementRealizReq = replaceFacilityDeclarationVariables( enhancementRealizReq, conceptFormalArgList, conceptActualArgList); // 3) Replace the enhancement formal with actuals enhancementRealizReq = replaceFacilityDeclarationVariables( enhancementRealizReq, enhancementFormalArgList, enhancementActualArgList); // Add this as a new confirm statement in our assertive code if (!enhancementRealizReq.equals(myTypeGraph.getTrueVarExp())) { Location enhancementRealizReqLoc = (Location) ebi.getBodyName().getLocation().clone(); enhancementRealizReqLoc.setDetails("Requires Clause for " + ebi.getBodyName().getName() + " in Facility Instantiation Rule"); enhancementRealizReq.setLocation(enhancementRealizReqLoc); assertiveCode.addConfirm(enhancementRealizReqLoc, enhancementRealizReq, false); } // Create a mapping from enhancement realization formal to actual arguments // for future use. for (int i = 0; i < enhancementRealizFormalArgList.size(); i++) { enhancementRealizArgMap.put(enhancementRealizFormalArgList .get(i), enhancementRealizActualArgList.get(i)); } enhancementArgMaps.put(facEnhancementRealizDec.getName(), enhancementRealizArgMap); // Facility Decl Rule (Operations as Enhancement Realization Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP and // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] // // Note: We need to pass in empty lists for concept realization // formal and actuals, because they are not needed here. assertiveCode = facilityDeclOperationParamHelper(decLoc, assertiveCode, facEnhancementRealizDec.getParameters(), ebi .getBodyParams(), conceptFormalArgList, conceptActualArgList, new ArrayList<Exp>(), new ArrayList<Exp>(), enhancementFormalArgList, enhancementActualArgList, enhancementRealizFormalArgList, enhancementRealizActualArgList); } // The code below stores a mapping between each of the concept/realization/enhancement // formal arguments to the actual arguments instantiated by the facility. // This is needed to replace the requires/ensures clauses from facility instantiated // operations. FacilityFormalToActuals formalToActuals = new FacilityFormalToActuals(conceptArgMap, conceptRealizArgMap, enhancementArgMaps); for (Dec d : facConceptDec.getDecs()) { if (d instanceof TypeDec) { Location loc = (Location) dec.getLocation().clone(); PosSymbol qual = dec.getName().copy(); PosSymbol name = d.getName().copy(); Ty dTy = ((TypeDec) d).getModel(); myInstantiatedFacilityArgMap.put(Utilities.createVarExp( loc, qual, name, dTy.getMathType(), dTy .getMathTypeValue()), formalToActuals); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(dec.getLocation()); } // This is a local facility and we need to add it to our incomplete // assertive code stack. if (addToIncAssertiveCodeStack) { // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Facility Dec Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nFacility Declaration Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } } /** * <p>Applies the function assignment rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>FuncAssignStmt</code>. */ private void applyFuncAssignStmtRule(FuncAssignStmt stmt) { PosSymbol qualifier = null; ProgramExp assignExp = stmt.getAssign(); ProgramParamExp assignParamExp = null; // Replace all instances of the variable on the left hand side // in the ensures clause with the expression on the right. Exp leftVariable; // We have a variable inside a record as the variable being assigned. if (stmt.getVar() instanceof VariableDotExp) { VariableDotExp v = (VariableDotExp) stmt.getVar(); List<VariableExp> vList = v.getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Loot through each variable expression and add it to our dot list for (VariableExp vr : vList) { VarExp varExp = new VarExp(); if (vr instanceof VariableNameExp) { varExp.setName(((VariableNameExp) vr).getName()); varExp.setMathType(vr.getMathType()); varExp.setMathTypeValue(vr.getMathTypeValue()); newSegments.add(varExp); } } // Expression to be replaced leftVariable = new DotExp(v.getLocation(), newSegments, null); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // We have a regular variable being assigned. else { // Expression to be replaced VariableNameExp v = (VariableNameExp) stmt.getVar(); leftVariable = new VarExp(v.getLocation(), null, v.getName()); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // Simply replace the numbers/characters/strings if (assignExp instanceof ProgramIntegerExp || assignExp instanceof ProgramCharExp || assignExp instanceof ProgramStringExp) { Exp replaceExp = Utilities.convertExp(assignExp, myCurrentModuleScope); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, replaceExp); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt .getSimplify()); } else { // Check to see what kind of expression is on the right hand side if (assignExp instanceof ProgramParamExp) { // Cast to a ProgramParamExp assignParamExp = (ProgramParamExp) assignExp; } else if (assignExp instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) assignExp; assignParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } // Call a method to locate the operation dec for this call List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : assignParamExp.getArguments()) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(stmt.getLocation(), qualifier, assignParamExp.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals( opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier() .equals(opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation() .clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = assignParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(assignParamExp .getLocation(), requires, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (assignParamExp.getName().getLocation() != null) { reqloc = (Location) assignParamExp.getName().getLocation() .clone(); } else { reqloc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location reqloc .setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location if (assignParamExp.getName().getLocation() != null) { // Set the details of the current location Location loc = (Location) assignParamExp.getName() .getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Replace the formal with the actual ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec .getStateVars(), replaceArgs, true); // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual( assignParamExp.getLocation(), ensures, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, ensures); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt.getSimplify()); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags .isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode .getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, assignParamExp .getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns( profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (assignParamExp.getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc .setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } finalConfirmExp = myTypeGraph.formConjunct( finalConfirmExp, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec .getParameters(), opDec .getStateVars(), replaceArgs, false); VarExp cumDur = Utilities .createVarExp( (Location) loc.clone(), null, Utilities .createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities .createDurCallExp( (Location) loc.clone(), Integer .toString(opDec .getParameters() .size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities .createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = assignParamExp.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities .getVarName(pExp), p .getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur( v, myTypeGraph.R); sumEvalDur = new InfixExp( (Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Add duration of assignment and finalize the temporary variable Exp assignDur = Utilities.createVarExp((Location) loc .clone(), null, Utilities .createPosSymbol("Dur_Assgn"), myTypeGraph.R, null); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), assignDur); sumEvalDur.setMathType(myTypeGraph.R); Exp finalExpDur = Utilities.createFinalizAnyDurExp(stmt .getVar(), myTypeGraph.R, myCurrentModuleScope); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalExpDur); sumEvalDur.setMathType(myTypeGraph.R); // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm( finalConfirmExp, finalConfirm .getSimplify()); } } else { Utilities.illegalOperationEnsures(opDec .getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } } // Verbose Mode Debug Messages myVCBuffer.append("\nFunction Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the if statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>IfStmt</code>. */ private void applyIfStmtRule(IfStmt stmt) { // Note: In the If Rule, we will have two instances of the assertive code. // One for when the if condition is true and one for the else condition. // The current global assertive code variable is going to be used for the if path, // and we are going to create a new assertive code for the else path (this includes // the case when there is no else clause). ProgramExp ifCondition = stmt.getTest(); // Negation of If (Need to make a copy before we start modifying // the current assertive code for the if part) AssertiveCode negIfAssertiveCode = new AssertiveCode(myCurrentAssertiveCode); // Call a method to locate the operation dec for this call PosSymbol qualifier = null; ProgramParamExp testParamExp = null; // Check to see what kind of expression is on the right hand side if (ifCondition instanceof ProgramParamExp) { // Cast to a ProgramParamExp testParamExp = (ProgramParamExp) ifCondition; } else if (ifCondition instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) ifCondition; testParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } else { Utilities.expNotHandled(ifCondition, stmt.getLocation()); } Location ifConditionLoc; if (ifCondition.getLocation() != null) { ifConditionLoc = (Location) ifCondition.getLocation().clone(); } else { ifConditionLoc = (Location) stmt.getLocation().clone(); } // Search for the operation dec List<PTType> argTypes = new LinkedList<PTType>(); List<ProgramExp> argsList = testParamExp.getArguments(); for (ProgramExp arg : argsList) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(ifCondition.getLocation(), qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals(opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier().equals( opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Confirm the invoking condition // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = testParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (testParamExp.getName().getLocation() != null) { reqloc = (Location) testParamExp.getName().getLocation().clone(); } else { reqloc = new Location(null, null); } // Set the details of the current location reqloc.setDetails("Requires Clause of " + opDec.getName()); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Add the if condition as the assume clause // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, negEnsures = null, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location Location loc = null; if (testParamExp.getName().getLocation() != null) { // Set the details of the current location loc = (Location) testParamExp.getName() .getLocation().clone(); loc.setDetails("If Statement Condition"); Utilities.setLocation(ensures, loc); } // Replace the formals with the actuals. ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); myCurrentAssertiveCode.addAssume(loc, ensures, true); // Negation of the condition negEnsures = Utilities.negateExp(ensures, BOOLEAN); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> thenStmtList; if (stmt.getThenclause() != null) { thenStmtList = stmt.getThenclause(); } else { thenStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp ifConfirmExp = ifConfirm.getAssertion(); Location ifLocation; if (ifConfirmExp.getLocation() != null) { ifLocation = (Location) ifConfirmExp.getLocation().clone(); } else { ifLocation = (Location) stmt.getLocation().clone(); } String ifDetail = ifLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is true"; ifLocation.setDetails(ifDetail); ifConfirmExp.setLocation(ifLocation); // NY YS // Duration for If Part InfixExp sumEvalDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) ifLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (ifConfirmExp.isLiteralTrue() && thenStmtList.size() != 0) { Statement st = thenStmtList.get(thenStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(ifConfirmExp)), myTypeGraph.R, null); } // Search for operation profile OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); Exp opDur = Exp.copy(ope.getDurationClause()); Exp durCallExp = Utilities.createDurCallExp(loc, Integer.toString(opDec .getParameters().size()), Z, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); thenStmtList.set(thenStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" ifConfirmExp = Utilities.replace(ifConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the if to the assertive code myCurrentAssertiveCode.addStatements(thenStmtList); // Set the final if confirm myCurrentAssertiveCode.setFinalConfirm(ifConfirmExp, ifConfirm .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nIf Part Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); // Add the negation of the if condition as the assume clause if (negEnsures != null) { negIfAssertiveCode.addAssume(ifLocation, negEnsures, true); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList; if (stmt.getElseclause() != null) { elseStmtList = stmt.getElseclause(); } else { elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt negIfConfirm = negIfAssertiveCode.getFinalConfirm(); Exp negIfConfirmExp = negIfConfirm.getAssertion(); Location negIfLocation; if (negIfConfirmExp.getLocation() != null) { negIfLocation = (Location) negIfConfirmExp.getLocation().clone(); } else { negIfLocation = (Location) stmt.getLocation().clone(); } String negIfDetail = negIfLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is false"; negIfLocation.setDetails(negIfDetail); negIfConfirmExp.setLocation(negIfLocation); // NY YS // Duration for Else Part if (sumEvalDur != null) { Location loc = (Location) negIfLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (negIfConfirmExp.isLiteralTrue() && elseStmtList.size() != 0) { Statement st = elseStmtList.get(elseStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(negIfConfirmExp)), myTypeGraph.R, null); } Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); elseStmtList.set(elseStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" negIfConfirmExp = Utilities.replace(negIfConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the else to the assertive code negIfAssertiveCode.addStatements(elseStmtList); // Set the final else confirm negIfAssertiveCode.setFinalConfirm(negIfConfirmExp, negIfConfirm .getSimplify()); // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(negIfAssertiveCode); // Verbose Mode Debug Messages String newString = "\nNegation of If Part Rule Applied: \n"; newString += negIfAssertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the initialization rule.</p> * * @param dec Representation declaration object. */ private void applyInitializationRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Add any variable declarations for records // TODO: Change this! The only variable we need to add is the exemplar Exp representationConstraint = myTypeGraph.getTrueVarExp(); List<ParameterVarDec> fieldAsParameters = new ArrayList<ParameterVarDec>(); if (dec.getRepresentation() instanceof RecordTy) { RecordTy ty = (RecordTy) dec.getRepresentation(); List<VarDec> decs = ty.getFields(); assertiveCode.addVariableDecs(decs); for (VarDec v : decs) { Ty vTy = v.getTy(); // Convert "v" into a parameter for substitution purposes fieldAsParameters.add(new ParameterVarDec(Mode.FIELD, v .getName(), vTy)); // Don't do anything if it is a generic type variable if (!(vTy.getProgramTypeValue() instanceof PTGeneric)) { // TODO: We could have a record ty here NameTy vTyAsNameTy = null; if (vTy instanceof NameTy) { vTyAsNameTy = (NameTy) v.getTy(); } else { Utilities.tyNotHandled(v.getTy(), v.getLocation()); } // Convert the raw type into a variable expression VarExp vTyAsVarExp = null; if (vTyAsNameTy.getQualifier() == null) { for (VarExp varExp : myInstantiatedFacilityArgMap .keySet()) { if (varExp.getName().getName().equals( vTyAsNameTy.getName().getName())) { if (vTyAsVarExp == null) { vTyAsVarExp = (VarExp) Exp.copy(varExp); } else { Utilities.ambiguousTy(vTy, v .getLocation()); } } } } else { vTyAsVarExp = Utilities.createVarExp(vTyAsNameTy .getLocation(), vTyAsNameTy .getQualifier(), vTyAsNameTy .getName(), vTyAsNameTy .getMathType(), vTyAsNameTy .getMathTypeValue()); } // Create a dotted expression to represent the record field "v" VarExp vAsVarExp = Utilities.createVarExp(v.getLocation(), null, v .getName(), vTyAsNameTy .getMathTypeValue(), null); edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(Exp.copy(exemplar)); dotExpList.add(vAsVarExp); DotExp dotExp = Utilities.createDotExp(v.getLocation(), dotExpList, vTyAsNameTy .getMathTypeValue()); // Obtain the constraint from this field Exp vConstraint = Utilities.retrieveConstraint(v.getLocation(), vTyAsVarExp, dotExp, myCurrentModuleScope); if (representationConstraint.isLiteralTrue()) { representationConstraint = vConstraint; } else { representationConstraint = myTypeGraph.formConjunct( representationConstraint, vConstraint); } } } } // Replace facility actuals variables in the representation constraint clause representationConstraint = Utilities.replaceFacilityFormalWithActual(decLoc, representationConstraint, fieldAsParameters, myInstantiatedFacilityArgMap, myCurrentModuleScope); // Add the representation constraint to our global map myRepresentationConstraintMap.put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation() .getMathTypeValue(), null), representationConstraint); // Add any statements in the initialization block if (dec.getInitialization() != null) { InitItem initItem = dec.getInitialization(); assertiveCode.addStatements(initItem.getStatements()); } // Make sure we have a convention Exp conventionExp; if (dec.getConvention() == null) { conventionExp = myTypeGraph.getTrueVarExp(); } else { conventionExp = Exp.copy(dec.getConvention()); } // Set the location for the constraint Location loc; if (conventionExp.getLocation() != null) { loc = (Location) conventionExp.getLocation().clone(); } else { loc = (Location) dec.getLocation().clone(); } loc.setDetails("Convention for " + dec.getName().getName()); Utilities.setLocation(conventionExp, loc); // Add the convention as something we need to confirm boolean simplify = false; // Simplify if we just have true if (conventionExp.isLiteralTrue()) { simplify = true; } Location conventionLoc = (Location) conventionExp.getLocation().clone(); conventionLoc.setDetails(conventionLoc.getDetails() + " generated by Initialization Rule"); Utilities.setLocation(conventionExp, conventionLoc); assertiveCode.addConfirm(loc, conventionExp, simplify); // Store the convention in our map myRepresentationConventionsMap .put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation().getMathTypeValue(), null), Exp.copy(conventionExp)); // Add the correspondence as given Location corrLoc; if (dec.getCorrespondence().getLocation() != null) { corrLoc = (Location) dec.getCorrespondence().getLocation() .clone(); } else { corrLoc = (Location) decLoc.clone(); } corrLoc.setDetails("Correspondence for " + dec.getName().getName()); assertiveCode.addAssume(corrLoc, dec.getCorrespondence(), false); // Create a variable that refers to the conceptual exemplar DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp init; if (type.getInitialization().getEnsures() == null) { init = myTypeGraph.getTrueVarExp(); } else { init = Exp.copy(type.getInitialization().getEnsures()); } init = Utilities.replace(init, exemplar, conceptualVar); // Set the location for the constraint Location initLoc; initLoc = (Location) dec.getLocation().clone(); initLoc.setDetails("Initialization Rule for " + dec.getName().getName()); Utilities.setLocation(init, initLoc); // Add the initialization as something we need to confirm simplify = false; // Simplify if we just have true if (init.isLiteralTrue()) { simplify = true; } assertiveCode.addConfirm(loc, init, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nInitialization Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the procedure declaration rule.</p> * * @param opLoc Location of the procedure declaration. * @param name Name of the procedure. * @param requires Requires clause * @param ensures Ensures clause * @param decreasing Decreasing clause (if any) * @param procDur Procedure duration clause (if in performance mode) * @param varFinalDur Local variable finalization duration clause (if in performance mode) * @param parameterVarList List of all parameter variables for this procedure * @param variableList List of all variables for this procedure * @param statementList List of statements for this procedure * @param isLocal True if the it is a local operation. False otherwise. */ private void applyProcedureDeclRule(Location opLoc, String name, Exp requires, Exp ensures, Exp decreasing, Exp procDur, Exp varFinalDur, List<ParameterVarDec> parameterVarList, List<VarDec> variableList, List<Statement> statementList, boolean isLocal) { // Add the global requires clause if (myGlobalRequiresExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalRequiresExp, false); } // Add the global constraints if (myGlobalConstraintExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalConstraintExp, false); } // Only do this if this is not a local operation // and we are in a concept realization Exp aggConventionExp = null; Exp aggCorrespondenceExp = null; if (!isLocal) { // Do this for all parameters that are type representations for (ParameterVarDec parameterVarDec : parameterVarList) { NameTy parameterVarDecTy = (NameTy) parameterVarDec.getTy(); Exp parameterAsVarExp = Utilities.createVarExp(parameterVarDec.getLocation(), null, parameterVarDec.getName(), parameterVarDecTy.getMathTypeValue(), null); Set<VarExp> conventionKeys = myRepresentationConventionsMap.keySet(); for (VarExp varExp : conventionKeys) { // Make sure the qualifiers are the same PosSymbol varExpQual = varExp.getQualifier(); PosSymbol parameterTyQual = parameterVarDecTy.getQualifier(); if ((varExpQual == null && parameterTyQual == null) || (varExpQual.getName().equals(parameterTyQual .getName()))) { // Make sure that the type names are the same if (varExp.getName().getName().equals( parameterVarDecTy.getName().getName())) { // Check to see if this is a type representation SymbolTableEntry typeEntry = Utilities.searchProgramType(opLoc, varExp .getQualifier(), varExp.getName(), myCurrentModuleScope); if (typeEntry instanceof RepresentationTypeEntry) { // Replacements MathSymbolEntry exemplarEntry = typeEntry.toRepresentationTypeEntry( opLoc).getDefiningTypeEntry() .getExemplar(); Exp exemplar = Utilities .createVarExp( opLoc, null, Utilities .createPosSymbol(exemplarEntry .getName()), exemplarEntry.getType(), null); Map<Exp, Exp> replacementMap = new HashMap<Exp, Exp>(); replacementMap.put(exemplar, parameterAsVarExp); // Obtain the convention and substitute formal with actual Exp conventionExp = Exp.copy(myRepresentationConventionsMap .get(varExp)); conventionExp = conventionExp .substitute(replacementMap); // Add the convention as something we need to ensure myCurrentAssertiveCode.addAssume( (Location) opLoc.clone(), conventionExp, false); // Store this convention in our aggregated convention exp if (aggConventionExp == null) { aggConventionExp = Exp.copy(conventionExp); } else { aggConventionExp = myTypeGraph.formConjunct( aggConventionExp, conventionExp); } aggConventionExp.setLocation(conventionExp .getLocation()); } } } } Set<VarExp> correspondencekeys = myRepresentationCorrespondenceMap.keySet(); for (VarExp varExp : correspondencekeys) { // Make sure the qualifiers are the same PosSymbol varExpQual = varExp.getQualifier(); PosSymbol parameterTyQual = parameterVarDecTy.getQualifier(); if ((varExpQual == null && parameterTyQual == null) || (varExpQual.getName().equals(parameterTyQual .getName()))) { // Make sure that the type names are the same if (varExp.getName().getName().equals( parameterVarDecTy.getName().getName())) { // Check to see if this is a type representation SymbolTableEntry typeEntry = Utilities.searchProgramType(opLoc, varExp .getQualifier(), varExp.getName(), myCurrentModuleScope); if (typeEntry instanceof RepresentationTypeEntry) { // Attempt to replace the correspondence for each parameter Location reqLoc = (Location) requires.getLocation() .clone(); Exp tmp = Exp.copy(requires); MathSymbolEntry exemplarEntry = typeEntry.toRepresentationTypeEntry( opLoc).getDefiningTypeEntry() .getExemplar(); // Replacements Exp exemplar = Utilities .createVarExp( opLoc, null, Utilities .createPosSymbol(exemplarEntry .getName()), exemplarEntry.getType(), null); Map<Exp, Exp> replacementMap = new HashMap<Exp, Exp>(); replacementMap.put(exemplar, parameterAsVarExp); // Obtain the correspondence and substitute formal with actual Exp corresponenceExp = Exp .copy(myRepresentationCorrespondenceMap .get(varExp)); corresponenceExp = corresponenceExp .substitute(replacementMap); if (corresponenceExp instanceof EqualsExp) { tmp = Utilities .replace( requires, ((EqualsExp) corresponenceExp) .getLeft(), ((EqualsExp) corresponenceExp) .getRight()); } // Well_Def_Corr_Hyp rule: Conjunct the correspondence to // the requires clause. This will ensure that the parsimonious // vc step replaces the requires clause if possible. if (tmp.equals(requires)) { requires = myTypeGraph.formConjunct(requires, Exp.copy(corresponenceExp)); } else { myCurrentAssertiveCode.addAssume( (Location) opLoc.clone(), Exp .copy(corresponenceExp), false); requires = tmp; } requires.setLocation(reqLoc); // Store this correspondence in our aggregated correspondence exp if (aggCorrespondenceExp == null) { aggCorrespondenceExp = Exp.copy(corresponenceExp); } else { aggCorrespondenceExp = myTypeGraph.formConjunct( aggCorrespondenceExp, corresponenceExp); } } } } } } } myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), requires, false); // NY - Add any procedure duration clauses InfixExp finalDurationExp = null; if (procDur != null) { // Add Cum_Dur as a free variable VarExp cumDur = Utilities.createVarExp((Location) opLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); myCurrentAssertiveCode.addFreeVar(cumDur); // Create 0.0 VarExp zeroPtZero = Utilities.createVarExp(opLoc, null, Utilities .createPosSymbol("0.0"), myTypeGraph.R, null); // Create an equals expression (Cum_Dur = 0.0) EqualsExp equalsExp = new EqualsExp(null, Exp.copy(cumDur), EqualsExp.EQUAL, zeroPtZero); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) opLoc.clone(); eqLoc.setDetails("Initialization of Cum_Dur for Procedure " + name); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); // Create the duration expression Exp durationExp; if (varFinalDur != null) { durationExp = new InfixExp(null, Exp.copy(cumDur), Utilities .createPosSymbol("+"), varFinalDur); } else { durationExp = Exp.copy(cumDur); } durationExp.setMathType(myTypeGraph.R); Location sumLoc = (Location) opLoc.clone(); sumLoc .setDetails("Summation of Finalization Duration for Procedure " + name); Utilities.setLocation(durationExp, sumLoc); finalDurationExp = new InfixExp(null, durationExp, Utilities .createPosSymbol("<="), procDur); finalDurationExp.setMathType(BOOLEAN); Location andLoc = (Location) opLoc.clone(); andLoc.setDetails("Duration Clause of " + name); Utilities.setLocation(finalDurationExp, andLoc); } // Add the remember rule myCurrentAssertiveCode.addCode(new MemoryStmt((Location) opLoc.clone(), true)); // Add declared variables into the assertion. Also add // them to the list of free variables. myCurrentAssertiveCode.addVariableDecs(variableList); addVarDecsAsFreeVars(variableList); // Check to see if we have a recursive procedure. // If yes, we will need to create an additional assume clause // (P_val = (decreasing clause)) in our list of assertions. if (decreasing != null) { // Store for future use myOperationDecreasingExp = decreasing; // Add P_val as a free variable VarExp pVal = Utilities.createPValExp(decreasing.getLocation(), myCurrentModuleScope); myCurrentAssertiveCode.addFreeVar(pVal); // Create an equals expression EqualsExp equalsExp = new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp .copy(decreasing)); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) decreasing.getLocation().clone(); eqLoc.setDetails("Progress Metric for Recursive Procedure"); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); } // Add the list of statements myCurrentAssertiveCode.addStatements(statementList); // Add the finalization duration ensures (if any) if (finalDurationExp != null) { myCurrentAssertiveCode.addConfirm(finalDurationExp.getLocation(), finalDurationExp, false); } // Correct_Op_Hyp rule: Only applies to non-local operations // in concept realizations. if (!isLocal && aggConventionExp != null) { if (!aggConventionExp.isLiteralTrue()) { Location conventionLoc = (Location) opLoc.clone(); conventionLoc.setDetails(aggConventionExp.getLocation() .getDetails() + " generated by " + name); Utilities.setLocation(aggConventionExp, conventionLoc); myCurrentAssertiveCode.addConfirm(aggConventionExp .getLocation(), aggConventionExp, false); } } // Well_Def_Corr_Hyp rule: Rather than doing direct replacement, // we leave that logic to the parsimonious vc step. A replacement // will occur if this is a correspondence function or an implies // will be formed if this is a correspondence relation. if (!isLocal && aggCorrespondenceExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), aggCorrespondenceExp, false); } // Add the final confirms clause myCurrentAssertiveCode.setFinalConfirm(ensures, false); // Verbose Mode Debug Messages myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the remember rule.</p> */ private void applyRememberRule() { // Obtain the final confirm and apply the remember method for Exp ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); conf = conf.remember(); myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nRemember Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be * stored for later use and therefore should be considered immutable after * a call to this method.</p> */ private void applyRules() { // Apply a proof rule to each of the assertions while (myCurrentAssertiveCode.hasAnotherAssertion()) { // Work our way from the last assertion VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion(); switch (curAssertion.getType()) { // Change Assertion case VerificationStatement.CHANGE: applyChangeRule(curAssertion); break; // Code case VerificationStatement.CODE: applyCodeRules((Statement) curAssertion.getAssertion()); break; // Variable Declaration Assertion case VerificationStatement.VARIABLE: applyVarDeclRule(curAssertion); break; } } } /** * <p>Applies the swap statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>SwapStmt</code>. */ private void applySwapStmtRule(SwapStmt stmt) { // Obtain the current final confirm clause ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); // Create a copy of the left and right hand side VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); // New left and right Exp newLeft = Utilities.convertExp(stmtLeft, myCurrentModuleScope); Exp newRight = Utilities.convertExp(stmtRight, myCurrentModuleScope); // Use our final confirm to obtain the math types List lst = conf.getSubExpressions(); for (int i = 0; i < lst.size(); i++) { if (lst.get(i) instanceof VarExp) { VarExp thisExp = (VarExp) lst.get(i); if (newRight instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newRight).getName().getName())) { newRight.setMathType(thisExp.getMathType()); newRight.setMathTypeValue(thisExp.getMathTypeValue()); } } if (newLeft instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newLeft).getName().getName())) { newLeft.setMathType(thisExp.getMathType()); newLeft.setMathTypeValue(thisExp.getMathTypeValue()); } } } } // Temp variable VarExp tmp = new VarExp(); tmp.setName(Utilities.createPosSymbol("_" + Utilities.getVarName(stmtLeft).getName())); tmp.setMathType(stmtLeft.getMathType()); tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); // Replace according to the swap rule conf = Utilities.replace(conf, newRight, tmp); conf = Utilities.replace(conf, newLeft, newRight); conf = Utilities.replace(conf, tmp, newLeft); // NY YS // Duration for swap statements if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities .createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf)), myTypeGraph.R, null); Exp swapDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol("Dur_Swap"), myTypeGraph.R, null); InfixExp sumSwapDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), swapDur); sumSwapDur.setMathType(myTypeGraph.R); conf = Utilities.replace(conf, cumDur, sumSwapDur); } // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nSwap Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the variable declaration rule.</p> * * @param var A declared variable stored as a * <code>VerificationStatement</code> */ private void applyVarDeclRule(VerificationStatement var) { // Obtain the variable from the verification statement VarDec varDec = (VarDec) var.getAssertion(); ProgramTypeEntry typeEntry; // Ty is NameTy if (varDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) varDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy .getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Deep copy the original initialization ensures Exp init = Exp.copy(type.getInitialization().getEnsures()); init = Utilities.replace(init, exemplar, varDecExp); // Set the location for the initialization ensures Location loc; if (init.getLocation() != null) { loc = (Location) init.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Initialization ensures on " + varDec.getName().getName()); Utilities.setLocation(init, loc); // Final confirm clause Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); // Obtain the string form of the variable String varName = varDec.getName().getName(); // Check to see if we have a variable dot expression. // If we do, we will need to extract the name. int dotIndex = varName.indexOf("."); if (dotIndex > 0) { varName = varName.substring(0, dotIndex); } // Check to see if this variable was declared inside a record ResolveConceptualElement element = myCurrentAssertiveCode.getInstantiatingElement(); if (element instanceof RepresentationDec) { RepresentationDec dec = (RepresentationDec) element; if (dec.getRepresentation() instanceof RecordTy) { SymbolTableEntry repSte = Utilities.searchProgramType(dec.getLocation(), null, dec.getName(), myCurrentModuleScope); ProgramTypeDefinitionEntry representationTypeEntry = repSte.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); // Create a variable expression from the type exemplar VarExp representationExemplar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(representationTypeEntry .getExemplar() .getName()), representationTypeEntry .getModelType(), null); // Create a dotted expression edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(representationExemplar); expList.add(varDecExp); DotExp dotExp = Utilities.createDotExp(loc, expList, varDecExp .getMathType()); // Replace the initialization clauses appropriately init = Utilities.replace(init, varDecExp, dotExp); } } // Replace facility actuals variables in the init clause List<ParameterVarDec> varDecAsParameter = new ArrayList<ParameterVarDec>(); varDecAsParameter.add(new ParameterVarDec(Mode.LOCAL, varDec .getName(), varDec.getTy())); init = Utilities.replaceFacilityFormalWithActual( (Location) loc.clone(), init, varDecAsParameter, myInstantiatedFacilityArgMap, myCurrentModuleScope); // Check if our confirm clause uses this variable if (finalConfirm.containsVar(varName, false)) { // Add the new assume clause to our assertive code. myCurrentAssertiveCode.addAssume((Location) loc.clone(), init, false); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = varDec.getLocation(); // Create an is_initial dot expression DotExp isInitialExp = Utilities.createInitExp(varDec, MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + varDec.getName().getName()); Utilities.setLocation(isInitialExp, loc); } // Add to our assertive code as an assume myCurrentAssertiveCode.addAssume(varLoc, isInitialExp, false); } // NY YS // Initialization duration for this variable if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { ConfirmStmt finalConfirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = finalConfirmStmt.getAssertion(); Location loc = ((NameTy) varDec.getTy()).getName().getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirm)), myTypeGraph.R, null); Exp initDur = Utilities.createInitAnyDur(varDec, myTypeGraph.R); InfixExp sumInitDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), initDur); sumInitDur.setMathType(myTypeGraph.R); finalConfirm = Utilities.replace(finalConfirm, cumDur, sumInitDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirm, finalConfirmStmt.getSimplify()); } // Verbose Mode Debug Messages myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Ty not handled. Utilities.tyNotHandled(varDec.getTy(), varDec.getLocation()); } } /** * <p>Applies the while statement rule.</p> * * @param stmt Our current <code>WhileStmt</code>. */ private void applyWhileStmtRule(WhileStmt stmt) { // Obtain the loop invariant Exp invariant; boolean simplifyInvariant = false; if (stmt.getMaintaining() != null) { invariant = Exp.copy(stmt.getMaintaining()); invariant.setMathType(stmt.getMaintaining().getMathType()); // Simplify if we just have true if (invariant.isLiteralTrue()) { simplifyInvariant = true; } } else { invariant = myTypeGraph.getTrueVarExp(); simplifyInvariant = true; } // NY YS // Obtain the elapsed time duration of loop Exp elapsedTimeDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { if (stmt.getElapsed_Time() != null) { elapsedTimeDur = Exp.copy(stmt.getElapsed_Time()); elapsedTimeDur.setMathType(myTypeGraph.R); } } // Confirm the base case of invariant Exp baseCase = Exp.copy(invariant); Location baseLoc; if (invariant.getLocation() != null) { baseLoc = (Location) invariant.getLocation().clone(); } else { baseLoc = (Location) stmt.getLocation().clone(); } baseLoc.setDetails("Base Case of the Invariant of While Statement"); Utilities.setLocation(baseCase, baseLoc); // NY YS // Confirm that elapsed time is 0.0 if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) && elapsedTimeDur != null) { Exp initElapseDurExp = Exp.copy(elapsedTimeDur); Location initElapseLoc; if (elapsedTimeDur != null && elapsedTimeDur.getLocation() != null) { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } else { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } initElapseLoc .setDetails("Base Case of Elapsed Time Duration of While Statement"); Utilities.setLocation(initElapseDurExp, initElapseLoc); Exp zeroEqualExp = new EqualsExp((Location) initElapseLoc.clone(), initElapseDurExp, 1, Utilities.createVarExp( (Location) initElapseLoc.clone(), null, Utilities.createPosSymbol("0.0"), myTypeGraph.R, null)); zeroEqualExp.setMathType(BOOLEAN); baseCase = myTypeGraph.formConjunct(baseCase, zeroEqualExp); } myCurrentAssertiveCode.addConfirm((Location) baseLoc.clone(), baseCase, simplifyInvariant); // Add the change rule if (stmt.getChanging() != null) { myCurrentAssertiveCode.addChange(stmt.getChanging()); } // Assume the invariant and NQV(RP, P_Val) = P_Exp Location whileLoc = stmt.getLocation(); Exp assume; Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); boolean simplifyFinalConfirm = myCurrentAssertiveCode.getFinalConfirm().getSimplify(); Exp decreasingExp = stmt.getDecreasing(); Exp nqv; if (decreasingExp != null) { VarExp pval = Utilities.createPValExp((Location) whileLoc.clone(), myCurrentModuleScope); nqv = Utilities.createQuestionMarkVariable(finalConfirm, pval); nqv.setMathType(pval.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), 1, Exp.copy(decreasingExp)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); } else { decreasingExp = myTypeGraph.getTrueVarExp(); nqv = myTypeGraph.getTrueVarExp(); assume = Exp.copy(invariant); } // NY YS // Also assume NQV(RP, Cum_Dur) = El_Dur_Exp Exp nqv2 = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { VarExp cumDurExp = Utilities.createVarExp((Location) whileLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); nqv2 = Utilities.createQuestionMarkVariable(finalConfirm, cumDurExp); nqv2.setMathType(cumDurExp.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv2), 1, Exp.copy(elapsedTimeDur)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(assume, equalPExp); } myCurrentAssertiveCode.addAssume((Location) whileLoc.clone(), assume, false); // if statement body (need to deep copy!) edu.clemson.cs.r2jt.collections.List<Statement> ifStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); edu.clemson.cs.r2jt.collections.List<Statement> whileStmtList = stmt.getStatements(); for (Statement s : whileStmtList) { ifStmtList.add((Statement) s.clone()); } // Confirm the inductive case of invariant Exp inductiveCase = Exp.copy(invariant); Location inductiveLoc; if (invariant.getLocation() != null) { inductiveLoc = (Location) invariant.getLocation().clone(); } else { inductiveLoc = (Location) stmt.getLocation().clone(); } inductiveLoc .setDetails("Inductive Case of Invariant of While Statement"); Utilities.setLocation(inductiveCase, inductiveLoc); ifStmtList.add(new ConfirmStmt(inductiveLoc, inductiveCase, simplifyInvariant)); // Confirm the termination of the loop. if (decreasingExp != null) { Location decreasingLoc = (Location) decreasingExp.getLocation().clone(); if (decreasingLoc != null) { decreasingLoc.setDetails("Termination of While Statement"); } // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(decreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp.copy(decreasingExp)); leftExp.setMathType(decreasingExp.getMathType()); Exp infixExp = Utilities.createLessThanEqExp(decreasingLoc, leftExp, Exp .copy(nqv), BOOLEAN); // Confirm NQV(RP, Cum_Dur) <= El_Dur_Exp if (nqv2 != null) { Location elapsedTimeLoc = (Location) elapsedTimeDur.getLocation().clone(); if (elapsedTimeLoc != null) { elapsedTimeLoc.setDetails("Termination of While Statement"); } Exp infixExp2 = Utilities.createLessThanEqExp(elapsedTimeLoc, Exp .copy(nqv2), Exp.copy(elapsedTimeDur), BOOLEAN); infixExp = myTypeGraph.formConjunct(infixExp, infixExp2); infixExp.setLocation(decreasingLoc); } ifStmtList.add(new ConfirmStmt(decreasingLoc, infixExp, false)); } else { throw new RuntimeException("No decreasing clause!"); } // empty elseif pair edu.clemson.cs.r2jt.collections.List<ConditionItem> elseIfPairList = new edu.clemson.cs.r2jt.collections.List<ConditionItem>(); // else body Location elseConfirmLoc; if (finalConfirm.getLocation() != null) { elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); } else { elseConfirmLoc = (Location) whileLoc.clone(); } edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); // NY YS // Form the confirm clause for the else Exp elseConfirm = Exp.copy(finalConfirm); if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(elseConfirm)), myTypeGraph.R, null); InfixExp sumWhileDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(elapsedTimeDur)); sumWhileDur.setMathType(myTypeGraph.R); elseConfirm = Utilities.replace(elseConfirm, cumDur, sumWhileDur); } elseStmtList.add(new ConfirmStmt(elseConfirmLoc, elseConfirm, simplifyFinalConfirm)); // condition ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); if (condition.getLocation() != null) { Location condLoc = (Location) condition.getLocation().clone(); condLoc.setDetails("While Loop Condition"); Utilities.setLocation(condition, condLoc); } // add it back to your assertive code IfStmt newIfStmt = new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); myCurrentAssertiveCode.addCode(newIfStmt); // Change our final confirm to "True" Exp trueVarExp = myTypeGraph.getTrueVarExp(); trueVarExp.setLocation((Location) whileLoc.clone()); myCurrentAssertiveCode.setFinalConfirm(trueVarExp, true); // Verbose Mode Debug Messages myVCBuffer.append("\nWhile Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } }
src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java
/** * VCGenerator.java * --------------------------------- * Copyright (c) 2015 * RESOLVE Software Research Group * School of Computing * Clemson University * All rights reserved. * --------------------------------- * This file is subject to the terms and conditions defined in * file 'LICENSE.txt', which is part of this source code package. */ package edu.clemson.cs.r2jt.vcgeneration; /* * Libraries */ import edu.clemson.cs.r2jt.ResolveCompiler; import edu.clemson.cs.r2jt.absyn.*; import edu.clemson.cs.r2jt.data.*; import edu.clemson.cs.r2jt.init.CompileEnvironment; import edu.clemson.cs.r2jt.misc.SourceErrorException; import edu.clemson.cs.r2jt.rewriteprover.VC; import edu.clemson.cs.r2jt.treewalk.TreeWalker; import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; import edu.clemson.cs.r2jt.typeandpopulate.*; import edu.clemson.cs.r2jt.typeandpopulate.entry.*; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTGeneric; import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; import edu.clemson.cs.r2jt.typeandpopulate.query.EntryTypeQuery; import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery; import edu.clemson.cs.r2jt.typereasoning.TypeGraph; import edu.clemson.cs.r2jt.misc.Flag; import edu.clemson.cs.r2jt.misc.FlagDependencies; import edu.clemson.cs.r2jt.vcgeneration.treewalkers.NestedFuncWalker; import java.io.File; import java.util.*; import java.util.List; /** * TODO: Write a description of this module */ public class VCGenerator extends TreeWalkerVisitor { // =========================================================== // Global Variables // =========================================================== // Symbol table related items private final MathSymbolTableBuilder mySymbolTable; private final TypeGraph myTypeGraph; private final MTType BOOLEAN; private final MTType MTYPE; private MTType Z; private ModuleScope myCurrentModuleScope; // Module level global variables private Exp myGlobalRequiresExp; private Exp myGlobalConstraintExp; // Operation/Procedure level global variables private OperationEntry myCurrentOperationEntry; private OperationProfileEntry myCurrentOperationProfileEntry; private Exp myOperationDecreasingExp; /** * <p>The current assertion we are applying * VC rules to.</p> */ private AssertiveCode myCurrentAssertiveCode; /** * <p>A map of facility instantiated types to a list of formal and actual constraints.</p> */ private final Map<VarExp, FacilityFormalToActuals> myInstantiatedFacilityArgMap; /** * <p>A list that will be built up with <code>AssertiveCode</code> * objects, each representing a VC or group of VCs that must be * satisfied to verify a parsed program.</p> */ private Collection<AssertiveCode> myFinalAssertiveCodeList; /** * <p>A stack that is used to keep track of the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<AssertiveCode> myIncAssertiveCodeStack; /** * <p>A stack that is used to keep track of the information that we * haven't printed for the <code>AssertiveCode</code> * that we still need to apply proof rules to.</p> */ private Stack<String> myIncAssertiveCodeStackInfo; /** * <p>The current compile environment used throughout * the compiler.</p> */ private CompileEnvironment myInstanceEnvironment; /** * <p>A map from representation types to their constraints.</p> */ private final Map<VarExp, Exp> myRepresentationConstraintMap; /** * <p>A map from representation types to their conventions.</p> */ private final Map<VarExp, Exp> myRepresentationConventionsMap; /** * <p>A map from representation types to their correspondence.</p> */ private final Map<VarExp, Exp> myRepresentationCorrespondenceMap; /** * <p>This object creates the different VC outputs.</p> */ private OutputVCs myOutputGenerator; /** * <p>This string buffer holds all the steps * the VC generator takes to generate VCs.</p> */ private StringBuffer myVCBuffer; // =========================================================== // Flag Strings // =========================================================== private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; private static final String FLAG_DESC_ATTPVCS_VC = "Generate Performance VCs"; // =========================================================== // Flags // =========================================================== public static final Flag FLAG_ALTVERIFY_VC = new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); public static final Flag FLAG_ALTPVCS_VC = new Flag(FLAG_ALTSECTION_NAME, "PVCs", FLAG_DESC_ATTPVCS_VC); public static final void setUpFlags() { FlagDependencies.addImplies(FLAG_ALTPVCS_VC, FLAG_ALTVERIFY_VC); } // =========================================================== // Constructors // =========================================================== public VCGenerator(ScopeRepository table, final CompileEnvironment env) { // Symbol table items mySymbolTable = (MathSymbolTableBuilder) table; myTypeGraph = mySymbolTable.getTypeGraph(); BOOLEAN = myTypeGraph.BOOLEAN; MTYPE = myTypeGraph.CLS; Z = null; // Current items myCurrentModuleScope = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; myOperationDecreasingExp = null; // Instance Environment myInstanceEnvironment = env; // VCs + Debugging String myCurrentAssertiveCode = null; myFinalAssertiveCodeList = new LinkedList<AssertiveCode>(); myIncAssertiveCodeStack = new Stack<AssertiveCode>(); myIncAssertiveCodeStackInfo = new Stack<String>(); myInstantiatedFacilityArgMap = new HashMap<VarExp, FacilityFormalToActuals>(); myRepresentationConstraintMap = new HashMap<VarExp, Exp>(); myRepresentationConventionsMap = new HashMap<VarExp, Exp>(); myRepresentationCorrespondenceMap = new HashMap<VarExp, Exp>(); myOutputGenerator = null; myVCBuffer = new StringBuffer(); } // =========================================================== // Visitor Methods // =========================================================== // ----------------------------------------------------------- // ConceptBodyModuleDec // ----------------------------------------------------------- @Override public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Concept Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Obtain the global type constraints from the module parameters Exp typeConstraints = getModuleTypeConstraint(dec.getLocation(), dec.getParameters()); if (!typeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = typeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(typeConstraints, myGlobalConstraintExp); } } // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); try { // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global type constraints from the Concept module parameters Exp conceptTypeConstraints = getModuleTypeConstraint(conceptModuleDec.getLocation(), conceptModuleDec.getParameters()); if (!conceptTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = conceptTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(conceptTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getConceptName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getConceptName().getLocation()); } } // ----------------------------------------------------------- // EnhancementBodyModuleDec // ----------------------------------------------------------- @Override public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Enhancement Realization Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n Enhancement Name:\t"); myVCBuffer.append(dec.getEnhancementName().getName()); myVCBuffer.append("\n Concept Name:\t"); myVCBuffer.append(dec.getConceptName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Obtain the global type constraints from the module parameters Exp typeConstraints = getModuleTypeConstraint(dec.getLocation(), dec.getParameters()); if (!typeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = typeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(typeConstraints, myGlobalConstraintExp); } } // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); try { // Obtain the global requires clause from the Concept ConceptModuleDec conceptModuleDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); Exp conceptRequires = getRequiresClause(conceptModuleDec.getLocation(), conceptModuleDec); if (!conceptRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = conceptRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, conceptRequires); } } // Obtain the global type constraints from the Concept module parameters Exp conceptTypeConstraints = getModuleTypeConstraint(conceptModuleDec.getLocation(), conceptModuleDec.getParameters()); if (!conceptTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = conceptTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct(conceptTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getConceptName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getConceptName().getLocation()); } try { // Obtain the global requires clause from the Enhancement EnhancementModuleDec enhancementModuleDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getEnhancementName() .getName())).getDefiningElement(); Exp enhancementRequires = getRequiresClause(enhancementModuleDec.getLocation(), enhancementModuleDec); if (!enhancementRequires.isLiteralTrue()) { if (myGlobalRequiresExp.isLiteralTrue()) { myGlobalRequiresExp = enhancementRequires; } else { myGlobalRequiresExp = myTypeGraph.formConjunct(myGlobalRequiresExp, enhancementRequires); } } // Obtain the global type constraints from the Concept module parameters Exp enhancementTypeConstraints = getModuleTypeConstraint(enhancementModuleDec.getLocation(), enhancementModuleDec.getParameters()); if (!enhancementTypeConstraints.isLiteralTrue()) { if (myGlobalConstraintExp.isLiteralTrue()) { myGlobalConstraintExp = enhancementTypeConstraints; } else { myGlobalConstraintExp = myTypeGraph.formConjunct( enhancementTypeConstraints, myGlobalConstraintExp); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getEnhancementName().getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getEnhancementName().getLocation()); } } // ----------------------------------------------------------- // FacilityDec // ----------------------------------------------------------- @Override public void postFacilityDec(FacilityDec dec) { // Applies the facility declaration rule. // Since this is a local facility, we will need to add // it to our incomplete assertive code stack. applyFacilityDeclRule(dec, true); // Loop through assertive code stack loopAssertiveCodeStack(); } // ----------------------------------------------------------- // FacilityModuleDec // ----------------------------------------------------------- @Override public void preFacilityModuleDec(FacilityModuleDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" VC Generation Details "); myVCBuffer.append(" =========================\n"); myVCBuffer.append("\n Facility Name:\t"); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append("\n"); myVCBuffer.append("\n===================================="); myVCBuffer.append("======================================\n"); myVCBuffer.append("\n"); // From the list of imports, obtain the global constraints // of the imported modules. myGlobalConstraintExp = getConstraints(dec.getLocation(), myCurrentModuleScope .getImports()); // Store the global requires clause myGlobalRequiresExp = getRequiresClause(dec.getLocation(), dec); } // ----------------------------------------------------------- // FacilityOperationDec // ----------------------------------------------------------- @Override public void preFacilityOperationDec(FacilityOperationDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postFacilityOperationDec(FacilityOperationDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation Location loc = dec.getLocation(); String name = dec.getName().getName(); OperationDec opDec = new OperationDec(dec.getName(), dec.getParameters(), dec .getReturnTy(), dec.getStateVars(), dec.getRequires(), dec.getEnsures()); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, dec), loc, myCurrentAssertiveCode, opDec, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, dec), loc, opDec, isLocal); List<Statement> statementList = dec.getStatements(); List<ParameterVarDec> parameterVarList = dec.getParameters(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, parameterVarList, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // ModuleDec // ----------------------------------------------------------- @Override public void preModuleDec(ModuleDec dec) { // Set the current module scope try { myCurrentModuleScope = mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); // Get "Z" from the TypeGraph Z = Utilities.getMathTypeZ(dec.getLocation(), myCurrentModuleScope); // Apply the facility declaration rule to imported facility declarations. List<SymbolTableEntry> results = myCurrentModuleScope .query(new EntryTypeQuery<SymbolTableEntry>( FacilityEntry.class, MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE)); for (SymbolTableEntry s : results) { if (s.getSourceModuleIdentifier().compareTo( myCurrentModuleScope.getModuleIdentifier()) != 0) { // Do all the facility declaration logic, but don't add this // to our incomplete assertive code stack. We shouldn't need to // verify facility declarations that are imported. FacilityDec facDec = (FacilityDec) s.toFacilityEntry(dec.getLocation()) .getDefiningElement(); applyFacilityDeclRule(facDec, false); } } } catch (NoSuchSymbolException e) { System.err.println("Module " + dec.getName() + " does not exist or is not in scope."); Utilities.noSuchModule(dec.getLocation()); } } @Override public void postModuleDec(ModuleDec dec) { // Create the output generator and finalize output myOutputGenerator = new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, myVCBuffer); // Check if it is generating VCs for WebIDE or not. if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { myOutputGenerator.outputToJSON(); } else { // Print to file if we are in debug mode // TODO: Add debug flag here String filename; if (myInstanceEnvironment.getOutputFilename() != null) { filename = myInstanceEnvironment.getOutputFilename(); } else { filename = createVCFileName(); } myOutputGenerator.outputToFile(filename); } // Set the module level global variables to null myCurrentModuleScope = null; myGlobalConstraintExp = null; myGlobalRequiresExp = null; } // ----------------------------------------------------------- // ProcedureDec // ----------------------------------------------------------- @Override public void preProcedureDec(ProcedureDec dec) { // Keep the current operation dec List<PTType> argTypes = new LinkedList<PTType>(); for (ParameterVarDec p : dec.getParameters()) { argTypes.add(p.getTy().getProgramTypeValue()); } myCurrentOperationEntry = Utilities.searchOperation(dec.getLocation(), null, dec .getName(), argTypes, myCurrentModuleScope); // Obtain the performance duration clause if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { myCurrentOperationProfileEntry = Utilities.searchOperationProfile(dec.getLocation(), null, dec.getName(), argTypes, myCurrentModuleScope); } } @Override public void postProcedureDec(ProcedureDec dec) { // Verbose Mode Debug Messages myVCBuffer.append("\n========================="); myVCBuffer.append(" Procedure: "); myVCBuffer.append(dec.getName().getName()); myVCBuffer.append(" =========================\n"); // The current assertive code myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtains items from the current operation OperationDec opDec = (OperationDec) myCurrentOperationEntry.getDefiningElement(); Location loc = dec.getLocation(); String name = dec.getName().getName(); boolean isLocal = Utilities.isLocationOperation(dec.getName().getName(), myCurrentModuleScope); Exp requires = modifyRequiresClause(getRequiresClause(loc, opDec), loc, myCurrentAssertiveCode, opDec, isLocal); Exp ensures = modifyEnsuresClause(getEnsuresClause(loc, opDec), loc, opDec, isLocal); List<Statement> statementList = dec.getStatements(); List<ParameterVarDec> parameterVarList = dec.getParameters(); List<VarDec> variableList = dec.getAllVariables(); Exp decreasing = dec.getDecreasing(); Exp procDur = null; Exp varFinalDur = null; // NY YS if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { procDur = myCurrentOperationProfileEntry.getDurationClause(); // Loop through local variables to get their finalization duration for (VarDec v : dec.getVariables()) { Exp finalVarDur = Utilities.createFinalizAnyDur(v, BOOLEAN); // Create/Add the duration expression if (varFinalDur == null) { varFinalDur = finalVarDur; } else { varFinalDur = new InfixExp((Location) loc.clone(), varFinalDur, Utilities.createPosSymbol("+"), finalVarDur); } varFinalDur.setMathType(myTypeGraph.R); } } // Apply the procedure declaration rule applyProcedureDeclRule(loc, name, requires, ensures, decreasing, procDur, varFinalDur, parameterVarList, variableList, statementList, isLocal); // Add this to our stack of to be processed assertive codes. myIncAssertiveCodeStack.push(myCurrentAssertiveCode); myIncAssertiveCodeStackInfo.push(""); // Set the current assertive code to null // YS: (We the modify requires and ensures clause needs to have // and current assertive code to work. Not very clean way to // solve the problem, but should work.) myCurrentAssertiveCode = null; // Loop through assertive code stack loopAssertiveCodeStack(); myOperationDecreasingExp = null; myCurrentOperationEntry = null; myCurrentOperationProfileEntry = null; } // ----------------------------------------------------------- // RepresentationDec // ----------------------------------------------------------- @Override public void postRepresentationDec(RepresentationDec dec) { // Applies the initialization rule applyInitializationRule(dec); // Applies the correspondence rule applyCorrespondenceRule(dec); // Loop through assertive code stack loopAssertiveCodeStack(); } // =========================================================== // Public Methods // =========================================================== // ----------------------------------------------------------- // Prover Mode // ----------------------------------------------------------- /** * <p>The set of immmutable VCs that the in house provers can use.</p> * * @return VCs to be proved. */ public List<VC> proverOutput() { return myOutputGenerator.getProverOutput(); } // =========================================================== // Private Methods // =========================================================== /** * <p>Loop through the list of <code>VarDec</code>, search * for their corresponding <code>ProgramVariableEntry</code> * and add the result to the list of free variables.</p> * * @param variableList List of the all variables as * <code>VarDec</code>. */ private void addVarDecsAsFreeVars(List<VarDec> variableList) { // Loop through the variable list for (VarDec v : variableList) { myCurrentAssertiveCode.addFreeVar(Utilities.createVarExp(v .getLocation(), null, v.getName(), v.getTy() .getMathTypeValue(), null)); } } /** * <p>Converts each actual programming expression into their mathematical * counterparts. It is possible that the passed in programming expression * contains nested function calls, therefore we will need to obtain all the * requires clauses from the different calls and add it as a confirm statement * in our current assertive code.</p> * * @param assertiveCode Current assertive code. * @param actualParams The list of actual parameter arguments. * * @return A list containing the newly created mathematical expression. */ private List<Exp> createModuleActualArgExpList(AssertiveCode assertiveCode, List<ModuleArgumentItem> actualParams) { List<Exp> retExpList = new ArrayList<Exp>(); for (ModuleArgumentItem item : actualParams) { // Obtain the math type for the module argument item MTType type; if (item.getProgramTypeValue() != null) { type = item.getProgramTypeValue().toMath(); } else { type = item.getMathType(); } // Convert the module argument items into math expressions Exp expToUse; if (item.getName() != null) { expToUse = Utilities.createVarExp(item.getLocation(), item .getQualifier(), item.getName(), type, null); } else { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. ProgramExp p = item.getEvalExp(); if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(null, null, mySymbolTable, myCurrentModuleScope, assertiveCode, myInstantiatedFacilityArgMap); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { assertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Use the modified ensures clause as the new expression we want // to replace. expToUse = nfw.getEnsuresClause(); } // For all other types of arguments, simply convert it to a // math expression. else { expToUse = Utilities.convertExp(p, myCurrentModuleScope); } } // Add this to our return list retExpList.add(expToUse); } return retExpList; } /** * <p>Converts each module's formal argument into variable expressions. This is only * possible if the argument is of type <code>ConstantParamDec</code>. All other types * are simply ignored and has mapped value of <code>null</code>.</p> * * @param formalParams The formal parameter list for a <code>ModuleDec</code>. * * @return A list containing the newly created variable expression. */ private List<Exp> createModuleFormalArgExpList( List<ModuleParameterDec> formalParams) { List<Exp> retExpList = new ArrayList<Exp>(); // Create a variable expression for each of the module arguments // and put it in our map. for (ModuleParameterDec dec : formalParams) { Dec wrappedDec = dec.getWrappedDec(); // Only do this for constant parameter and operation declarations // We don't really care about type declarations or definitions. Exp newExp; if (wrappedDec instanceof ConstantParamDec || wrappedDec instanceof ConceptTypeParamDec) { newExp = Utilities.createVarExp(wrappedDec.getLocation(), null, wrappedDec.getName(), wrappedDec.getMathType(), null); } else if (wrappedDec instanceof OperationDec) { OperationDec opDec = (OperationDec) wrappedDec; newExp = Utilities.createVarExp(wrappedDec.getLocation(), null, opDec.getName(), dec.getMathType(), null); } else { newExp = null; } // Store the result retExpList.add(newExp); } return retExpList; } /** * <p>Creates the name of the output file.</p> * * @return Name of the file */ private String createVCFileName() { File file = myInstanceEnvironment.getTargetFile(); ModuleID cid = myInstanceEnvironment.getModuleID(file); file = myInstanceEnvironment.getFile(cid); String filename = file.toString(); int temp = filename.indexOf("."); String tempfile = filename.substring(0, temp); String mainFileName; mainFileName = tempfile + ".asrt_new"; return mainFileName; } /** * <p>This is a helper method that checks to see if the given assume expression * can be used to prove our confirm expression. This is done by finding the * intersection between the set of symbols in the assume expression and * the set of symbols in the confirm expression.</p> * * <p>If the assume expressions are part of a stipulate assume clause, * then we keep all the assume expressions no matter what.</p> * * <p>If it is not a stipulate assume clause, we loop though keep looping through * all the assume expressions until we can't form another implies.</p> * * @param confirmExp The current confirm expression. * @param remAssumeExpList The list of remaining assume expressions. * @param isStipulate Whether or not the assume expression is an stipulate assume expression. * * @return The modified confirm expression. */ private Exp formImplies(Exp confirmExp, List<Exp> remAssumeExpList, boolean isStipulate) { // If it is stipulate clause, keep it no matter what if (isStipulate) { for (Exp assumeExp : remAssumeExpList) { confirmExp = myTypeGraph.formImplies(Exp.copy(assumeExp), Exp .copy(confirmExp)); } } else { boolean checkList = false; if (remAssumeExpList.size() > 0) { checkList = true; } // Loop until we no longer add more expressions or we have added all // expressions in the remaining assume expression list. while (checkList) { List<Exp> tmpExpList = new ArrayList<Exp>(); boolean formedImplies = false; for (Exp assumeExp : remAssumeExpList) { // Create a new implies expression if there are common symbols // in the assume and in the confirm. (Parsimonious step) Set<String> intersection = Utilities.getSymbols(confirmExp); intersection.retainAll(Utilities.getSymbols(assumeExp)); if (!intersection.isEmpty()) { // Don't form implies if we have "Assume true" if (!assumeExp.isLiteralTrue()) { confirmExp = myTypeGraph.formImplies( Exp.copy(assumeExp), Exp .copy(confirmExp)); formedImplies = true; } } else { // Form implies if we have "Assume false" if (assumeExp.isLiteralFalse()) { confirmExp = myTypeGraph.formImplies( Exp.copy(assumeExp), Exp .copy(confirmExp)); formedImplies = true; } else { tmpExpList.add(assumeExp); } } } remAssumeExpList = tmpExpList; if (remAssumeExpList.size() > 0) { // Check to see if we formed an implication if (formedImplies) { // Loop again to see if we can form any more implications checkList = true; } else { // If no implications are formed, then none of the remaining // expressions will be helpful. checkList = false; } } else { // Since we are done with all assume expressions, we can quit // out of the loop. checkList = false; } } } return confirmExp; } /** * <p>A helper method to deal with operations as parameters.</p> * * @param loc Location of some facility declaration. * @param assertiveCode The current assertive code. * @param formalParams The formal parameters. * @param actualParams The actual parameters. * @param conceptFormalParamExp The concept formal parameter expression. * @param conceptActualParamExp The concept actual parameter expression. * @param conceptRealizFormalParamExp The concept realization formal parameter expression. * @param conceptRealizActualParamExp The concept realization actual parameter expression. * @param enhancementFormalParamExp The enhancement formal parameter expression. * @param enhancementActualParamExp The enhancement actual parameter expression. * @param enhancementRealizFormalParamExp The enhancement realization formal parameter expression. * @param enhancementRealizActualParamExp The enhancement realization actual parameter expression. * @return */ private AssertiveCode facilityDeclOperationParamHelper(Location loc, AssertiveCode assertiveCode, List<ModuleParameterDec> formalParams, List<ModuleArgumentItem> actualParams, List<Exp> conceptFormalParamExp, List<Exp> conceptActualParamExp, List<Exp> conceptRealizFormalParamExp, List<Exp> conceptRealizActualParamExp, List<Exp> enhancementFormalParamExp, List<Exp> enhancementActualParamExp, List<Exp> enhancementRealizFormalParamExp, List<Exp> enhancementRealizActualParamExp) { AssertiveCode copyAssertiveCode = new AssertiveCode(assertiveCode); Iterator<ModuleParameterDec> realizParameterIt = formalParams.iterator(); Iterator<ModuleArgumentItem> realizArgumentItemIt = actualParams.iterator(); while (realizParameterIt.hasNext() && realizArgumentItemIt.hasNext()) { ModuleParameterDec moduleParameterDec = realizParameterIt.next(); ModuleArgumentItem moduleArgumentItem = realizArgumentItemIt.next(); if (moduleParameterDec.getWrappedDec() instanceof OperationDec) { // Formal operation OperationDec formalOperationDec = (OperationDec) moduleParameterDec.getWrappedDec(); boolean isFormalOpDecLocal = Utilities.isLocationOperation(formalOperationDec .getName().getName(), myCurrentModuleScope); Exp formalOperationRequires = getRequiresClause(formalOperationDec.getLocation(), formalOperationDec); Exp formalOperationEnsures = getEnsuresClause(formalOperationDec.getLocation(), formalOperationDec); // Construct a list of formal parameters as expressions // for substitution purposes. List<ParameterVarDec> formalParameterVarDecs = formalOperationDec.getParameters(); List<Exp> formalParamAsExp = new ArrayList<Exp>(); for (ParameterVarDec varDec : formalParameterVarDecs) { Ty varDecTy = varDec.getTy(); // varDec as VarExp VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), varDecTy.getMathType(), null); formalParamAsExp.add(varDecExp); // #varDec as OldExp OldExp oldVarDecExp = new OldExp(varDec.getLocation(), Exp .copy(varDecExp)); formalParamAsExp.add(oldVarDecExp); } if (formalOperationDec.getReturnTy() != null) { Ty varDecTy = formalOperationDec.getReturnTy(); formalParamAsExp.add(Utilities.createVarExp(varDecTy .getLocation(), null, formalOperationDec.getName(), varDecTy.getMathType(), null)); } // Locate the corresponding actual operation OperationDec actualOperationDec = null; List<Exp> actualParamAsExp = new ArrayList<Exp>(); try { OperationEntry op = myCurrentModuleScope .queryForOne( new NameQuery( moduleArgumentItem .getQualifier(), moduleArgumentItem .getName(), MathSymbolTable.ImportStrategy.IMPORT_NAMED, MathSymbolTable.FacilityStrategy.FACILITY_INSTANTIATE, true)) .toOperationEntry(loc); if (op.getDefiningElement() instanceof OperationDec) { actualOperationDec = (OperationDec) op.getDefiningElement(); } else { FacilityOperationDec fOpDec = (FacilityOperationDec) op.getDefiningElement(); actualOperationDec = new OperationDec(fOpDec.getName(), fOpDec .getParameters(), fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec .getRequires(), fOpDec .getEnsures()); } // Construct a list of actual parameters as expressions // for substitution purposes. List<ParameterVarDec> parameterVarDecs = actualOperationDec.getParameters(); for (ParameterVarDec varDec : parameterVarDecs) { Ty varDecTy = varDec.getTy(); // varDec as VarExp VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), varDecTy .getMathType(), null); actualParamAsExp.add(varDecExp); // #varDec as OldExp OldExp oldVarDecExp = new OldExp(varDec.getLocation(), Exp .copy(varDecExp)); actualParamAsExp.add(oldVarDecExp); } // TODO: Move this to the populator opAsParameterSanityCheck(moduleArgumentItem.getLocation(), formalParameterVarDecs, parameterVarDecs); // Add any return types as something we need to replace if (actualOperationDec.getReturnTy() != null) { Ty varDecTy = actualOperationDec.getReturnTy(); actualParamAsExp.add(Utilities.createVarExp(varDecTy .getLocation(), null, actualOperationDec .getName(), varDecTy.getMathType(), null)); } } catch (NoSuchSymbolException nsse) { Utilities.noSuchSymbol(moduleArgumentItem.getQualifier(), moduleArgumentItem.getName().getName(), loc); } catch (DuplicateSymbolException dse) { //This should be caught earlier, when the duplicate operation is //created throw new RuntimeException(dse); } Exp actualOperationRequires = getRequiresClause(moduleArgumentItem.getLocation(), actualOperationDec); Exp actualOperationEnsures = getEnsuresClause(moduleArgumentItem.getLocation(), actualOperationDec); // Facility Decl Rule (Operations as Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP Exp formalRequires = modifyRequiresClause(formalOperationRequires, moduleParameterDec.getLocation(), copyAssertiveCode, formalOperationDec, isFormalOpDecLocal); formalRequires = replaceFacilityDeclarationVariables(formalRequires, conceptFormalParamExp, conceptActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, conceptRealizFormalParamExp, conceptRealizActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, enhancementFormalParamExp, enhancementActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, enhancementRealizFormalParamExp, enhancementRealizActualParamExp); formalRequires = replaceFacilityDeclarationVariables(formalRequires, formalParamAsExp, actualParamAsExp); if (!actualOperationRequires .equals(myTypeGraph.getTrueVarExp())) { Location newLoc = (Location) actualOperationRequires.getLocation() .clone(); newLoc.setDetails("Requires Clause of " + formalOperationDec.getName().getName() + " implies the Requires Clause of " + actualOperationDec.getName().getName() + " in Facility Instantiation Rule"); Exp newConfirmExp; if (!formalRequires.equals(myTypeGraph.getTrueVarExp())) { newConfirmExp = myTypeGraph.formImplies(formalRequires, actualOperationRequires); } else { newConfirmExp = actualOperationRequires; } Utilities.setLocation(newConfirmExp, newLoc); copyAssertiveCode.addConfirm(newLoc, newConfirmExp, false); } // Facility Decl Rule (Operations as Parameters): // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] Exp formalEnsures = modifyEnsuresClause(formalOperationEnsures, moduleParameterDec.getLocation(), formalOperationDec, isFormalOpDecLocal); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, conceptFormalParamExp, conceptActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, conceptRealizFormalParamExp, conceptRealizActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, enhancementFormalParamExp, enhancementActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, enhancementRealizFormalParamExp, enhancementRealizActualParamExp); formalEnsures = replaceFacilityDeclarationVariables(formalEnsures, formalParamAsExp, actualParamAsExp); if (!formalEnsures.equals(myTypeGraph.getTrueVarExp())) { Location newLoc = (Location) actualOperationEnsures.getLocation() .clone(); newLoc.setDetails("Ensures Clause of " + actualOperationDec.getName().getName() + " implies the Ensures Clause of " + formalOperationDec.getName().getName() + " in Facility Instantiation Rule"); Exp newConfirmExp; if (!actualOperationEnsures.equals(myTypeGraph .getTrueVarExp())) { newConfirmExp = myTypeGraph.formImplies(actualOperationEnsures, formalEnsures); } else { newConfirmExp = formalEnsures; } Utilities.setLocation(newConfirmExp, newLoc); copyAssertiveCode.addConfirm(newLoc, newConfirmExp, false); } } } return copyAssertiveCode; } /** * <p>This method iterates through each of the assume expressions. * If the expression is a replaceable equals expression, it will substitute * all instances of the expression in the rest of the assume expression * list and in the confirm expression list.</p> * * <p>When it is not a replaceable expression, we apply a step to generate * parsimonious VCs.</p> * * @param confirmExpList The list of conjunct confirm expressions. * @param assumeExpList The list of conjunct assume expressions. * @param isStipulate Boolean to indicate whether it is a stipulate assume * clause and we need to keep the assume statement. * * @return The modified confirm statement expression in <code>Exp/code> form. */ private Exp formParsimoniousVC(List<Exp> confirmExpList, List<Exp> assumeExpList, boolean isStipulate) { // Loop through each confirm expression for (int i = 0; i < confirmExpList.size(); i++) { Exp currentConfirmExp = confirmExpList.get(i); // Make a deep copy of the assume expression list List<Exp> assumeExpCopyList = new ArrayList<Exp>(); for (Exp assumeExp : assumeExpList) { assumeExpCopyList.add(Exp.copy(assumeExp)); } // Stores the remaining assume expressions // we have not substituted. Note that if the expression // is part of a stipulate assume statement, we keep // the assume no matter what. List<Exp> remAssumeExpList = new ArrayList<Exp>(); // Loop through each assume expression for (int j = 0; j < assumeExpCopyList.size(); j++) { Exp currentAssumeExp = assumeExpCopyList.get(j); Exp tmp; boolean hasVerificationVar = false; boolean isConceptualVar = false; boolean doneReplacement = false; // Attempts to simplify equality expressions if (currentAssumeExp instanceof EqualsExp && ((EqualsExp) currentAssumeExp).getOperator() == EqualsExp.EQUAL) { EqualsExp equalsExp = (EqualsExp) currentAssumeExp; boolean isLeftReplaceable = Utilities.containsReplaceableExp(equalsExp .getLeft()); boolean isRightReplaceable = Utilities.containsReplaceableExp(equalsExp .getRight()); // Check to see if we have P_val or Cum_Dur if (equalsExp.getLeft() instanceof VarExp) { if (((VarExp) equalsExp.getLeft()).getName().getName() .matches("\\?*P_val") || ((VarExp) equalsExp.getLeft()).getName() .getName().matches("\\?*Cum_Dur")) { hasVerificationVar = true; } } // Check to see if we have Conc.[expression] else if (equalsExp.getLeft() instanceof DotExp) { DotExp tempLeft = (DotExp) equalsExp.getLeft(); isConceptualVar = tempLeft.containsVar("Conc", false); } // Check if both the left and right are replaceable if (isLeftReplaceable && isRightReplaceable) { // Only check for verification variable on the left // hand side. If that is the case, we know the // right hand side is the only one that makes sense // in the current context, therefore we do the // substitution. if (hasVerificationVar || isConceptualVar) { tmp = Utilities.replace(currentConfirmExp, equalsExp.getLeft(), equalsExp .getRight()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { // Replace all instances of the left side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList .get(k), equalsExp .getLeft(), equalsExp .getRight()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the left side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList .size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList .get(k), equalsExp .getLeft(), equalsExp .getRight()); assumeExpCopyList.set(k, newAssumeExp); } doneReplacement = true; } } else { // Don't do any substitutions, we don't know // which makes sense in the current context. tmp = currentConfirmExp; } } // Check if left hand side is replaceable else if (isLeftReplaceable) { // Create a temp expression where left is replaced with the right tmp = Utilities.replace(currentConfirmExp, equalsExp .getLeft(), equalsExp.getRight()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { doneReplacement = true; } // Replace all instances of the left side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList.get(k), equalsExp.getLeft(), equalsExp .getRight()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the left side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList.size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList.get(k), equalsExp.getLeft(), equalsExp .getRight()); assumeExpCopyList.set(k, newAssumeExp); } } // Only right hand side is replaceable else if (isRightReplaceable) { // Create a temp expression where right is replaced with the left tmp = Utilities.replace(currentConfirmExp, equalsExp .getRight(), equalsExp.getLeft()); // Check to see if something has been replaced if (!tmp.equals(currentConfirmExp)) { doneReplacement = true; } // Replace all instances of the right side in // the assume expressions we have already processed. for (int k = 0; k < remAssumeExpList.size(); k++) { Exp newAssumeExp = Utilities.replace(remAssumeExpList.get(k), equalsExp.getRight(), equalsExp .getLeft()); remAssumeExpList.set(k, newAssumeExp); } // Replace all instances of the right side in // the assume expressions we haven't processed. for (int k = j + 1; k < assumeExpCopyList.size(); k++) { Exp newAssumeExp = Utilities.replace(assumeExpCopyList.get(k), equalsExp.getRight(), equalsExp .getLeft()); assumeExpCopyList.set(k, newAssumeExp); } } // Both sides are not replaceable else { tmp = currentConfirmExp; } } else { tmp = currentConfirmExp; } // Check to see if this is a stipulate assume clause // If yes, we keep a copy of the current // assume expression. if (isStipulate) { remAssumeExpList.add(Exp.copy(currentAssumeExp)); } else { // Update the current confirm expression // if we did a replacement. if (doneReplacement) { currentConfirmExp = tmp; } else { // Check to see if this a verification // variable. If yes, we don't keep this assume. // Otherwise, we need to store this for the // step that generates the parsimonious vcs. if (!hasVerificationVar) { remAssumeExpList.add(Exp.copy(currentAssumeExp)); } } } } // Use the remaining assume expression list // Create a new implies expression if there are common symbols // in the assume and in the confirm. (Parsimonious step) Exp newConfirmExp = formImplies(currentConfirmExp, remAssumeExpList, isStipulate); confirmExpList.set(i, newConfirmExp); } // Form the return confirm statement Exp retExp = myTypeGraph.getTrueVarExp(); for (Exp e : confirmExpList) { if (retExp.isLiteralTrue()) { retExp = e; } else { retExp = myTypeGraph.formConjunct(retExp, e); } } return retExp; } /** * <p>Returns all the constraint clauses combined together for the * for the current <code>ModuleDec</code>.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param imports The list of imported modules. * * @return The constraint clause <code>Exp</code>. */ private Exp getConstraints(Location loc, List<ModuleIdentifier> imports) { Exp retExp = null; List<String> importedConceptName = new LinkedList<String>(); // Loop for (ModuleIdentifier mi : imports) { try { ModuleDec dec = mySymbolTable.getModuleScope(mi).getDefiningElement(); List<Exp> contraintExpList = null; // Handling for facility imports if (dec instanceof ShortFacilityModuleDec) { FacilityDec facDec = ((ShortFacilityModuleDec) dec).getDec(); dec = mySymbolTable.getModuleScope( new ModuleIdentifier(facDec .getConceptName().getName())) .getDefiningElement(); } if (dec instanceof ConceptModuleDec && !importedConceptName.contains(dec.getName() .getName())) { contraintExpList = ((ConceptModuleDec) dec).getConstraints(); // Copy all the constraints for (Exp e : contraintExpList) { // Deep copy and set the location detail Exp constraint = Exp.copy(e); if (constraint.getLocation() != null) { Location theLoc = constraint.getLocation(); theLoc.setDetails("Constraint of Module: " + dec.getName()); Utilities.setLocation(constraint, theLoc); } // Form conjunct if needed. if (retExp == null) { retExp = Exp.copy(e); } else { retExp = myTypeGraph.formConjunct(retExp, Exp .copy(e)); } } // Avoid importing constraints for the same concept twice importedConceptName.add(dec.getName().getName()); } } catch (NoSuchSymbolException e) { System.err.println("Module " + mi.toString() + " does not exist or is not in scope."); Utilities.noSuchModule(loc); } } return retExp; } /** * <p>Returns the ensures clause for the current <code>Dec</code>.</p> * * @param location The location of the ensures clause. * @param dec The corresponding <code>Dec</code>. * * @return The ensures clause <code>Exp</code>. */ private Exp getEnsuresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp ensures = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { ensures = ((FacilityOperationDec) dec).getEnsures(); } else if (dec instanceof OperationDec) { ensures = ((OperationDec) dec).getEnsures(); } // Deep copy and fill in the details of this location if (ensures != null) { retExp = Exp.copy(ensures); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Ensures Clause of " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Returns all the constraint clauses combined together for the * for the list of module parameters.</p> * * @param loc The location of the <code>ModuleDec</code>. * @param moduleParameterDecs The list of parameter for this module. * * @return The constraint clause <code>Exp</code>. */ private Exp getModuleTypeConstraint(Location loc, List<ModuleParameterDec> moduleParameterDecs) { Exp retVal = myTypeGraph.getTrueVarExp(); for (ModuleParameterDec m : moduleParameterDecs) { Dec wrappedDec = m.getWrappedDec(); if (wrappedDec instanceof ConstantParamDec) { ConstantParamDec dec = (ConstantParamDec) wrappedDec; ProgramTypeEntry typeEntry; if (dec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) dec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(dec.getLocation(), null, dec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type.getExemplar(), typeEntry .getModelType(), null); // Deep copy the original constraint clause Exp constraint = Exp.copy(type.getConstraint()); constraint = Utilities.replace(constraint, exemplar, varDecExp); // Conjunct to our other constraints (if any) if (!constraint.isLiteralTrue()) { if (retVal.isLiteralTrue()) { retVal = constraint; } else { retVal = myTypeGraph.formConjunct(retVal, constraint); } } } } else { Utilities.tyNotHandled(dec.getTy(), loc); } } } return retVal; } /** * <p>Returns the requires clause for the current <code>Dec</code>.</p> * * @param location The location of the requires clause. * @param dec The corresponding <code>Dec</code>. * * @return The requires clause <code>Exp</code>. */ private Exp getRequiresClause(Location location, Dec dec) { PosSymbol name = dec.getName(); Exp requires = null; Exp retExp; // Check for each kind of ModuleDec possible if (dec instanceof FacilityOperationDec) { requires = ((FacilityOperationDec) dec).getRequires(); } else if (dec instanceof OperationDec) { requires = ((OperationDec) dec).getRequires(); } else if (dec instanceof ConceptModuleDec) { requires = ((ConceptModuleDec) dec).getRequirement(); } else if (dec instanceof ConceptBodyModuleDec) { requires = ((ConceptBodyModuleDec) dec).getRequires(); } else if (dec instanceof EnhancementModuleDec) { requires = ((EnhancementModuleDec) dec).getRequirement(); } else if (dec instanceof EnhancementBodyModuleDec) { requires = ((EnhancementBodyModuleDec) dec).getRequires(); } else if (dec instanceof FacilityModuleDec) { requires = ((FacilityModuleDec) dec).getRequirement(); } // Deep copy and fill in the details of this location if (requires != null) { retExp = Exp.copy(requires); } else { retExp = myTypeGraph.getTrueVarExp(); } if (location != null) { Location loc = (Location) location.clone(); loc.setDetails("Requires Clause for " + name); Utilities.setLocation(retExp, loc); } return retExp; } /** * <p>Loop through our stack of incomplete assertive codes.</p> */ private void loopAssertiveCodeStack() { // Loop until our to process assertive code stack is empty while (!myIncAssertiveCodeStack.empty()) { // Set the incoming assertive code as our current assertive // code we are working on. myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Append any information that still needs to be added to our // Debug VC Buffer myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); // Apply proof rules applyRules(); myVCBuffer.append("\n***********************"); myVCBuffer.append("***********************\n"); // Add it to our list of final assertive codes ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); if (!confirmStmt.getAssertion().isLiteralTrue()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } else { // Only add true if it is a goal we want to show up. if (!confirmStmt.getSimplify()) { myFinalAssertiveCodeList.add(myCurrentAssertiveCode); } } // Set the current assertive code to null myCurrentAssertiveCode = null; } } /** * <p>Modify the argument expression list if we have a * nested function call.</p> * * @param callArgs The original list of arguments. * * @return The modified list of arguments. */ private List<Exp> modifyArgumentList(List<ProgramExp> callArgs) { // Find all the replacements that needs to happen to the requires // and ensures clauses List<Exp> replaceArgs = new ArrayList<Exp>(); for (ProgramExp p : callArgs) { // Check for nested function calls in ProgramDotExp // and ProgramParamExp. if (p instanceof ProgramDotExp || p instanceof ProgramParamExp) { NestedFuncWalker nfw = new NestedFuncWalker(myCurrentOperationEntry, myOperationDecreasingExp, mySymbolTable, myCurrentModuleScope, myCurrentAssertiveCode, myInstantiatedFacilityArgMap); TreeWalker tw = new TreeWalker(nfw); tw.visit(p); // Add the requires clause as something we need to confirm Exp pRequires = nfw.getRequiresClause(); if (!pRequires.isLiteralTrue()) { myCurrentAssertiveCode.addConfirm(pRequires.getLocation(), pRequires, false); } // Add the modified ensures clause as the new expression we want // to replace in the CallStmt's ensures clause. replaceArgs.add(nfw.getEnsuresClause()); } // For all other types of arguments, simply add it to the list to be replaced else { replaceArgs.add(p); } } return replaceArgs; } /** * <p>Modifies the ensures clause based on the parameter mode.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation * @param opName The name of the operation. * @param parameterVarDecList The list of parameter variables for the operation. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, String opName, List<ParameterVarDec> parameterVarDecList, boolean isLocal) { // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); // Exp form of the parameter variable VarExp parameterExp = new VarExp(p.getLocation(), null, p.getName().copy()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Create an old exp (#parameterExp) OldExp oldParameterExp = new OldExp(p.getLocation(), Exp.copy(parameterExp)); oldParameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste .toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Restores mode // TODO: Preserves mode needs to be syntaticlly checked. if (p.getMode() == Mode.RESTORES) { // Set the details for the new location Location restoresLoc; if (ensures != null && ensures.getLocation() != null) { Location enLoc = ensures.getLocation(); restoresLoc = ((Location) enLoc.clone()); } else { restoresLoc = ((Location) opLocation.clone()); restoresLoc.setDetails("Ensures Clause of " + opName); } restoresLoc.setDetails(restoresLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); // Need to ensure here that the everything inside the type family // is restored at the end of the operation. Exp restoresConditionExp = null; if (typeEntry.getModelType() instanceof MTCartesian) { MTCartesian cartesian = (MTCartesian) typeEntry.getModelType(); List<MTType> elementTypes = cartesian.getComponentTypes(); for (int i = 0; i < cartesian.size(); i++) { // Retrieve the information on each cartesian product element PosSymbol name = Utilities.createPosSymbol(cartesian .getTag(i)); MTType type = elementTypes.get(i); // Create a list of segments. The first element should be the original // parameterExp and oldParameterExp and the second element the cartesian product element. edu.clemson.cs.r2jt.collections.List<Exp> segments = new edu.clemson.cs.r2jt.collections.List<Exp>(); edu.clemson.cs.r2jt.collections.List<Exp> oldSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); segments.add(Exp.copy(parameterExp)); oldSegments.add(Exp.copy(oldParameterExp)); segments.add(Utilities.createVarExp( (Location) opLocation.clone(), null, name .copy(), type, null)); oldSegments.add(Utilities.createVarExp( (Location) opLocation.clone(), null, name .copy(), type, null)); // Create the dotted expressions DotExp elementDotExp = Utilities.createDotExp( (Location) opLocation.clone(), segments, type); DotExp oldElementDotExp = Utilities.createDotExp( (Location) opLocation.clone(), oldSegments, type); // Create an equality expression EqualsExp equalsExp = new EqualsExp(opLocation, elementDotExp, EqualsExp.EQUAL, oldElementDotExp); equalsExp.setMathType(BOOLEAN); equalsExp.setLocation((Location) restoresLoc .clone()); // Add this to our final equals expression if (restoresConditionExp == null) { restoresConditionExp = equalsExp; } else { restoresConditionExp = myTypeGraph .formConjunct( restoresConditionExp, equalsExp); } } } else { // Construct an expression using the expression and it's // old expression equivalent. restoresConditionExp = new EqualsExp(opLocation, Exp .copy(parameterExp), EqualsExp.EQUAL, Exp.copy(oldParameterExp)); restoresConditionExp.setMathType(BOOLEAN); restoresConditionExp.setLocation(restoresLoc); } // Create an AND infix expression with the ensures clause if (ensures != null && !ensures.equals(myTypeGraph.getTrueVarExp())) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, restoresConditionExp); ensures.setLocation(newEnsuresLoc); } // Make new expression the ensures clause else { ensures = restoresConditionExp; } } // Clears mode else if (p.getMode() == Mode.CLEARS) { Exp init; if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form VarExp exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // Deep copy the original initialization ensures and the constraint init = Exp.copy(type.getInitialization().getEnsures()); // Replace the formal with the actual init = Utilities.replace(init, exemplar, parameterExp); // Set the details for the new location Location initLoc; if (ensures != null && ensures.getLocation() != null) { Location reqLoc = ensures.getLocation(); initLoc = ((Location) reqLoc.clone()); } else { initLoc = ((Location) opLocation.clone()); initLoc.setDetails("Ensures Clause of " + opName); } initLoc.setDetails(initLoc.getDetails() + " (Condition from \"" + p.getMode().getModeName() + "\" parameter mode)"); Utilities.setLocation(init, initLoc); } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = p.getLocation(); // Create an is_initial dot expression init = Utilities.createInitExp(new VarDec(p.getName(), p.getTy()), MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + p.getName().getName()); Utilities.setLocation(init, loc); } } // Create an AND infix expression with the ensures clause if (ensures != null) { Location newEnsuresLoc = (Location) ensures.getLocation().clone(); ensures = myTypeGraph.formConjunct(ensures, init); ensures.setLocation(newEnsuresLoc); } // Make initialization expression the ensures clause else { ensures = init; } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { Exp conceptualExp = Utilities.createConcVarExp(opLocation, parameterExp, parameterExp.getMathType(), BOOLEAN); OldExp oldConceptualExp = new OldExp(opLocation, Exp.copy(conceptualExp)); ensures = Utilities.replace(ensures, parameterExp, conceptualExp); ensures = Utilities.replace(ensures, oldParameterExp, oldConceptualExp); } } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual(opLocation, ensures, parameterVarDecList, myInstantiatedFacilityArgMap, myCurrentModuleScope); return ensures; } /** * <p>Returns the ensures clause.</p> * * @param ensures The <code>Exp</code> containing the ensures clause. * @param opLocation The <code>Location</code> for the operation. * @param operationDec The <code>OperationDec</code> that is modifying the ensures clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified ensures clause <code>Exp</code>. */ private Exp modifyEnsuresClause(Exp ensures, Location opLocation, OperationDec operationDec, boolean isLocal) { // Modifies the existing ensures clause based on // the parameter modes. ensures = modifyEnsuresByParameter(ensures, opLocation, operationDec .getName().getName(), operationDec.getParameters(), isLocal); return ensures; } /** * <p>Modifies the requires clause based on .</p> * * @param requires The <code>Exp</code> containing the requires clause. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByGlobalMode(Exp requires) { return requires; } /** * <p>Modifies the requires clause based on the parameter mode.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param assertiveCode The current assertive code we are currently generating. * @param operationDec The <code>OperationDec</code> that is modifying the requires clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresByParameter(Exp requires, Location opLocation, AssertiveCode assertiveCode, OperationDec operationDec, boolean isLocal) { // Obtain the list of parameters List<ParameterVarDec> parameterVarDecList = operationDec.getParameters(); // Loop through each parameter for (ParameterVarDec p : parameterVarDecList) { ProgramTypeEntry typeEntry; // Ty is NameTy if (p.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) p.getTy(); PTType ptType = pNameTy.getProgramTypeValue(); // Only deal with actual types and don't deal // with entry types passed in to the concept realization if (!(ptType instanceof PTGeneric)) { // Convert p to a VarExp VarExp parameterExp = new VarExp(null, null, p.getName()); parameterExp.setMathType(pNameTy.getMathTypeValue()); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy.getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); } // Obtain the original dec from the AST VarExp exemplar = null; Exp constraint = null; if (typeEntry.getDefiningElement() instanceof TypeDec) { TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Obtain the exemplar in VarExp form exemplar = new VarExp(null, null, type.getExemplar()); exemplar.setMathType(pNameTy.getMathTypeValue()); // If we have a type representation, then there are no initialization // or constraint clauses. if (ste instanceof ProgramTypeEntry) { // Deep copy the constraint if (type.getConstraint() != null) { constraint = Exp.copy(type.getConstraint()); } } } // Other than the replaces mode, constraints for the // other parameter modes needs to be added // to the requires clause as conjuncts. if (p.getMode() != Mode.REPLACES) { if (constraint != null && !constraint.equals(myTypeGraph .getTrueVarExp())) { // Replace the formal with the actual if (exemplar != null) { constraint = Utilities.replace(constraint, exemplar, parameterExp); } // Set the details for the new location if (constraint.getLocation() != null) { Location constLoc; if (requires != null && requires.getLocation() != null) { Location reqLoc = requires.getLocation(); constLoc = ((Location) reqLoc.clone()); } else { // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry .getName(); } constLoc = ((Location) opLocation.clone()); constLoc.setDetails("Requires Clause of " + operationDec.getName().getName() + details); } constLoc.setDetails(constLoc.getDetails() + " (Constraint from \"" + p.getMode().getModeName() + "\" parameter mode)"); constraint.setLocation(constLoc); } // Create an AND infix expression with the requires clause if (requires != null && !requires.equals(myTypeGraph .getTrueVarExp())) { requires = myTypeGraph.formConjunct(requires, constraint); requires.setLocation((Location) opLocation .clone()); } // Make constraint expression the requires clause else { requires = constraint; } } } // If the type is a type representation, then our requires clause // should really say something about the conceptual type and not // the variable if (ste instanceof RepresentationTypeEntry && !isLocal) { requires = Utilities.replace(requires, parameterExp, Utilities .createConcVarExp(opLocation, parameterExp, parameterExp .getMathType(), BOOLEAN)); requires.setLocation((Location) opLocation.clone()); } // If the type is a type representation, then we need to add // all the type constraints from all the variable declarations // in the type representation. if (ste instanceof RepresentationTypeEntry) { Exp repConstraintExp = null; Set<VarExp> keys = myRepresentationConstraintMap.keySet(); for (VarExp varExp : keys) { if (varExp.getQualifier() == null && varExp.getName().getName().equals( pNameTy.getName().getName())) { if (repConstraintExp == null) { repConstraintExp = myRepresentationConstraintMap .get(varExp); } else { Utilities.ambiguousTy(pNameTy, pNameTy .getLocation()); } } } // Only do the following if the expression is not simply true if (!repConstraintExp.isLiteralTrue()) { // Replace the exemplar with the actual parameter variable expression repConstraintExp = Utilities.replace(repConstraintExp, exemplar, parameterExp); // Add this to our requires clause requires = myTypeGraph.formConjunct(requires, repConstraintExp); requires.setLocation((Location) opLocation.clone()); } } } // Add the current variable to our list of free variables assertiveCode.addFreeVar(Utilities.createVarExp( p.getLocation(), null, p.getName(), pNameTy .getMathTypeValue(), null)); } else { // Ty not handled. Utilities.tyNotHandled(p.getTy(), p.getLocation()); } } // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(opLocation, requires, parameterVarDecList, myInstantiatedFacilityArgMap, myCurrentModuleScope); return requires; } /** * <p>Modifies the requires clause.</p> * * @param requires The <code>Exp</code> containing the requires clause. * @param opLocation The <code>Location</code> for the operation. * @param assertiveCode The current assertive code we are currently generating. * @param operationDec The <code>OperationDec</code> that is modifying the requires clause. * @param isLocal True if it is a local operation, false otherwise. * * @return The modified requires clause <code>Exp</code>. */ private Exp modifyRequiresClause(Exp requires, Location opLocation, AssertiveCode assertiveCode, OperationDec operationDec, boolean isLocal) { // Modifies the existing requires clause based on // the parameter modes. requires = modifyRequiresByParameter(requires, opLocation, assertiveCode, operationDec, isLocal); // Modifies the existing requires clause based on // the parameter modes. // TODO: Ask Murali what this means requires = modifyRequiresByGlobalMode(requires); return requires; } /** * <p>Basic sanity check for operations as parameters.</p> * * @param loc Location of the actual operation as parameter. * @param formalParams Formal parameters. * @param actualParams Actual parameters. */ private void opAsParameterSanityCheck(Location loc, List<ParameterVarDec> formalParams, List<ParameterVarDec> actualParams) { if (formalParams.size() != actualParams.size()) { throw new SourceErrorException( "Actual operation parameter count " + "does not correspond to the formal operation parameter count." + "\n\tExpected count: " + formalParams.size() + "\n\tFound count: " + actualParams.size(), loc); } Iterator<ParameterVarDec> formalIt = formalParams.iterator(); Iterator<ParameterVarDec> actualIt = actualParams.iterator(); ParameterVarDec currFormalParam, currActualParam; while (formalIt.hasNext()) { currFormalParam = formalIt.next(); currActualParam = actualIt.next(); if (!currActualParam.getMode().getModeName().equals( currFormalParam.getMode().getModeName())) { throw new SourceErrorException( "Operation parameter modes are not the same." + "\n\tExpecting: " + currFormalParam.getMode().getModeName() + " " + currFormalParam.getName() + "\n\tFound: " + currActualParam.getMode().getModeName() + " " + currActualParam.getName(), loc); } } } /** * <p>Replace the formal parameter variables with the actual mathematical * expressions passed in.</p> * * @param exp The expression to be replaced. * @param actualParamList The list of actual parameter variables. * @param formalParamList The list of formal parameter variables. * * @return The modified expression. */ private Exp replaceFacilityDeclarationVariables(Exp exp, List<Exp> formalParamList, List<Exp> actualParamList) { Exp retExp = Exp.copy(exp); if (formalParamList.size() == actualParamList.size()) { // Loop through the argument list for (int i = 0; i < formalParamList.size(); i++) { // Concept variable Exp formalExp = formalParamList.get(i); if (formalExp != null) { // Temporary replacement to avoid formal and actuals being the same Exp newFormalExp; if (formalExp instanceof VarExp) { VarExp formalExpAsVarExp = (VarExp) formalExp; newFormalExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + formalExpAsVarExp.getName()), formalExp.getMathType(), formalExp .getMathTypeValue()); } else { VarExp modifiedInnerVarExp = (VarExp) Exp .copy(((OldExp) formalExp).getExp()); modifiedInnerVarExp.setName(Utilities .createPosSymbol("_" + modifiedInnerVarExp.getName() .getName())); newFormalExp = new OldExp(modifiedInnerVarExp.getLocation(), modifiedInnerVarExp); } retExp = Utilities.replace(retExp, formalExp, newFormalExp); // Actually perform the desired replacement Exp actualExp = actualParamList.get(i); retExp = Utilities.replace(retExp, newFormalExp, actualExp); } } } else { throw new RuntimeException("Size not equal!"); } return retExp; } /** * <p>Replace the formal with the actual variables * inside the ensures clause.</p> * * @param ensures The ensures clause. * @param paramList The list of parameter variables. * @param stateVarList The list of state variables. * @param argList The list of arguments from the operation call. * @param isSimple Check if it is a simple replacement. * * @return The ensures clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualEns(Exp ensures, List<ParameterVarDec> paramList, List<AffectsItem> stateVarList, List<Exp> argList, boolean isSimple) { // Current final confirm Exp newConfirm; // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace state variables in the ensures clause // and create new confirm statements if needed. for (int i = 0; i < stateVarList.size(); i++) { ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); AffectsItem stateVar = stateVarList.get(i); // Only deal with Alters/Reassigns/Replaces/Updates modes if (stateVar.getMode() == Mode.ALTERS || stateVar.getMode() == Mode.REASSIGNS || stateVar.getMode() == Mode.REPLACES || stateVar.getMode() == Mode.UPDATES) { // Obtain the variable from our free variable list Exp globalFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar.getName(), true); if (globalFreeVar != null) { VarExp oldNamesVar = new VarExp(); oldNamesVar.setName(stateVar.getName()); // Create a local free variable if it is not there Exp localFreeVar = myCurrentAssertiveCode.getFreeVar(stateVar .getName(), false); if (localFreeVar == null) { // TODO: Don't have a type for state variables? localFreeVar = new VarExp(null, null, stateVar.getName()); localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); myCurrentAssertiveCode.addFreeVar(localFreeVar); } else { localFreeVar = Utilities.createQuestionMarkVariable( myTypeGraph.formConjunct(ensures, newConfirm), (VarExp) localFreeVar); } // Creating "#" expressions and replace these in the // ensures clause. OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); OldExp oldNameOSVar = new OldExp(null, Exp.copy(oldNamesVar)); ensures = Utilities.replace(ensures, oldNamesVar, globalFreeVar); ensures = Utilities.replace(ensures, oldNameOSVar, osVar); // If it is not simple replacement, replace all ensures clauses // with the appropriate expressions. if (!isSimple) { ensures = Utilities.replace(ensures, globalFreeVar, localFreeVar); ensures = Utilities .replace(ensures, osVar, globalFreeVar); newConfirm = Utilities.replace(newConfirm, globalFreeVar, localFreeVar); } // Set newConfirm as our new final confirm statement myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // Error: Why isn't it a free variable. else { Utilities.notInFreeVarList(stateVar.getName(), stateVar .getLocation()); } } } // Replace postcondition variables in the ensures clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); PosSymbol VDName = varDec.getName(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); newConfirm = confirmStmt.getAssertion(); // VarExp form of the parameter variable VarExp oldExp = new VarExp(null, null, VDName); oldExp.setMathType(exp.getMathType()); oldExp.setMathTypeValue(exp.getMathTypeValue()); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp, myCurrentModuleScope); Exp undqRep = null, quesRep = null; OldExp oSpecVar, oRealVar; String replName = null; // Case #1: ProgramIntegerExp // Case #2: ProgramCharExp // Case #3: ProgramStringExp if (exp instanceof ProgramIntegerExp || exp instanceof ProgramCharExp || exp instanceof ProgramStringExp) { Exp convertExp = Utilities.convertExp(exp, myCurrentModuleScope); if (exp instanceof ProgramIntegerExp) { replName = Integer.toString(((IntegerExp) convertExp) .getValue()); } else if (exp instanceof ProgramCharExp) { replName = Character.toString(((CharExp) convertExp) .getValue()); } else { replName = ((StringExp) convertExp).getValue(); } // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #4: VariableDotExp else if (exp instanceof VariableDotExp) { if (repl instanceof DotExp) { Exp pE = ((DotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<Exp> segList = ((DotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((DotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((DotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((DotExp) quesRep).setSegments(segList); } else if (repl instanceof VariableDotExp) { Exp pE = ((VariableDotExp) repl).getSegments().get(0); replName = pE.toString(0); // Create a variable expression of the form "_?[Argument Name]" undqRep = Exp.copy(repl); edu.clemson.cs.r2jt.collections.List<VariableExp> segList = ((VariableDotExp) undqRep).getSegments(); VariableNameExp undqNameRep = new VariableNameExp(null, null, Utilities .createPosSymbol("_?" + replName)); undqNameRep.setMathType(pE.getMathType()); segList.set(0, undqNameRep); ((VariableDotExp) undqRep).setSegments(segList); // Create a variable expression of the form "?[Argument Name]" quesRep = Exp.copy(repl); segList = ((VariableDotExp) quesRep).getSegments(); segList.set(0, ((VariableDotExp) exp).getSegments().get(0)); ((VariableDotExp) quesRep).setSegments(segList); } // Error: Case not handled! else { Utilities.expNotHandled(exp, exp.getLocation()); } } // Case #5: VariableNameExp else if (exp instanceof VariableNameExp) { // Name of repl in string form replName = ((VariableNameExp) exp).getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // Case #6: Result from a nested function call else { // Name of repl in string form replName = varDec.getName().getName(); // Create a variable expression of the form "_?[Argument Name]" undqRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_?" + replName), exp .getMathType(), exp.getMathTypeValue()); // Create a variable expression of the form "?[Argument Name]" quesRep = Utilities.createVarExp(null, null, Utilities .createPosSymbol("?" + replName), exp .getMathType(), exp.getMathTypeValue()); } // "#" versions of oldExp and repl oSpecVar = new OldExp(null, Exp.copy(oldExp)); oRealVar = new OldExp(null, Exp.copy(repl)); // Nothing can be null! if (oldExp != null && quesRep != null && oSpecVar != null && repl != null && oRealVar != null) { // Alters, Clears, Reassigns, Replaces, Updates if (varDec.getMode() == Mode.ALTERS || varDec.getMode() == Mode.CLEARS || varDec.getMode() == Mode.REASSIGNS || varDec.getMode() == Mode.REPLACES || varDec.getMode() == Mode.UPDATES) { Exp quesVar; // Obtain the free variable VarExp freeVar = (VarExp) myCurrentAssertiveCode.getFreeVar( Utilities.createPosSymbol(replName), false); if (freeVar == null) { freeVar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(replName), varDec.getTy() .getMathTypeValue(), null); } // Apply the question mark to the free variable freeVar = Utilities .createQuestionMarkVariable(myTypeGraph .formConjunct(ensures, newConfirm), freeVar); if (exp instanceof ProgramDotExp || exp instanceof VariableDotExp) { // Make a copy from repl quesVar = Exp.copy(repl); // Replace the free variable in the question mark variable as the first element // in the dot expression. VarExp tmpVar = new VarExp(null, null, freeVar.getName()); tmpVar.setMathType(myTypeGraph.BOOLEAN); edu.clemson.cs.r2jt.collections.List<Exp> segs = ((DotExp) quesVar).getSegments(); segs.set(0, tmpVar); ((DotExp) quesVar).setSegments(segs); } else { // Create a variable expression from free variable quesVar = new VarExp(null, null, freeVar.getName()); quesVar.setMathType(freeVar.getMathType()); quesVar.setMathTypeValue(freeVar.getMathTypeValue()); } // Add the new free variable to free variable list myCurrentAssertiveCode.addFreeVar(freeVar); // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, repl); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(quesVar); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, quesRep); ensures = Utilities.replace(ensures, oSpecVar, repl); } // Update our final confirm with the parameter argument newConfirm = Utilities.replace(newConfirm, repl, quesVar); myCurrentAssertiveCode.setFinalConfirm(newConfirm, confirmStmt.getSimplify()); } // All other modes else { // Check if our ensures clause has the parameter variable in it. if (ensures.containsVar(VDName.getName(), true) || ensures.containsVar(VDName.getName(), false)) { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, undqRep); ensures = Utilities.replace(ensures, oSpecVar, undqRep); // Add it to our list of variables to be replaced later undRepList.add(undqRep); replList.add(repl); } else { // Replace the ensures clause ensures = Utilities.replace(ensures, oldExp, repl); ensures = Utilities.replace(ensures, oSpecVar, repl); } } } } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { ensures = Utilities.replace(ensures, undRepList.get(i), replList .get(i)); } return ensures; } /** * <p>Replace the formal with the actual variables * inside the requires clause.</p> * * @param requires The requires clause. * @param paramList The list of parameter variables. * @param argList The list of arguments from the operation call. * * @return The requires clause in <code>Exp</code> form. */ private Exp replaceFormalWithActualReq(Exp requires, List<ParameterVarDec> paramList, List<Exp> argList) { // List to hold temp and real values of variables in case // of duplicate spec and real variables List<Exp> undRepList = new ArrayList<Exp>(); List<Exp> replList = new ArrayList<Exp>(); // Replace precondition variables in the requires clause for (int i = 0; i < argList.size(); i++) { ParameterVarDec varDec = paramList.get(i); Exp exp = argList.get(i); // Convert the pExp into a something we can use Exp repl = Utilities.convertExp(exp, myCurrentModuleScope); // VarExp form of the parameter variable VarExp oldExp = Utilities.createVarExp(null, null, varDec.getName(), exp .getMathType(), exp.getMathTypeValue()); // New VarExp VarExp newExp = Utilities.createVarExp(null, null, Utilities .createPosSymbol("_" + varDec.getName().getName()), repl.getMathType(), repl.getMathTypeValue()); // Replace the old with the new in the requires clause requires = Utilities.replace(requires, oldExp, newExp); // Add it to our list undRepList.add(newExp); replList.add(repl); } // Replace the temp values with the actual values for (int i = 0; i < undRepList.size(); i++) { requires = Utilities.replace(requires, undRepList.get(i), replList .get(i)); } return requires; } // ----------------------------------------------------------- // Proof Rules // ----------------------------------------------------------- /** * <p>Applies the assume rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>AssumeStmt</code>. */ private void applyAssumeStmtRule(AssumeStmt stmt) { // Check to see if our assertion just has "True" Exp assertion = stmt.getAssertion(); if (assertion instanceof VarExp && assertion.equals(myTypeGraph.getTrueVarExp())) { // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Apply simplification for equals expressions and // apply steps to generate parsimonious vcs. ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); boolean simplify = finalConfirm.getSimplify(); List<Exp> assumeExpList = Utilities.splitConjunctExp(stmt.getAssertion(), new ArrayList<Exp>()); List<Exp> confirmExpList = Utilities.splitConjunctExp(finalConfirm.getAssertion(), new ArrayList<Exp>()); Exp currentFinalConfirm = formParsimoniousVC(confirmExpList, assumeExpList, stmt .getIsStipulate()); // Set this as our new final confirm myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm, simplify); // Verbose Mode Debug Messages myVCBuffer.append("\nAssume Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } /** * <p>Applies the change rule.</p> * * @param change The change clause */ private void applyChangeRule(VerificationStatement change) { List<VariableExp> changeList = (List<VariableExp>) change.getAssertion(); ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = confirmStmt.getAssertion(); // Loop through each variable for (VariableExp v : changeList) { // v is an instance of VariableNameExp if (v instanceof VariableNameExp) { VariableNameExp vNameExp = (VariableNameExp) v; // Create VarExp for vNameExp VarExp vExp = Utilities.createVarExp(vNameExp.getLocation(), vNameExp .getQualifier(), vNameExp.getName(), vNameExp .getMathType(), vNameExp.getMathTypeValue()); // Create a new question mark variable VarExp newV = Utilities .createQuestionMarkVariable(finalConfirm, vExp); // Add this new variable to our list of free variables myCurrentAssertiveCode.addFreeVar(newV); // Replace all instances of vExp with newV finalConfirm = Utilities.replace(finalConfirm, vExp, newV); } } // Set the modified statement as our new final confirm myCurrentAssertiveCode.setFinalConfirm(finalConfirm, confirmStmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nChange Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the call statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>CallStmt</code>. */ private void applyCallStmtRule(CallStmt stmt) { // Call a method to locate the operation dec for this call List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : stmt.getArguments()) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(stmt.getLocation(), stmt .getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); boolean isLocal = Utilities.isLocationOperation(stmt.getName().getName(), myCurrentModuleScope); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures; if (opDec.getEnsures() != null) { ensures = Exp.copy(opDec.getEnsures()); } else { ensures = myTypeGraph.getTrueVarExp(); Location loc; if (opDec.getLocation() != null) { loc = (Location) opDec.getLocation().clone(); } else { loc = (Location) opDec.getEnsures().getLocation().clone(); } ensures.setLocation(loc); } // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals(opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier().equals( opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = stmt.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Modify ensures using the parameter modes ensures = modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec .getName().getName(), opDec.getParameters(), isLocal); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace PostCondition variables in the ensures clause ensures = replaceFormalWithActualEns(ensures, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(stmt.getLocation(), requires, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual(stmt.getLocation(), ensures, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry OperationProfileEntry ope = Utilities.searchOperationProfile(loc, stmt.getQualifier(), stmt.getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns(profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (stmt.getName().getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc.setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } ensures = myTypeGraph.formConjunct(ensures, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec.getParameters(), opDec.getStateVars(), replaceArgs, false); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities.createDurCallExp((Location) loc.clone(), Integer .toString(opDec.getParameters().size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = stmt.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities.getVarName(pExp), p.getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur(v, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities.createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirmExp, finalConfirm.getSimplify()); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (requires != null) { // Obtain the current location // Note: If we don't have a location, we create one Location loc; if (stmt.getName().getLocation() != null) { loc = (Location) stmt.getName().getLocation().clone(); } else { loc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location loc.setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, loc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) loc.clone(), requires, simplify); } // Modify the location of the requires clause and add it to myCurrentAssertiveCode if (ensures != null) { // Obtain the current location Location loc = null; if (stmt.getName().getLocation() != null) { // Set the details of the current location loc = (Location) stmt.getName().getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Add this to our list of things to assume myCurrentAssertiveCode.addAssume(loc, ensures, false); } // Verbose Mode Debug Messages myVCBuffer.append("\nOperation Call Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies different rules to code statements.</p> * * @param statement The different statements. */ private void applyCodeRules(Statement statement) { // Apply each statement rule here. if (statement instanceof AssumeStmt) { applyAssumeStmtRule((AssumeStmt) statement); } else if (statement instanceof CallStmt) { applyCallStmtRule((CallStmt) statement); } else if (statement instanceof ConfirmStmt) { applyConfirmStmtRule((ConfirmStmt) statement); } else if (statement instanceof FuncAssignStmt) { applyFuncAssignStmtRule((FuncAssignStmt) statement); } else if (statement instanceof IfStmt) { applyIfStmtRule((IfStmt) statement); } else if (statement instanceof MemoryStmt) { // TODO: Deal with Forget if (((MemoryStmt) statement).isRemember()) { applyRememberRule(); } } else if (statement instanceof SwapStmt) { applySwapStmtRule((SwapStmt) statement); } else if (statement instanceof WhileStmt) { applyWhileStmtRule((WhileStmt) statement); } } /** * <p>Applies the confirm rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>ConfirmStmt</code>. */ private void applyConfirmStmtRule(ConfirmStmt stmt) { // Check to see if our assertion can be simplified Exp assertion = stmt.getAssertion(); if (stmt.getSimplify()) { // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Obtain the current final confirm statement ConfirmStmt currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); // Check to see if we can simplify the final confirm if (currentFinalConfirm.getSimplify()) { // Obtain the current location if (assertion.getLocation() != null) { // Set the details of the current location Location loc = (Location) assertion.getLocation().clone(); Utilities.setLocation(assertion, loc); } myCurrentAssertiveCode.setFinalConfirm(assertion, stmt .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Create a new and expression InfixExp newConf = myTypeGraph.formConjunct(assertion, currentFinalConfirm .getAssertion()); // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(newConf, false); // Verbose Mode Debug Messages myVCBuffer.append("\nConfirm Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } } } /** * <p>Applies the correspondence rule.</p> * * @param dec Representation declaration object. */ private void applyCorrespondenceRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Obtain the location for each assume clause Location decLoc = dec.getLocation(); // Add the global constraints as given Location constraintLoc; if (myGlobalConstraintExp.getLocation() != null) { constraintLoc = (Location) myGlobalConstraintExp.getLocation().clone(); } else { constraintLoc = (Location) decLoc.clone(); } constraintLoc.setDetails("Global Constraints from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(constraintLoc, myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Add the convention as given assertiveCode.addAssume((Location) decLoc.clone(), dec.getConvention(), false); // Add the type representation constraint Exp repConstraintExp = null; Set<VarExp> keys = myRepresentationConstraintMap.keySet(); for (VarExp varExp : keys) { if (varExp.getQualifier() == null && varExp.getName().getName().equals( dec.getName().getName())) { if (repConstraintExp == null) { repConstraintExp = myRepresentationConstraintMap.get(varExp); } else { Utilities.ambiguousTy(dec.getRepresentation(), dec .getLocation()); } } } assertiveCode.addAssume((Location) decLoc.clone(), repConstraintExp, false); // Add the correspondence as given Exp correspondenceExp = Exp.copy(dec.getCorrespondence()); assertiveCode.addAssume((Location) decLoc.clone(), correspondenceExp, false); // Store the correspondence in our map myRepresentationCorrespondenceMap.put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation().getMathTypeValue(), null), Exp .copy(correspondenceExp)); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp constraint; if (type.getConstraint() == null) { constraint = myTypeGraph.getTrueVarExp(); } else { constraint = Exp.copy(type.getConstraint()); } constraint = Utilities.replace(constraint, exemplar, conceptualVar); // Set the location for the constraint Location loc; if (correspondenceExp.getLocation() != null) { loc = (Location) correspondenceExp.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Well Defined Correspondence for " + dec.getName().getName()); Utilities.setLocation(constraint, loc); // We need to make sure the constraints for the type we are // implementing is met. boolean simplify = false; // Simplify if we just have true if (constraint.isLiteralTrue()) { simplify = true; } assertiveCode.setFinalConfirm(constraint, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nCorrespondence Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the facility declaration rule.</p> * * @param dec Facility declaration object. * @param addToIncAssertiveCodeStack True if the created assertive code needs * to be added to our incomplete assertive code stack. */ private void applyFacilityDeclRule(FacilityDec dec, boolean addToIncAssertiveCodeStack) { // Create a new assertive code to hold the facility declaration VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the current facility dec Location decLoc = dec.getLocation(); // Add the global constraints as given (if any) if (myGlobalConstraintExp != null) { Location gConstraintLoc; if (myGlobalConstraintExp.getLocation() != null) { gConstraintLoc = (Location) myGlobalConstraintExp.getLocation().clone(); } else { gConstraintLoc = (Location) decLoc.clone(); } gConstraintLoc.setDetails("Global Constraints from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(gConstraintLoc, myGlobalConstraintExp, false); } // Add the global require clause as given (if any) if (myGlobalRequiresExp != null) { Location gRequiresLoc; if (myGlobalRequiresExp.getLocation() != null) { gRequiresLoc = (Location) myGlobalRequiresExp.getLocation().clone(); } else { gRequiresLoc = (Location) decLoc.clone(); } gRequiresLoc.setDetails("Global Requires Clause from " + myCurrentModuleScope.getModuleIdentifier()); assertiveCode.addAssume(gRequiresLoc, myGlobalRequiresExp, false); } // Add a remember rule assertiveCode.addCode(new MemoryStmt((Location) decLoc.clone(), true)); try { // Obtain the concept module for the facility ConceptModuleDec facConceptDec = (ConceptModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(dec.getConceptName() .getName())).getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> conceptFormalArgList = createModuleFormalArgExpList(facConceptDec.getParameters()); List<Exp> conceptActualArgList = createModuleActualArgExpList(assertiveCode, dec .getConceptParams()); // Facility Decl Rule (Concept Requires): CPC[ n ~> n_exp, R ~> IR ] Exp conceptReq = replaceFacilityDeclarationVariables(getRequiresClause( facConceptDec.getLocation(), facConceptDec), conceptFormalArgList, conceptActualArgList); if (!conceptReq.equals(myTypeGraph.getTrueVarExp())) { Location conceptReqLoc = (Location) dec.getConceptName().getLocation().clone(); conceptReqLoc.setDetails("Requires Clause for " + dec.getConceptName().getName() + " in Facility Instantiation Rule"); conceptReq.setLocation(conceptReqLoc); assertiveCode.addConfirm(conceptReqLoc, conceptReq, false); } // Create a mapping from concept formal to actual arguments // for future use. Map<Exp, Exp> conceptArgMap = new HashMap<Exp, Exp>(); for (int i = 0; i < conceptFormalArgList.size(); i++) { conceptArgMap.put(conceptFormalArgList.get(i), conceptActualArgList.get(i)); } // Facility Decl Rule (Concept Realization Requires): // (RPC[ rn ~> rn_exp, RR ~> IRR ])[ n ~> n_exp, R ~> IR ] // // Note: Only apply this part of the rule if the concept realization // is not externally realized. Map<Exp, Exp> conceptRealizArgMap = new HashMap<Exp, Exp>(); if (!dec.getExternallyRealizedFlag()) { ConceptBodyModuleDec facConceptRealizDec = (ConceptBodyModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(dec.getBodyName() .getName())).getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> conceptRealizFormalArgList = createModuleFormalArgExpList(facConceptRealizDec .getParameters()); List<Exp> conceptRealizActualArgList = createModuleActualArgExpList(assertiveCode, dec .getBodyParams()); // 1) Replace the concept realization formal with actuals Exp conceptRealizReq = replaceFacilityDeclarationVariables(getRequiresClause( facConceptRealizDec.getLocation(), facConceptRealizDec), conceptRealizFormalArgList, conceptRealizActualArgList); // 2) Replace the concept formal with actuals conceptRealizReq = replaceFacilityDeclarationVariables(conceptRealizReq, conceptFormalArgList, conceptActualArgList); // Add this as a new confirm statement in our assertive code if (!conceptRealizReq.equals(myTypeGraph.getTrueVarExp())) { Location conceptRealizReqLoc = (Location) dec.getBodyName().getLocation().clone(); conceptRealizReqLoc.setDetails("Requires Clause for " + dec.getBodyName().getName() + " in Facility Instantiation Rule"); conceptRealizReq.setLocation(conceptRealizReqLoc); assertiveCode.addConfirm(conceptRealizReqLoc, conceptRealizReq, false); } // Create a mapping from concept realization formal to actual arguments // for future use. for (int i = 0; i < conceptRealizFormalArgList.size(); i++) { conceptRealizArgMap.put(conceptRealizFormalArgList.get(i), conceptRealizActualArgList.get(i)); } // Facility Decl Rule (Operations as Concept Realization Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP and // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] // // Note: We need to pass in empty lists for enhancement/enhancement realization // formal and actuals, because they are not needed here. assertiveCode = facilityDeclOperationParamHelper(decLoc, assertiveCode, facConceptRealizDec.getParameters(), dec .getBodyParams(), conceptFormalArgList, conceptActualArgList, conceptRealizFormalArgList, conceptRealizActualArgList, new ArrayList<Exp>(), new ArrayList<Exp>(), new ArrayList<Exp>(), new ArrayList<Exp>()); } // TODO: Figure out how to apply the rule when there are enhancements for concept realizations List<EnhancementItem> enhancementList = dec.getEnhancements(); for (EnhancementItem e : enhancementList) { // Do something here. } // Apply the facility declaration rules to regular enhancement/enhancement realizations List<EnhancementBodyItem> enhancementBodyList = dec.getEnhancementBodies(); Map<PosSymbol, Map<Exp, Exp>> enhancementArgMaps = new HashMap<PosSymbol, Map<Exp, Exp>>(); for (EnhancementBodyItem ebi : enhancementBodyList) { // Obtain the enhancement module for the facility EnhancementModuleDec facEnhancementDec = (EnhancementModuleDec) mySymbolTable.getModuleScope( new ModuleIdentifier(ebi.getName().getName())) .getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> enhancementFormalArgList = createModuleFormalArgExpList(facEnhancementDec .getParameters()); List<Exp> enhancementActualArgList = createModuleActualArgExpList(assertiveCode, ebi .getParams()); // Facility Decl Rule (Enhancement Requires): // CPC[ n ~> n_exp, R ~> IR ] (Use the enhancement equivalents) Exp enhancementReq = replaceFacilityDeclarationVariables(getRequiresClause( facEnhancementDec.getLocation(), facEnhancementDec), enhancementFormalArgList, enhancementActualArgList); if (!enhancementReq.equals(myTypeGraph.getTrueVarExp())) { Location enhancementReqLoc = (Location) ebi.getName().getLocation().clone(); enhancementReqLoc.setDetails("Requires Clause for " + ebi.getName().getName() + " in Facility Instantiation Rule"); enhancementReq.setLocation(enhancementReqLoc); assertiveCode.addConfirm(enhancementReqLoc, enhancementReq, false); } // Create a mapping from concept formal to actual arguments // for future use. Map<Exp, Exp> enhancementArgMap = new HashMap<Exp, Exp>(); for (int i = 0; i < enhancementFormalArgList.size(); i++) { enhancementArgMap.put(enhancementFormalArgList.get(i), enhancementActualArgList.get(i)); } enhancementArgMaps.put(facEnhancementDec.getName(), enhancementArgMap); // Facility Decl Rule (Enhancement Realization Requires): // (RPC[ rn ~> rn_exp, RR ~> IRR ])[ n ~> n_exp, R ~> IR ] // (Use the enhancement realization equivalents and // also have to replace enhancement formals with actuals) // // Note: Only apply this part of the rule if the concept realization // is not externally realized. Map<Exp, Exp> enhancementRealizArgMap = new HashMap<Exp, Exp>(); EnhancementBodyModuleDec facEnhancementRealizDec = (EnhancementBodyModuleDec) mySymbolTable .getModuleScope( new ModuleIdentifier(ebi.getBodyName() .getName())) .getDefiningElement(); // Convert the module arguments into mathematical expressions // Note that we could potentially have a nested function call // as one of the arguments, therefore we pass in the assertive // code to store the confirm statement generated from all the // requires clauses. List<Exp> enhancementRealizFormalArgList = createModuleFormalArgExpList(facEnhancementRealizDec .getParameters()); List<Exp> enhancementRealizActualArgList = createModuleActualArgExpList(assertiveCode, ebi .getBodyParams()); // 1) Replace the enhancement realization formal with actuals Exp enhancementRealizReq = replaceFacilityDeclarationVariables(getRequiresClause( facEnhancementRealizDec.getLocation(), facEnhancementRealizDec), enhancementRealizFormalArgList, enhancementRealizActualArgList); // 2) Replace the concept formal with actuals enhancementRealizReq = replaceFacilityDeclarationVariables( enhancementRealizReq, conceptFormalArgList, conceptActualArgList); // 3) Replace the enhancement formal with actuals enhancementRealizReq = replaceFacilityDeclarationVariables( enhancementRealizReq, enhancementFormalArgList, enhancementActualArgList); // Add this as a new confirm statement in our assertive code if (!enhancementRealizReq.equals(myTypeGraph.getTrueVarExp())) { Location enhancementRealizReqLoc = (Location) ebi.getBodyName().getLocation().clone(); enhancementRealizReqLoc.setDetails("Requires Clause for " + ebi.getBodyName().getName() + " in Facility Instantiation Rule"); enhancementRealizReq.setLocation(enhancementRealizReqLoc); assertiveCode.addConfirm(enhancementRealizReqLoc, enhancementRealizReq, false); } // Create a mapping from enhancement realization formal to actual arguments // for future use. for (int i = 0; i < enhancementRealizFormalArgList.size(); i++) { enhancementRealizArgMap.put(enhancementRealizFormalArgList .get(i), enhancementRealizActualArgList.get(i)); } enhancementArgMaps.put(facEnhancementRealizDec.getName(), enhancementRealizArgMap); // Facility Decl Rule (Operations as Enhancement Realization Parameters): // preRP [ rn ~> rn_exp, rx ~> irx ] implies preIRP and // postIRP implies postRP [ rn ~> rn_exp, #rx ~> #irx, rx ~> irx ] // // Note: We need to pass in empty lists for concept realization // formal and actuals, because they are not needed here. assertiveCode = facilityDeclOperationParamHelper(decLoc, assertiveCode, facEnhancementRealizDec.getParameters(), ebi .getBodyParams(), conceptFormalArgList, conceptActualArgList, new ArrayList<Exp>(), new ArrayList<Exp>(), enhancementFormalArgList, enhancementActualArgList, enhancementRealizFormalArgList, enhancementRealizActualArgList); } // The code below stores a mapping between each of the concept/realization/enhancement // formal arguments to the actual arguments instantiated by the facility. // This is needed to replace the requires/ensures clauses from facility instantiated // operations. FacilityFormalToActuals formalToActuals = new FacilityFormalToActuals(conceptArgMap, conceptRealizArgMap, enhancementArgMaps); for (Dec d : facConceptDec.getDecs()) { if (d instanceof TypeDec) { Location loc = (Location) dec.getLocation().clone(); PosSymbol qual = dec.getName().copy(); PosSymbol name = d.getName().copy(); Ty dTy = ((TypeDec) d).getModel(); myInstantiatedFacilityArgMap.put(Utilities.createVarExp( loc, qual, name, dTy.getMathType(), dTy .getMathTypeValue()), formalToActuals); } } } catch (NoSuchSymbolException e) { Utilities.noSuchModule(dec.getLocation()); } // This is a local facility and we need to add it to our incomplete // assertive code stack. if (addToIncAssertiveCodeStack) { // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Facility Dec Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nFacility Declaration Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } } /** * <p>Applies the function assignment rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>FuncAssignStmt</code>. */ private void applyFuncAssignStmtRule(FuncAssignStmt stmt) { PosSymbol qualifier = null; ProgramExp assignExp = stmt.getAssign(); ProgramParamExp assignParamExp = null; // Replace all instances of the variable on the left hand side // in the ensures clause with the expression on the right. Exp leftVariable; // We have a variable inside a record as the variable being assigned. if (stmt.getVar() instanceof VariableDotExp) { VariableDotExp v = (VariableDotExp) stmt.getVar(); List<VariableExp> vList = v.getSegments(); edu.clemson.cs.r2jt.collections.List<Exp> newSegments = new edu.clemson.cs.r2jt.collections.List<Exp>(); // Loot through each variable expression and add it to our dot list for (VariableExp vr : vList) { VarExp varExp = new VarExp(); if (vr instanceof VariableNameExp) { varExp.setName(((VariableNameExp) vr).getName()); varExp.setMathType(vr.getMathType()); varExp.setMathTypeValue(vr.getMathTypeValue()); newSegments.add(varExp); } } // Expression to be replaced leftVariable = new DotExp(v.getLocation(), newSegments, null); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // We have a regular variable being assigned. else { // Expression to be replaced VariableNameExp v = (VariableNameExp) stmt.getVar(); leftVariable = new VarExp(v.getLocation(), null, v.getName()); leftVariable.setMathType(v.getMathType()); leftVariable.setMathTypeValue(v.getMathTypeValue()); } // Simply replace the numbers/characters/strings if (assignExp instanceof ProgramIntegerExp || assignExp instanceof ProgramCharExp || assignExp instanceof ProgramStringExp) { Exp replaceExp = Utilities.convertExp(assignExp, myCurrentModuleScope); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, replaceExp); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt .getSimplify()); } else { // Check to see what kind of expression is on the right hand side if (assignExp instanceof ProgramParamExp) { // Cast to a ProgramParamExp assignParamExp = (ProgramParamExp) assignExp; } else if (assignExp instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) assignExp; assignParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } // Call a method to locate the operation dec for this call List<PTType> argTypes = new LinkedList<PTType>(); for (ProgramExp arg : assignParamExp.getArguments()) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(stmt.getLocation(), qualifier, assignParamExp.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals( opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier() .equals(opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation() .clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = assignParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Replace facility actuals variables in the requires clause requires = Utilities.replaceFacilityFormalWithActual(assignParamExp .getLocation(), requires, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (assignParamExp.getName().getLocation() != null) { reqloc = (Location) assignParamExp.getName().getLocation() .clone(); } else { reqloc = new Location(null, null); } // Append the name of the current procedure String details = ""; if (myCurrentOperationEntry != null) { details = " in Procedure " + myCurrentOperationEntry.getName(); } // Set the details of the current location reqloc .setDetails("Requires Clause of " + opDec.getName() + details); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location if (assignParamExp.getName().getLocation() != null) { // Set the details of the current location Location loc = (Location) assignParamExp.getName() .getLocation().clone(); loc.setDetails("Ensures Clause of " + opDec.getName()); Utilities.setLocation(ensures, loc); } // Replace the formal with the actual ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec .getStateVars(), replaceArgs, true); // Replace facility actuals variables in the ensures clause ensures = Utilities.replaceFacilityFormalWithActual( assignParamExp.getLocation(), ensures, opDec.getParameters(), myInstantiatedFacilityArgMap, myCurrentModuleScope); // Replace all instances of the left hand side // variable in the current final confirm statement. ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp newConf = confirmStmt.getAssertion(); newConf = Utilities.replace(newConf, leftVariable, ensures); // Set this as our new final confirm statement. myCurrentAssertiveCode.setFinalConfirm(newConf, confirmStmt.getSimplify()); // NY YS // Duration for CallStmt if (myInstanceEnvironment.flags .isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) stmt.getLocation().clone(); ConfirmStmt finalConfirm = myCurrentAssertiveCode .getFinalConfirm(); Exp finalConfirmExp = finalConfirm.getAssertion(); // Obtain the corresponding OperationProfileEntry OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, assignParamExp .getName(), argTypes, myCurrentModuleScope); // Add the profile ensures as additional assume Exp profileEnsures = ope.getEnsuresClause(); if (profileEnsures != null) { profileEnsures = replaceFormalWithActualEns( profileEnsures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); // Obtain the current location if (assignParamExp.getLocation() != null) { // Set the details of the current location Location ensuresLoc = (Location) loc.clone(); ensuresLoc .setDetails("Ensures Clause of " + opDec.getName() + " from Profile " + ope.getName()); Utilities.setLocation(profileEnsures, ensuresLoc); } finalConfirmExp = myTypeGraph.formConjunct( finalConfirmExp, profileEnsures); } // Construct the Duration Clause Exp opDur = Exp.copy(ope.getDurationClause()); // Replace PostCondition variables in the duration clause opDur = replaceFormalWithActualEns(opDur, opDec .getParameters(), opDec .getStateVars(), replaceArgs, false); VarExp cumDur = Utilities .createVarExp( (Location) loc.clone(), null, Utilities .createPosSymbol(Utilities .getCumDur(finalConfirmExp)), myTypeGraph.R, null); Exp durCallExp = Utilities .createDurCallExp( (Location) loc.clone(), Integer .toString(opDec .getParameters() .size()), Z, myTypeGraph.R); InfixExp sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities .createPosSymbol("+"), sumEvalDur); sumEvalDur.setMathType(myTypeGraph.R); // For any evaluates mode expression, we need to finalize the variable edu.clemson.cs.r2jt.collections.List<ProgramExp> assignExpList = assignParamExp.getArguments(); for (int i = 0; i < assignExpList.size(); i++) { ParameterVarDec p = opDec.getParameters().get(i); VariableExp pExp = (VariableExp) assignExpList.get(i); if (p.getMode() == Mode.EVALUATES) { VarDec v = new VarDec(Utilities .getVarName(pExp), p .getTy()); FunctionExp finalDur = Utilities.createFinalizAnyDur( v, myTypeGraph.R); sumEvalDur = new InfixExp( (Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalDur); sumEvalDur.setMathType(myTypeGraph.R); } } // Add duration of assignment and finalize the temporary variable Exp assignDur = Utilities.createVarExp((Location) loc .clone(), null, Utilities .createPosSymbol("Dur_Assgn"), myTypeGraph.R, null); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), assignDur); sumEvalDur.setMathType(myTypeGraph.R); Exp finalExpDur = Utilities.createFinalizAnyDurExp(stmt .getVar(), myTypeGraph.R, myCurrentModuleScope); sumEvalDur = new InfixExp((Location) loc.clone(), sumEvalDur, Utilities .createPosSymbol("+"), finalExpDur); sumEvalDur.setMathType(myTypeGraph.R); // Replace Cum_Dur in our final ensures clause finalConfirmExp = Utilities.replace(finalConfirmExp, cumDur, sumEvalDur); myCurrentAssertiveCode.setFinalConfirm( finalConfirmExp, finalConfirm .getSimplify()); } } else { Utilities.illegalOperationEnsures(opDec .getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } } // Verbose Mode Debug Messages myVCBuffer.append("\nFunction Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the if statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>IfStmt</code>. */ private void applyIfStmtRule(IfStmt stmt) { // Note: In the If Rule, we will have two instances of the assertive code. // One for when the if condition is true and one for the else condition. // The current global assertive code variable is going to be used for the if path, // and we are going to create a new assertive code for the else path (this includes // the case when there is no else clause). ProgramExp ifCondition = stmt.getTest(); // Negation of If (Need to make a copy before we start modifying // the current assertive code for the if part) AssertiveCode negIfAssertiveCode = new AssertiveCode(myCurrentAssertiveCode); // Call a method to locate the operation dec for this call PosSymbol qualifier = null; ProgramParamExp testParamExp = null; // Check to see what kind of expression is on the right hand side if (ifCondition instanceof ProgramParamExp) { // Cast to a ProgramParamExp testParamExp = (ProgramParamExp) ifCondition; } else if (ifCondition instanceof ProgramDotExp) { // Cast to a ProgramParamExp ProgramDotExp dotExp = (ProgramDotExp) ifCondition; testParamExp = (ProgramParamExp) dotExp.getExp(); qualifier = dotExp.getQualifier(); } else { Utilities.expNotHandled(ifCondition, stmt.getLocation()); } Location ifConditionLoc; if (ifCondition.getLocation() != null) { ifConditionLoc = (Location) ifCondition.getLocation().clone(); } else { ifConditionLoc = (Location) stmt.getLocation().clone(); } // Search for the operation dec List<PTType> argTypes = new LinkedList<PTType>(); List<ProgramExp> argsList = testParamExp.getArguments(); for (ProgramExp arg : argsList) { argTypes.add(arg.getProgramType()); } OperationEntry opEntry = Utilities.searchOperation(ifCondition.getLocation(), qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); OperationDec opDec = Utilities.convertToOperationDec(opEntry); // Check for recursive call of itself if (myCurrentOperationEntry != null && myOperationDecreasingExp != null && myCurrentOperationEntry.getName().equals(opEntry.getName()) && myCurrentOperationEntry.getReturnType().equals( opEntry.getReturnType()) && myCurrentOperationEntry.getSourceModuleIdentifier().equals( opEntry.getSourceModuleIdentifier())) { // Create a new confirm statement using P_val and the decreasing clause VarExp pVal = Utilities.createPValExp(myOperationDecreasingExp .getLocation(), myCurrentModuleScope); // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp .copy(myOperationDecreasingExp)); leftExp.setMathType(myOperationDecreasingExp.getMathType()); InfixExp exp = Utilities.createLessThanEqExp(stmt.getLocation(), leftExp, pVal, BOOLEAN); // Create the new confirm statement Location loc; if (myOperationDecreasingExp.getLocation() != null) { loc = (Location) myOperationDecreasingExp.getLocation().clone(); } else { loc = (Location) stmt.getLocation().clone(); } loc.setDetails("Show Termination of Recursive Call"); Utilities.setLocation(exp, loc); ConfirmStmt conf = new ConfirmStmt(loc, exp, false); // Add it to our list of assertions myCurrentAssertiveCode.addCode(conf); } // Confirm the invoking condition // Get the requires clause for this operation Exp requires; boolean simplify = false; if (opDec.getRequires() != null) { requires = Exp.copy(opDec.getRequires()); // Simplify if we just have true if (requires.isLiteralTrue()) { simplify = true; } } else { requires = myTypeGraph.getTrueVarExp(); simplify = true; } // Find all the replacements that needs to happen to the requires // and ensures clauses List<ProgramExp> callArgs = testParamExp.getArguments(); List<Exp> replaceArgs = modifyArgumentList(callArgs); // Replace PreCondition variables in the requires clause requires = replaceFormalWithActualReq(requires, opDec.getParameters(), replaceArgs); // Modify the location of the requires clause and add it to myCurrentAssertiveCode // Obtain the current location // Note: If we don't have a location, we create one Location reqloc; if (testParamExp.getName().getLocation() != null) { reqloc = (Location) testParamExp.getName().getLocation().clone(); } else { reqloc = new Location(null, null); } // Set the details of the current location reqloc.setDetails("Requires Clause of " + opDec.getName()); Utilities.setLocation(requires, reqloc); // Add this to our list of things to confirm myCurrentAssertiveCode.addConfirm((Location) reqloc.clone(), requires, simplify); // Add the if condition as the assume clause // Get the ensures clause for this operation // Note: If there isn't an ensures clause, it is set to "True" Exp ensures, negEnsures = null, opEnsures; if (opDec.getEnsures() != null) { opEnsures = Exp.copy(opDec.getEnsures()); // Make sure we have an EqualsExp, else it is an error. if (opEnsures instanceof EqualsExp) { // Has to be a VarExp on the left hand side (containing the name // of the function operation) if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); // Check if it has the name of the operation if (leftExp.getName().equals(opDec.getName())) { ensures = ((EqualsExp) opEnsures).getRight(); // Obtain the current location Location loc = null; if (testParamExp.getName().getLocation() != null) { // Set the details of the current location loc = (Location) testParamExp.getName() .getLocation().clone(); loc.setDetails("If Statement Condition"); Utilities.setLocation(ensures, loc); } // Replace the formals with the actuals. ensures = replaceFormalWithActualEns(ensures, opDec .getParameters(), opDec.getStateVars(), replaceArgs, false); myCurrentAssertiveCode.addAssume(loc, ensures, true); // Negation of the condition negEnsures = Utilities.negateExp(ensures, BOOLEAN); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> thenStmtList; if (stmt.getThenclause() != null) { thenStmtList = stmt.getThenclause(); } else { thenStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); Exp ifConfirmExp = ifConfirm.getAssertion(); Location ifLocation; if (ifConfirmExp.getLocation() != null) { ifLocation = (Location) ifConfirmExp.getLocation().clone(); } else { ifLocation = (Location) stmt.getLocation().clone(); } String ifDetail = ifLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is true"; ifLocation.setDetails(ifDetail); ifConfirmExp.setLocation(ifLocation); // NY YS // Duration for If Part InfixExp sumEvalDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = (Location) ifLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (ifConfirmExp.isLiteralTrue() && thenStmtList.size() != 0) { Statement st = thenStmtList.get(thenStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(ifConfirmExp)), myTypeGraph.R, null); } // Search for operation profile OperationProfileEntry ope = Utilities.searchOperationProfile(loc, qualifier, testParamExp.getName(), argTypes, myCurrentModuleScope); Exp opDur = Exp.copy(ope.getDurationClause()); Exp durCallExp = Utilities.createDurCallExp(loc, Integer.toString(opDec .getParameters().size()), Z, myTypeGraph.R); sumEvalDur = new InfixExp((Location) loc.clone(), opDur, Utilities .createPosSymbol("+"), durCallExp); sumEvalDur.setMathType(myTypeGraph.R); Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); thenStmtList.set(thenStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" ifConfirmExp = Utilities.replace(ifConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the if to the assertive code myCurrentAssertiveCode.addStatements(thenStmtList); // Set the final if confirm myCurrentAssertiveCode.setFinalConfirm(ifConfirmExp, ifConfirm .getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nIf Part Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); // Add the negation of the if condition as the assume clause if (negEnsures != null) { negIfAssertiveCode.addAssume(ifLocation, negEnsures, true); } else { Utilities.illegalOperationEnsures(opDec.getLocation()); } // Create a list for the then clause edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList; if (stmt.getElseclause() != null) { elseStmtList = stmt.getElseclause(); } else { elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); } // Modify the confirm details ConfirmStmt negIfConfirm = negIfAssertiveCode.getFinalConfirm(); Exp negIfConfirmExp = negIfConfirm.getAssertion(); Location negIfLocation; if (negIfConfirmExp.getLocation() != null) { negIfLocation = (Location) negIfConfirmExp.getLocation().clone(); } else { negIfLocation = (Location) stmt.getLocation().clone(); } String negIfDetail = negIfLocation.getDetails() + ", Condition at " + ifConditionLoc.toString() + " is false"; negIfLocation.setDetails(negIfDetail); negIfConfirmExp.setLocation(negIfLocation); // NY YS // Duration for Else Part if (sumEvalDur != null) { Location loc = (Location) negIfLocation.clone(); VarExp cumDur; boolean trueConfirm = false; // Our previous rule must have been a while rule ConfirmStmt conf = null; if (negIfConfirmExp.isLiteralTrue() && elseStmtList.size() != 0) { Statement st = elseStmtList.get(elseStmtList.size() - 1); if (st instanceof ConfirmStmt) { conf = (ConfirmStmt) st; cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf.getAssertion())), myTypeGraph.R, null); trueConfirm = true; } else { cumDur = null; Utilities.noSuchSymbol(null, "Cum_Dur", loc); } } else { cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(negIfConfirmExp)), myTypeGraph.R, null); } Exp sumPlusCumDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(sumEvalDur)); sumPlusCumDur.setMathType(myTypeGraph.R); if (trueConfirm && conf != null) { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" Exp confirm = conf.getAssertion(); confirm = Utilities.replace(confirm, cumDur, Exp .copy(sumPlusCumDur)); conf.setAssertion(confirm); elseStmtList.set(elseStmtList.size() - 1, conf); } else { // Replace "Cum_Dur" with "Cum_Dur + Dur_Call(<num of args>) + <duration of call>" negIfConfirmExp = Utilities.replace(negIfConfirmExp, cumDur, Exp .copy(sumPlusCumDur)); } } // Add the statements inside the else to the assertive code negIfAssertiveCode.addStatements(elseStmtList); // Set the final else confirm negIfAssertiveCode.setFinalConfirm(negIfConfirmExp, negIfConfirm .getSimplify()); // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(negIfAssertiveCode); // Verbose Mode Debug Messages String newString = "\nNegation of If Part Rule Applied: \n"; newString += negIfAssertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the initialization rule.</p> * * @param dec Representation declaration object. */ private void applyInitializationRule(RepresentationDec dec) { // Create a new assertive code to hold the correspondence VCs AssertiveCode assertiveCode = new AssertiveCode(myInstanceEnvironment, dec); // Location for the assume clauses Location decLoc = dec.getLocation(); // Add the global constraints as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalConstraintExp, false); // Add the global require clause as given assertiveCode.addAssume((Location) decLoc.clone(), myGlobalRequiresExp, false); // Search for the type we are implementing SymbolTableEntry ste = Utilities.searchProgramType(dec.getLocation(), null, dec .getName(), myCurrentModuleScope); ProgramTypeEntry typeEntry; if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(dec.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(dec.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Add any variable declarations for records // TODO: Change this! The only variable we need to add is the exemplar Exp representationConstraint = myTypeGraph.getTrueVarExp(); List<ParameterVarDec> fieldAsParameters = new ArrayList<ParameterVarDec>(); if (dec.getRepresentation() instanceof RecordTy) { RecordTy ty = (RecordTy) dec.getRepresentation(); List<VarDec> decs = ty.getFields(); assertiveCode.addVariableDecs(decs); for (VarDec v : decs) { Ty vTy = v.getTy(); // Convert "v" into a parameter for substitution purposes fieldAsParameters.add(new ParameterVarDec(Mode.FIELD, v .getName(), vTy)); // Don't do anything if it is a generic type variable if (!(vTy.getProgramTypeValue() instanceof PTGeneric)) { // TODO: We could have a record ty here NameTy vTyAsNameTy = null; if (vTy instanceof NameTy) { vTyAsNameTy = (NameTy) v.getTy(); } else { Utilities.tyNotHandled(v.getTy(), v.getLocation()); } // Convert the raw type into a variable expression VarExp vTyAsVarExp = null; if (vTyAsNameTy.getQualifier() == null) { for (VarExp varExp : myInstantiatedFacilityArgMap .keySet()) { if (varExp.getName().getName().equals( vTyAsNameTy.getName().getName())) { if (vTyAsVarExp == null) { vTyAsVarExp = (VarExp) Exp.copy(varExp); } else { Utilities.ambiguousTy(vTy, v .getLocation()); } } } } else { vTyAsVarExp = Utilities.createVarExp(vTyAsNameTy .getLocation(), vTyAsNameTy .getQualifier(), vTyAsNameTy .getName(), vTyAsNameTy .getMathType(), vTyAsNameTy .getMathTypeValue()); } // Create a dotted expression to represent the record field "v" VarExp vAsVarExp = Utilities.createVarExp(v.getLocation(), null, v .getName(), vTyAsNameTy .getMathTypeValue(), null); edu.clemson.cs.r2jt.collections.List<Exp> dotExpList = new edu.clemson.cs.r2jt.collections.List<Exp>(); dotExpList.add(Exp.copy(exemplar)); dotExpList.add(vAsVarExp); DotExp dotExp = Utilities.createDotExp(v.getLocation(), dotExpList, vTyAsNameTy .getMathTypeValue()); // Obtain the constraint from this field Exp vConstraint = Utilities.retrieveConstraint(v.getLocation(), vTyAsVarExp, dotExp, myCurrentModuleScope); if (representationConstraint.isLiteralTrue()) { representationConstraint = vConstraint; } else { representationConstraint = myTypeGraph.formConjunct( representationConstraint, vConstraint); } } } } // Replace facility actuals variables in the ensures clause representationConstraint = Utilities.replaceFacilityFormalWithActual(decLoc, representationConstraint, fieldAsParameters, myInstantiatedFacilityArgMap, myCurrentModuleScope); // Add the representation constraint to our global map myRepresentationConstraintMap.put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation() .getMathTypeValue(), null), representationConstraint); // Add any statements in the initialization block if (dec.getInitialization() != null) { InitItem initItem = dec.getInitialization(); assertiveCode.addStatements(initItem.getStatements()); } // Make sure we have a convention Exp conventionExp; if (dec.getConvention() == null) { conventionExp = myTypeGraph.getTrueVarExp(); } else { conventionExp = Exp.copy(dec.getConvention()); } // Set the location for the constraint Location loc; if (conventionExp.getLocation() != null) { loc = (Location) conventionExp.getLocation().clone(); } else { loc = (Location) dec.getLocation().clone(); } loc.setDetails("Convention for " + dec.getName().getName()); Utilities.setLocation(conventionExp, loc); // Add the convention as something we need to confirm boolean simplify = false; // Simplify if we just have true if (conventionExp.isLiteralTrue()) { simplify = true; } Location conventionLoc = (Location) conventionExp.getLocation().clone(); conventionLoc.setDetails(conventionLoc.getDetails() + " generated by Initialization Rule"); Utilities.setLocation(conventionExp, conventionLoc); assertiveCode.addConfirm(loc, conventionExp, simplify); // Store the convention in our map myRepresentationConventionsMap .put(Utilities.createVarExp(decLoc, null, dec.getName(), dec.getRepresentation().getMathTypeValue(), null), Exp.copy(conventionExp)); // Add the correspondence as given Location corrLoc; if (dec.getCorrespondence().getLocation() != null) { corrLoc = (Location) dec.getCorrespondence().getLocation() .clone(); } else { corrLoc = (Location) decLoc.clone(); } corrLoc.setDetails("Correspondence for " + dec.getName().getName()); assertiveCode.addAssume(corrLoc, dec.getCorrespondence(), false); // Create a variable that refers to the conceptual exemplar DotExp conceptualVar = Utilities.createConcVarExp(null, exemplar, typeEntry .getModelType(), BOOLEAN); // Make sure we have a constraint Exp init; if (type.getInitialization().getEnsures() == null) { init = myTypeGraph.getTrueVarExp(); } else { init = Exp.copy(type.getInitialization().getEnsures()); } init = Utilities.replace(init, exemplar, conceptualVar); // Set the location for the constraint Location initLoc; initLoc = (Location) dec.getLocation().clone(); initLoc.setDetails("Initialization Rule for " + dec.getName().getName()); Utilities.setLocation(init, initLoc); // Add the initialization as something we need to confirm simplify = false; // Simplify if we just have true if (init.isLiteralTrue()) { simplify = true; } assertiveCode.addConfirm(loc, init, simplify); } // Add this new assertive code to our incomplete assertive code stack myIncAssertiveCodeStack.push(assertiveCode); // Verbose Mode Debug Messages String newString = "\n========================= Type Representation Name:\t" + dec.getName().getName() + " =========================\n"; newString += "\nInitialization Rule Applied: \n"; newString += assertiveCode.assertionToString(); newString += "\n_____________________ \n"; myIncAssertiveCodeStackInfo.push(newString); } /** * <p>Applies the procedure declaration rule.</p> * * @param opLoc Location of the procedure declaration. * @param name Name of the procedure. * @param requires Requires clause * @param ensures Ensures clause * @param decreasing Decreasing clause (if any) * @param procDur Procedure duration clause (if in performance mode) * @param varFinalDur Local variable finalization duration clause (if in performance mode) * @param parameterVarList List of all parameter variables for this procedure * @param variableList List of all variables for this procedure * @param statementList List of statements for this procedure * @param isLocal True if the it is a local operation. False otherwise. */ private void applyProcedureDeclRule(Location opLoc, String name, Exp requires, Exp ensures, Exp decreasing, Exp procDur, Exp varFinalDur, List<ParameterVarDec> parameterVarList, List<VarDec> variableList, List<Statement> statementList, boolean isLocal) { // Add the global requires clause if (myGlobalRequiresExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalRequiresExp, false); } // Add the global constraints if (myGlobalConstraintExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), myGlobalConstraintExp, false); } // Only do this if this is not a local operation // and we are in a concept realization Exp aggConventionExp = null; Exp aggCorrespondenceExp = null; if (!isLocal) { // Do this for all parameters that are type representations for (ParameterVarDec parameterVarDec : parameterVarList) { NameTy parameterVarDecTy = (NameTy) parameterVarDec.getTy(); Exp parameterAsVarExp = Utilities.createVarExp(parameterVarDec.getLocation(), null, parameterVarDec.getName(), parameterVarDecTy.getMathTypeValue(), null); Set<VarExp> conventionKeys = myRepresentationConventionsMap.keySet(); for (VarExp varExp : conventionKeys) { // Make sure the qualifiers are the same PosSymbol varExpQual = varExp.getQualifier(); PosSymbol parameterTyQual = parameterVarDecTy.getQualifier(); if ((varExpQual == null && parameterTyQual == null) || (varExpQual.getName().equals(parameterTyQual .getName()))) { // Make sure that the type names are the same if (varExp.getName().getName().equals( parameterVarDecTy.getName().getName())) { // Check to see if this is a type representation SymbolTableEntry typeEntry = Utilities.searchProgramType(opLoc, varExp .getQualifier(), varExp.getName(), myCurrentModuleScope); if (typeEntry instanceof RepresentationTypeEntry) { // Replacements MathSymbolEntry exemplarEntry = typeEntry.toRepresentationTypeEntry( opLoc).getDefiningTypeEntry() .getExemplar(); Exp exemplar = Utilities .createVarExp( opLoc, null, Utilities .createPosSymbol(exemplarEntry .getName()), exemplarEntry.getType(), null); Map<Exp, Exp> replacementMap = new HashMap<Exp, Exp>(); replacementMap.put(exemplar, parameterAsVarExp); // Obtain the convention and substitute formal with actual Exp conventionExp = Exp.copy(myRepresentationConventionsMap .get(varExp)); conventionExp = conventionExp .substitute(replacementMap); // Add the convention as something we need to ensure myCurrentAssertiveCode.addAssume( (Location) opLoc.clone(), conventionExp, false); // Store this convention in our aggregated convention exp if (aggConventionExp == null) { aggConventionExp = Exp.copy(conventionExp); } else { aggConventionExp = myTypeGraph.formConjunct( aggConventionExp, conventionExp); } aggConventionExp.setLocation(conventionExp .getLocation()); } } } } Set<VarExp> correspondencekeys = myRepresentationCorrespondenceMap.keySet(); for (VarExp varExp : correspondencekeys) { // Make sure the qualifiers are the same PosSymbol varExpQual = varExp.getQualifier(); PosSymbol parameterTyQual = parameterVarDecTy.getQualifier(); if ((varExpQual == null && parameterTyQual == null) || (varExpQual.getName().equals(parameterTyQual .getName()))) { // Make sure that the type names are the same if (varExp.getName().getName().equals( parameterVarDecTy.getName().getName())) { // Check to see if this is a type representation SymbolTableEntry typeEntry = Utilities.searchProgramType(opLoc, varExp .getQualifier(), varExp.getName(), myCurrentModuleScope); if (typeEntry instanceof RepresentationTypeEntry) { // Attempt to replace the correspondence for each parameter Location reqLoc = (Location) requires.getLocation() .clone(); Exp tmp = Exp.copy(requires); MathSymbolEntry exemplarEntry = typeEntry.toRepresentationTypeEntry( opLoc).getDefiningTypeEntry() .getExemplar(); // Replacements Exp exemplar = Utilities .createVarExp( opLoc, null, Utilities .createPosSymbol(exemplarEntry .getName()), exemplarEntry.getType(), null); Map<Exp, Exp> replacementMap = new HashMap<Exp, Exp>(); replacementMap.put(exemplar, parameterAsVarExp); // Obtain the correspondence and substitute formal with actual Exp corresponenceExp = Exp .copy(myRepresentationCorrespondenceMap .get(varExp)); corresponenceExp = corresponenceExp .substitute(replacementMap); if (corresponenceExp instanceof EqualsExp) { tmp = Utilities .replace( requires, ((EqualsExp) corresponenceExp) .getLeft(), ((EqualsExp) corresponenceExp) .getRight()); } // Well_Def_Corr_Hyp rule: Conjunct the correspondence to // the requires clause. This will ensure that the parsimonious // vc step replaces the requires clause if possible. if (tmp.equals(requires)) { requires = myTypeGraph.formConjunct(requires, Exp.copy(corresponenceExp)); } else { myCurrentAssertiveCode.addAssume( (Location) opLoc.clone(), Exp .copy(corresponenceExp), false); requires = tmp; } requires.setLocation(reqLoc); // Store this correspondence in our aggregated correspondence exp if (aggCorrespondenceExp == null) { aggCorrespondenceExp = Exp.copy(corresponenceExp); } else { aggCorrespondenceExp = myTypeGraph.formConjunct( aggCorrespondenceExp, corresponenceExp); } } } } } } } myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), requires, false); // NY - Add any procedure duration clauses InfixExp finalDurationExp = null; if (procDur != null) { // Add Cum_Dur as a free variable VarExp cumDur = Utilities.createVarExp((Location) opLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); myCurrentAssertiveCode.addFreeVar(cumDur); // Create 0.0 VarExp zeroPtZero = Utilities.createVarExp(opLoc, null, Utilities .createPosSymbol("0.0"), myTypeGraph.R, null); // Create an equals expression (Cum_Dur = 0.0) EqualsExp equalsExp = new EqualsExp(null, Exp.copy(cumDur), EqualsExp.EQUAL, zeroPtZero); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) opLoc.clone(); eqLoc.setDetails("Initialization of Cum_Dur for Procedure " + name); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); // Create the duration expression Exp durationExp; if (varFinalDur != null) { durationExp = new InfixExp(null, Exp.copy(cumDur), Utilities .createPosSymbol("+"), varFinalDur); } else { durationExp = Exp.copy(cumDur); } durationExp.setMathType(myTypeGraph.R); Location sumLoc = (Location) opLoc.clone(); sumLoc .setDetails("Summation of Finalization Duration for Procedure " + name); Utilities.setLocation(durationExp, sumLoc); finalDurationExp = new InfixExp(null, durationExp, Utilities .createPosSymbol("<="), procDur); finalDurationExp.setMathType(BOOLEAN); Location andLoc = (Location) opLoc.clone(); andLoc.setDetails("Duration Clause of " + name); Utilities.setLocation(finalDurationExp, andLoc); } // Add the remember rule myCurrentAssertiveCode.addCode(new MemoryStmt((Location) opLoc.clone(), true)); // Add declared variables into the assertion. Also add // them to the list of free variables. myCurrentAssertiveCode.addVariableDecs(variableList); addVarDecsAsFreeVars(variableList); // Check to see if we have a recursive procedure. // If yes, we will need to create an additional assume clause // (P_val = (decreasing clause)) in our list of assertions. if (decreasing != null) { // Store for future use myOperationDecreasingExp = decreasing; // Add P_val as a free variable VarExp pVal = Utilities.createPValExp(decreasing.getLocation(), myCurrentModuleScope); myCurrentAssertiveCode.addFreeVar(pVal); // Create an equals expression EqualsExp equalsExp = new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp .copy(decreasing)); equalsExp.setMathType(BOOLEAN); Location eqLoc = (Location) decreasing.getLocation().clone(); eqLoc.setDetails("Progress Metric for Recursive Procedure"); Utilities.setLocation(equalsExp, eqLoc); // Add it to our things to assume myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), equalsExp, false); } // Add the list of statements myCurrentAssertiveCode.addStatements(statementList); // Add the finalization duration ensures (if any) if (finalDurationExp != null) { myCurrentAssertiveCode.addConfirm(finalDurationExp.getLocation(), finalDurationExp, false); } // Correct_Op_Hyp rule: Only applies to non-local operations // in concept realizations. if (!isLocal && aggConventionExp != null) { if (!aggConventionExp.isLiteralTrue()) { Location conventionLoc = (Location) opLoc.clone(); conventionLoc.setDetails(aggConventionExp.getLocation() .getDetails() + " generated by " + name); Utilities.setLocation(aggConventionExp, conventionLoc); myCurrentAssertiveCode.addConfirm(aggConventionExp .getLocation(), aggConventionExp, false); } } // Well_Def_Corr_Hyp rule: Rather than doing direct replacement, // we leave that logic to the parsimonious vc step. A replacement // will occur if this is a correspondence function or an implies // will be formed if this is a correspondence relation. if (!isLocal && aggCorrespondenceExp != null) { myCurrentAssertiveCode.addAssume((Location) opLoc.clone(), aggCorrespondenceExp, false); } // Add the final confirms clause myCurrentAssertiveCode.setFinalConfirm(ensures, false); // Verbose Mode Debug Messages myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the remember rule.</p> */ private void applyRememberRule() { // Obtain the final confirm and apply the remember method for Exp ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); conf = conf.remember(); myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nRemember Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies each of the proof rules. This <code>AssertiveCode</code> will be * stored for later use and therefore should be considered immutable after * a call to this method.</p> */ private void applyRules() { // Apply a proof rule to each of the assertions while (myCurrentAssertiveCode.hasAnotherAssertion()) { // Work our way from the last assertion VerificationStatement curAssertion = myCurrentAssertiveCode.getLastAssertion(); switch (curAssertion.getType()) { // Change Assertion case VerificationStatement.CHANGE: applyChangeRule(curAssertion); break; // Code case VerificationStatement.CODE: applyCodeRules((Statement) curAssertion.getAssertion()); break; // Variable Declaration Assertion case VerificationStatement.VARIABLE: applyVarDeclRule(curAssertion); break; } } } /** * <p>Applies the swap statement rule to the * <code>Statement</code>.</p> * * @param stmt Our current <code>SwapStmt</code>. */ private void applySwapStmtRule(SwapStmt stmt) { // Obtain the current final confirm clause ConfirmStmt confirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp conf = confirmStmt.getAssertion(); // Create a copy of the left and right hand side VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); // New left and right Exp newLeft = Utilities.convertExp(stmtLeft, myCurrentModuleScope); Exp newRight = Utilities.convertExp(stmtRight, myCurrentModuleScope); // Use our final confirm to obtain the math types List lst = conf.getSubExpressions(); for (int i = 0; i < lst.size(); i++) { if (lst.get(i) instanceof VarExp) { VarExp thisExp = (VarExp) lst.get(i); if (newRight instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newRight).getName().getName())) { newRight.setMathType(thisExp.getMathType()); newRight.setMathTypeValue(thisExp.getMathTypeValue()); } } if (newLeft instanceof VarExp) { if (thisExp.getName().equals( ((VarExp) newLeft).getName().getName())) { newLeft.setMathType(thisExp.getMathType()); newLeft.setMathTypeValue(thisExp.getMathTypeValue()); } } } } // Temp variable VarExp tmp = new VarExp(); tmp.setName(Utilities.createPosSymbol("_" + Utilities.getVarName(stmtLeft).getName())); tmp.setMathType(stmtLeft.getMathType()); tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); // Replace according to the swap rule conf = Utilities.replace(conf, newRight, tmp); conf = Utilities.replace(conf, newLeft, newRight); conf = Utilities.replace(conf, tmp, newLeft); // NY YS // Duration for swap statements if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities .createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(conf)), myTypeGraph.R, null); Exp swapDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol("Dur_Swap"), myTypeGraph.R, null); InfixExp sumSwapDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), swapDur); sumSwapDur.setMathType(myTypeGraph.R); conf = Utilities.replace(conf, cumDur, sumSwapDur); } // Set this new expression as the new final confirm myCurrentAssertiveCode.setFinalConfirm(conf, confirmStmt.getSimplify()); // Verbose Mode Debug Messages myVCBuffer.append("\nSwap Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } /** * <p>Applies the variable declaration rule.</p> * * @param var A declared variable stored as a * <code>VerificationStatement</code> */ private void applyVarDeclRule(VerificationStatement var) { // Obtain the variable from the verification statement VarDec varDec = (VarDec) var.getAssertion(); ProgramTypeEntry typeEntry; // Ty is NameTy if (varDec.getTy() instanceof NameTy) { NameTy pNameTy = (NameTy) varDec.getTy(); // Query for the type entry in the symbol table SymbolTableEntry ste = Utilities.searchProgramType(pNameTy.getLocation(), pNameTy .getQualifier(), pNameTy.getName(), myCurrentModuleScope); if (ste instanceof ProgramTypeEntry) { typeEntry = ste.toProgramTypeEntry(pNameTy.getLocation()); } else { typeEntry = ste.toRepresentationTypeEntry(pNameTy.getLocation()) .getDefiningTypeEntry(); } // Make sure we don't have a generic type if (typeEntry.getDefiningElement() instanceof TypeDec) { // Obtain the original dec from the AST TypeDec type = (TypeDec) typeEntry.getDefiningElement(); // Create a variable expression from the declared variable VarExp varDecExp = Utilities.createVarExp(varDec.getLocation(), null, varDec.getName(), typeEntry.getModelType(), null); // Create a variable expression from the type exemplar VarExp exemplar = Utilities.createVarExp(type.getLocation(), null, type .getExemplar(), typeEntry.getModelType(), null); // Deep copy the original initialization ensures Exp init = Exp.copy(type.getInitialization().getEnsures()); init = Utilities.replace(init, exemplar, varDecExp); // Set the location for the initialization ensures Location loc; if (init.getLocation() != null) { loc = (Location) init.getLocation().clone(); } else { loc = (Location) type.getLocation().clone(); } loc.setDetails("Initialization ensures on " + varDec.getName().getName()); Utilities.setLocation(init, loc); // Final confirm clause Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); // Obtain the string form of the variable String varName = varDec.getName().getName(); // Check to see if we have a variable dot expression. // If we do, we will need to extract the name. int dotIndex = varName.indexOf("."); if (dotIndex > 0) { varName = varName.substring(0, dotIndex); } // Check to see if this variable was declared inside a record ResolveConceptualElement element = myCurrentAssertiveCode.getInstantiatingElement(); if (element instanceof RepresentationDec) { RepresentationDec dec = (RepresentationDec) element; if (dec.getRepresentation() instanceof RecordTy) { SymbolTableEntry repSte = Utilities.searchProgramType(dec.getLocation(), null, dec.getName(), myCurrentModuleScope); ProgramTypeDefinitionEntry representationTypeEntry = repSte.toRepresentationTypeEntry( pNameTy.getLocation()) .getDefiningTypeEntry(); // Create a variable expression from the type exemplar VarExp representationExemplar = Utilities .createVarExp( varDec.getLocation(), null, Utilities .createPosSymbol(representationTypeEntry .getExemplar() .getName()), representationTypeEntry .getModelType(), null); // Create a dotted expression edu.clemson.cs.r2jt.collections.List<Exp> expList = new edu.clemson.cs.r2jt.collections.List<Exp>(); expList.add(representationExemplar); expList.add(varDecExp); DotExp dotExp = Utilities.createDotExp(loc, expList, varDecExp .getMathType()); // Replace the initialization clauses appropriately init = Utilities.replace(init, varDecExp, dotExp); } } // Check if our confirm clause uses this variable if (finalConfirm.containsVar(varName, false)) { // Add the new assume clause to our assertive code. myCurrentAssertiveCode.addAssume((Location) loc.clone(), init, false); } } // Since the type is generic, we can only use the is_initial predicate // to ensure that the value is initial value. else { // Obtain the original dec from the AST Location varLoc = varDec.getLocation(); // Create an is_initial dot expression DotExp isInitialExp = Utilities.createInitExp(varDec, MTYPE, BOOLEAN); if (varLoc != null) { Location loc = (Location) varLoc.clone(); loc.setDetails("Initial Value for " + varDec.getName().getName()); Utilities.setLocation(isInitialExp, loc); } // Add to our assertive code as an assume myCurrentAssertiveCode.addAssume(varLoc, isInitialExp, false); } // NY YS // Initialization duration for this variable if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { ConfirmStmt finalConfirmStmt = myCurrentAssertiveCode.getFinalConfirm(); Exp finalConfirm = finalConfirmStmt.getAssertion(); Location loc = ((NameTy) varDec.getTy()).getName().getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(finalConfirm)), myTypeGraph.R, null); Exp initDur = Utilities.createInitAnyDur(varDec, myTypeGraph.R); InfixExp sumInitDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), initDur); sumInitDur.setMathType(myTypeGraph.R); finalConfirm = Utilities.replace(finalConfirm, cumDur, sumInitDur); myCurrentAssertiveCode.setFinalConfirm(finalConfirm, finalConfirmStmt.getSimplify()); } // Verbose Mode Debug Messages myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } else { // Ty not handled. Utilities.tyNotHandled(varDec.getTy(), varDec.getLocation()); } } /** * <p>Applies the while statement rule.</p> * * @param stmt Our current <code>WhileStmt</code>. */ private void applyWhileStmtRule(WhileStmt stmt) { // Obtain the loop invariant Exp invariant; boolean simplifyInvariant = false; if (stmt.getMaintaining() != null) { invariant = Exp.copy(stmt.getMaintaining()); invariant.setMathType(stmt.getMaintaining().getMathType()); // Simplify if we just have true if (invariant.isLiteralTrue()) { simplifyInvariant = true; } } else { invariant = myTypeGraph.getTrueVarExp(); simplifyInvariant = true; } // NY YS // Obtain the elapsed time duration of loop Exp elapsedTimeDur = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC)) { if (stmt.getElapsed_Time() != null) { elapsedTimeDur = Exp.copy(stmt.getElapsed_Time()); elapsedTimeDur.setMathType(myTypeGraph.R); } } // Confirm the base case of invariant Exp baseCase = Exp.copy(invariant); Location baseLoc; if (invariant.getLocation() != null) { baseLoc = (Location) invariant.getLocation().clone(); } else { baseLoc = (Location) stmt.getLocation().clone(); } baseLoc.setDetails("Base Case of the Invariant of While Statement"); Utilities.setLocation(baseCase, baseLoc); // NY YS // Confirm that elapsed time is 0.0 if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) && elapsedTimeDur != null) { Exp initElapseDurExp = Exp.copy(elapsedTimeDur); Location initElapseLoc; if (elapsedTimeDur != null && elapsedTimeDur.getLocation() != null) { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } else { initElapseLoc = (Location) elapsedTimeDur.getLocation().clone(); } initElapseLoc .setDetails("Base Case of Elapsed Time Duration of While Statement"); Utilities.setLocation(initElapseDurExp, initElapseLoc); Exp zeroEqualExp = new EqualsExp((Location) initElapseLoc.clone(), initElapseDurExp, 1, Utilities.createVarExp( (Location) initElapseLoc.clone(), null, Utilities.createPosSymbol("0.0"), myTypeGraph.R, null)); zeroEqualExp.setMathType(BOOLEAN); baseCase = myTypeGraph.formConjunct(baseCase, zeroEqualExp); } myCurrentAssertiveCode.addConfirm((Location) baseLoc.clone(), baseCase, simplifyInvariant); // Add the change rule if (stmt.getChanging() != null) { myCurrentAssertiveCode.addChange(stmt.getChanging()); } // Assume the invariant and NQV(RP, P_Val) = P_Exp Location whileLoc = stmt.getLocation(); Exp assume; Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm().getAssertion(); boolean simplifyFinalConfirm = myCurrentAssertiveCode.getFinalConfirm().getSimplify(); Exp decreasingExp = stmt.getDecreasing(); Exp nqv; if (decreasingExp != null) { VarExp pval = Utilities.createPValExp((Location) whileLoc.clone(), myCurrentModuleScope); nqv = Utilities.createQuestionMarkVariable(finalConfirm, pval); nqv.setMathType(pval.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), 1, Exp.copy(decreasingExp)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); } else { decreasingExp = myTypeGraph.getTrueVarExp(); nqv = myTypeGraph.getTrueVarExp(); assume = Exp.copy(invariant); } // NY YS // Also assume NQV(RP, Cum_Dur) = El_Dur_Exp Exp nqv2 = null; if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { VarExp cumDurExp = Utilities.createVarExp((Location) whileLoc.clone(), null, Utilities.createPosSymbol("Cum_Dur"), myTypeGraph.R, null); nqv2 = Utilities.createQuestionMarkVariable(finalConfirm, cumDurExp); nqv2.setMathType(cumDurExp.getMathType()); Exp equalPExp = new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv2), 1, Exp.copy(elapsedTimeDur)); equalPExp.setMathType(BOOLEAN); assume = myTypeGraph.formConjunct(assume, equalPExp); } myCurrentAssertiveCode.addAssume((Location) whileLoc.clone(), assume, false); // if statement body (need to deep copy!) edu.clemson.cs.r2jt.collections.List<Statement> ifStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); edu.clemson.cs.r2jt.collections.List<Statement> whileStmtList = stmt.getStatements(); for (Statement s : whileStmtList) { ifStmtList.add((Statement) s.clone()); } // Confirm the inductive case of invariant Exp inductiveCase = Exp.copy(invariant); Location inductiveLoc; if (invariant.getLocation() != null) { inductiveLoc = (Location) invariant.getLocation().clone(); } else { inductiveLoc = (Location) stmt.getLocation().clone(); } inductiveLoc .setDetails("Inductive Case of Invariant of While Statement"); Utilities.setLocation(inductiveCase, inductiveLoc); ifStmtList.add(new ConfirmStmt(inductiveLoc, inductiveCase, simplifyInvariant)); // Confirm the termination of the loop. if (decreasingExp != null) { Location decreasingLoc = (Location) decreasingExp.getLocation().clone(); if (decreasingLoc != null) { decreasingLoc.setDetails("Termination of While Statement"); } // Create a new infix expression IntegerExp oneExp = new IntegerExp(); oneExp.setValue(1); oneExp.setMathType(decreasingExp.getMathType()); InfixExp leftExp = new InfixExp(stmt.getLocation(), oneExp, Utilities .createPosSymbol("+"), Exp.copy(decreasingExp)); leftExp.setMathType(decreasingExp.getMathType()); Exp infixExp = Utilities.createLessThanEqExp(decreasingLoc, leftExp, Exp .copy(nqv), BOOLEAN); // Confirm NQV(RP, Cum_Dur) <= El_Dur_Exp if (nqv2 != null) { Location elapsedTimeLoc = (Location) elapsedTimeDur.getLocation().clone(); if (elapsedTimeLoc != null) { elapsedTimeLoc.setDetails("Termination of While Statement"); } Exp infixExp2 = Utilities.createLessThanEqExp(elapsedTimeLoc, Exp .copy(nqv2), Exp.copy(elapsedTimeDur), BOOLEAN); infixExp = myTypeGraph.formConjunct(infixExp, infixExp2); infixExp.setLocation(decreasingLoc); } ifStmtList.add(new ConfirmStmt(decreasingLoc, infixExp, false)); } else { throw new RuntimeException("No decreasing clause!"); } // empty elseif pair edu.clemson.cs.r2jt.collections.List<ConditionItem> elseIfPairList = new edu.clemson.cs.r2jt.collections.List<ConditionItem>(); // else body Location elseConfirmLoc; if (finalConfirm.getLocation() != null) { elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); } else { elseConfirmLoc = (Location) whileLoc.clone(); } edu.clemson.cs.r2jt.collections.List<Statement> elseStmtList = new edu.clemson.cs.r2jt.collections.List<Statement>(); // NY YS // Form the confirm clause for the else Exp elseConfirm = Exp.copy(finalConfirm); if (myInstanceEnvironment.flags.isFlagSet(FLAG_ALTPVCS_VC) & elapsedTimeDur != null) { Location loc = stmt.getLocation(); VarExp cumDur = Utilities.createVarExp((Location) loc.clone(), null, Utilities.createPosSymbol(Utilities .getCumDur(elseConfirm)), myTypeGraph.R, null); InfixExp sumWhileDur = new InfixExp((Location) loc.clone(), Exp.copy(cumDur), Utilities.createPosSymbol("+"), Exp .copy(elapsedTimeDur)); sumWhileDur.setMathType(myTypeGraph.R); elseConfirm = Utilities.replace(elseConfirm, cumDur, sumWhileDur); } elseStmtList.add(new ConfirmStmt(elseConfirmLoc, elseConfirm, simplifyFinalConfirm)); // condition ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); if (condition.getLocation() != null) { Location condLoc = (Location) condition.getLocation().clone(); condLoc.setDetails("While Loop Condition"); Utilities.setLocation(condition, condLoc); } // add it back to your assertive code IfStmt newIfStmt = new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); myCurrentAssertiveCode.addCode(newIfStmt); // Change our final confirm to "True" Exp trueVarExp = myTypeGraph.getTrueVarExp(); trueVarExp.setLocation((Location) whileLoc.clone()); myCurrentAssertiveCode.setFinalConfirm(trueVarExp, true); // Verbose Mode Debug Messages myVCBuffer.append("\nWhile Rule Applied: \n"); myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); myVCBuffer.append("\n_____________________ \n"); } }
Variable dec's initialization also need to substitute facility formal with actuals
src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java
Variable dec's initialization also need to substitute facility formal with actuals
Java
mit
f9fbaa9618afd84527c689b4dd859f426a279a76
0
FWDekker/intellij-randomness,FWDekker/intellij-randomness
package com.fwdekker.randomness.common; import javax.swing.JComponent; import org.jetbrains.annotations.NotNull; /** * An exception indicating that the validation of some {@code JComponent} has failed. */ public final class ValidationException extends Exception { private final JComponent component; /** * @param message the detail message * @param component the component * @see Exception#Exception(String) */ public ValidationException(final String message, @NotNull final JComponent component) { super(message); this.component = component; } /** * Returns the invalid component. * * @return the invalid component */ public JComponent getComponent() { return component; } }
src/main/java/com/fwdekker/randomness/common/ValidationException.java
package com.fwdekker.randomness.common; import javax.swing.JComponent; import org.jetbrains.annotations.NotNull; /** * An exception indicating that the validation of some {@code JComponent} has failed. */ public final class ValidationException extends Exception { private final JComponent component; /** * @param message the detail message * @param component the component * @see Exception#Exception(String) */ public ValidationException(final String message, @NotNull final JComponent component) { super(message); this.component = component; } /** * @param message the detail message * @param cause the cause * @param component the component * @see Exception#Exception(String, Throwable) */ public ValidationException(final String message, final Throwable cause, @NotNull final JComponent component) { super(message, cause); this.component = component; } /** * Returns the invalid component. * * @return the invalid component */ public JComponent getComponent() { return component; } }
Remove unused constructor
src/main/java/com/fwdekker/randomness/common/ValidationException.java
Remove unused constructor
Java
mit
0d2a89181b3ca26d5f268c59356897fe4bc00943
0
freecode/FreeVoteBot,freecode/FreeVoteBot,freecode/FreeVoteBot
package org.freecode.irc.votebot.modules.common; import org.freecode.irc.Notice; import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.NoticeFilter; import org.freecode.irc.votebot.api.CommandModule; import org.freecode.irc.votebot.dao.PollDAO; import org.freecode.irc.votebot.dao.VoteDAO; import org.freecode.irc.votebot.entity.Poll; import org.freecode.irc.votebot.entity.Vote; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; /** * Processes and validates voting commands sent by users * * @author Shivam Mistry */ public class VoteModule extends CommandModule { private PollDAO pollDAO; private VoteDAO voteDAO; public void processMessage(Privmsg privmsg) { String message = privmsg.getMessage(); if (message.startsWith("!v ") || message.startsWith("!vote ")) { final String msg = privmsg.getMessage().substring(privmsg.getMessage().indexOf(' ')).trim(); System.out.println(msg); final String[] split = msg.split(" ", 2); if (split.length == 2) { String ids = split[0]; String vote = split[1].toLowerCase(); final int nId; switch (vote) { case "yes": nId = 0; break; case "no": nId = 1; break; case "abstain": nId = 2; break; default: return; } if (!ids.matches("\\d+")) { return; } final int id = Integer.parseInt(ids); vote(nId, id, privmsg); } else if (split.length == 1) { String id = split[0]; if (!id.matches("\\d+")) { return; } try { int pollId = Integer.parseInt(id); Poll poll = pollDAO.getPoll(pollId); if (poll != null) { String expiry = getDateFormatter().format(new Date(poll.getExpiry())); String closed = poll.isClosed() ? "Closed" : "Open"; if (System.currentTimeMillis() >= poll.getExpiry()) { closed = "Expired"; } Vote[] votes = voteDAO.getVotesOnPoll(pollId); int yes = 0, no = 0, abstain = 0; for (Vote vote : votes) { int answerIndex = vote.getAnswerIndex(); if (answerIndex == 0) { yes++; } else if (answerIndex == 1) { no++; } else if (answerIndex == 2) { abstain++; } } boolean open = closed.equals("Open"); StringBuilder options = new StringBuilder(); String[] optionsSplit = poll.getOptions().split(","); for (int i = 0; i < optionsSplit.length; i++) { String option = optionsSplit[i]; options.append("\u0002"); options.append(option.charAt(0)); options.append("\u000F"); options.append(option.substring(1)); if (i != optionsSplit.length - 1) { options.append(", "); } } privmsg.send("Poll #" + poll.getId() + ": " + poll.getQuestion() + " Options: " + options.toString() + " Created by: " + poll.getCreator() + " Yes: " + yes + " No: " + no + " Abstain: " + abstain + " Status: \u00030" + (open ? "3" : "4") + closed + "\u0003" + (open ? " Ends: " : " Ended: ") + expiry); } } catch (SQLException e) { privmsg.send(e.getMessage()); } } } else if (message.startsWith("!y ")) { String id = message.replace("!y", "").trim(); if (id.matches("\\d+")) { voteYes(Integer.parseInt(id), privmsg); } } else if (message.startsWith("!n ")) { String id = message.replace("!n", "").trim(); if (id.matches("\\d+")) { voteNo(Integer.parseInt(id), privmsg); } } else if (message.startsWith("!a ")) { String id = message.replace("!a", "").trim(); if (id.matches("\\d+")) { voteAbstain(Integer.parseInt(id), privmsg); } } } private void voteYes(final int pollId, final Privmsg privmsg) { vote(0, pollId, privmsg); } private void voteNo(final int pollId, final Privmsg privmsg) { vote(1, pollId, privmsg); } private void voteAbstain(final int pollId, final Privmsg privmsg) { vote(2, pollId, privmsg); } private void vote(final int answerIndex, final int pollId, final Privmsg privmsg) { privmsg.getIrcConnection().addListener(new NoticeFilter() { public boolean accept(Notice notice) { if (notice.getNick().equals("ChanServ") && notice.getMessage().equals("Permission denied.")) { notice.getIrcConnection().removeListener(this); return false; } return notice.getNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains(privmsg.getNick()); } public void run(Notice notice) { try { String mainNick = notice.getMessage().substring(notice.getMessage().indexOf("Main nick:") + 10).trim(); System.out.println(mainNick); Poll poll = pollDAO.getPoll(pollId); if (poll != null) { long time = poll.getExpiry(); if (System.currentTimeMillis() < time && !poll.isClosed()) { Vote vote = voteDAO.getUsersVoteOnPoll(mainNick, pollId); if (vote != null) { if (vote.getAnswerIndex() == answerIndex) { privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "You've already voted with this option!", privmsg.getIrcConnection())); } else { vote.setAnswerIndex(answerIndex); voteDAO.updateUsersVote(vote); privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote updated.", privmsg.getIrcConnection())); } } else { voteDAO.addUsersVote(mainNick, pollId, answerIndex); privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote cast.", privmsg.getIrcConnection())); } } else { privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Voting is closed for this poll.", privmsg.getIrcConnection())); } } } catch (Exception e) { e.printStackTrace(); } privmsg.getIrcConnection().removeListener(this); } }); askChanServForUserCreds(privmsg); } private DateFormat getDateFormatter() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); return dateFormat; } public String getName() { return "(vote|v|y|n|a)"; } public void setPollDAO(PollDAO pollDAO) { this.pollDAO = pollDAO; } public void setVoteDAO(VoteDAO voteDAO) { this.voteDAO = voteDAO; } }
src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java
package org.freecode.irc.votebot.modules.common; import org.freecode.irc.Notice; import org.freecode.irc.Privmsg; import org.freecode.irc.votebot.NoticeFilter; import org.freecode.irc.votebot.api.CommandModule; import org.freecode.irc.votebot.dao.PollDAO; import org.freecode.irc.votebot.dao.VoteDAO; import org.freecode.irc.votebot.entity.Poll; import org.freecode.irc.votebot.entity.Vote; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; /** * Processes and validates voting commands sent by users * * @author Shivam Mistry */ public class VoteModule extends CommandModule { private PollDAO pollDAO; private VoteDAO voteDAO; public void processMessage(Privmsg privmsg) { String message = privmsg.getMessage(); if (message.startsWith("!v ") || message.startsWith("!vote ")) { final String msg = privmsg.getMessage().substring(privmsg.getMessage().indexOf(' ')).trim(); System.out.println(msg); final String[] split = msg.split(" ", 2); if (split.length == 2) { String ids = split[0]; String vote = split[1].toLowerCase(); final int nId; switch (vote) { case "yes": nId = 0; break; case "no": nId = 1; break; case "abstain": nId = 2; break; default: return; } if (!ids.matches("\\d+")) { return; } final int id = Integer.parseInt(ids); vote(nId, id, privmsg); } else if (split.length == 1) { String id = split[0]; if (!id.matches("\\d+")) { return; } try { int pollId = Integer.parseInt(id); Poll poll = pollDAO.getPoll(pollId); if (poll != null) { String expiry = getDateFormatter().format(new Date(poll.getExpiry())); String closed = poll.isClosed() ? "Closed" : "Open"; if (System.currentTimeMillis() >= poll.getExpiry()) { closed = "Expired"; } Vote[] votes = voteDAO.getVotesOnPoll(pollId); int yes = 0, no = 0, abstain = 0; for (Vote vote : votes) { int answerIndex = vote.getAnswerIndex(); if (answerIndex == 0) { yes++; } else if (answerIndex == 1) { no++; } else if (answerIndex == 2) { abstain++; } } boolean open = closed.equals("Open"); privmsg.send("Poll #" + poll.getId() + ": " + poll.getQuestion() + " Options: " + poll.getOptions() + " Created by: " + poll.getCreator() + " Yes: " + yes + " No: " + no + " Abstain: " + abstain + " Status: \u00030" + (open ? "3" : "4") + closed + "\u0003" + (open ? " Ends: " : " Ended: ") + expiry); } } catch (SQLException e) { privmsg.send(e.getMessage()); } } } else if (message.startsWith("!y ")) { String id = message.replace("!y", "").trim(); if (id.matches("\\d+")) { voteYes(Integer.parseInt(id), privmsg); } } else if (message.startsWith("!n ")) { String id = message.replace("!n", "").trim(); if (id.matches("\\d+")) { voteNo(Integer.parseInt(id), privmsg); } } else if (message.startsWith("!a ")) { String id = message.replace("!a", "").trim(); if (id.matches("\\d+")) { voteAbstain(Integer.parseInt(id), privmsg); } } } private void voteYes(final int pollId, final Privmsg privmsg) { vote(0, pollId, privmsg); } private void voteNo(final int pollId, final Privmsg privmsg) { vote(1, pollId, privmsg); } private void voteAbstain(final int pollId, final Privmsg privmsg) { vote(2, pollId, privmsg); } private void vote(final int answerIndex, final int pollId, final Privmsg privmsg) { privmsg.getIrcConnection().addListener(new NoticeFilter() { public boolean accept(Notice notice) { if (notice.getNick().equals("ChanServ") && notice.getMessage().equals("Permission denied.")) { notice.getIrcConnection().removeListener(this); return false; } return notice.getNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains(privmsg.getNick()); } public void run(Notice notice) { try { String mainNick = notice.getMessage().substring(notice.getMessage().indexOf("Main nick:") + 10).trim(); System.out.println(mainNick); Poll poll = pollDAO.getPoll(pollId); if (poll != null) { long time = poll.getExpiry(); if (System.currentTimeMillis() < time && !poll.isClosed()) { Vote vote = voteDAO.getUsersVoteOnPoll(mainNick, pollId); if (vote != null) { if (vote.getAnswerIndex() == answerIndex) { privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "You've already voted with this option!", privmsg.getIrcConnection())); } else { vote.setAnswerIndex(answerIndex); voteDAO.updateUsersVote(vote); privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote updated.", privmsg.getIrcConnection())); } } else { voteDAO.addUsersVote(mainNick, pollId, answerIndex); privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Vote cast.", privmsg.getIrcConnection())); } } else { privmsg.getIrcConnection().send(new Notice(privmsg.getNick(), "Voting is closed for this poll.", privmsg.getIrcConnection())); } } } catch (Exception e) { e.printStackTrace(); } privmsg.getIrcConnection().removeListener(this); } }); askChanServForUserCreds(privmsg); } private DateFormat getDateFormatter() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); return dateFormat; } public String getName() { return "(vote|v|y|n|a)"; } public void setPollDAO(PollDAO pollDAO) { this.pollDAO = pollDAO; } public void setVoteDAO(VoteDAO voteDAO) { this.voteDAO = voteDAO; } }
Slightly format !v
src/main/java/org/freecode/irc/votebot/modules/common/VoteModule.java
Slightly format !v
Java
mit
88c9da74ba30a804697295f7ac2e18de62dfadfc
0
Dauth/TextBuddy,Dauth/TextBuddy
import static org.junit.Assert.*; import java.util.*; import org.junit.*; public class TextBuddyTest { static TextBuddy curr; String newLine=System.lineSeparator(); private static String MSG_ADD="added to %s: \"%s\"\n"; private static String MSG_CLEAR="all content deleted from %s\n"; private static String MSG_DELETE="deleted from %s: \"%s\"\n"; static String fileName; @BeforeClass public static void setUpBeforeClass() throws Exception { fileName="testfile.txt"; curr=new TextBuddy(fileName); } @After public void tearDown() throws Exception { curr.wipeFileOperation(); } @Test public void testAddOperation() { assertEquals(String.format(MSG_ADD, fileName,"New Guinea"), curr.commandOperations("add New Guinea")); assertEquals(String.format(MSG_ADD, fileName,"Ellesmere Island"), curr.commandOperations("add Ellesmere Island")); assertEquals(2,curr.getListSize()); } @Test public void testDeleteOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); String expectedDeletedLine="Yos Sudarso"; assertEquals(String.format(MSG_DELETE, fileName, expectedDeletedLine), curr.commandOperations("delete 3")); assertEquals(3,curr.getListSize()); } @Test public void testSearchOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); String expectedLines="1. Kodiak Island"+newLine+"2. King George Island"+newLine; assertEquals(expectedLines, curr.commandOperations("search Island")); } @Test public void testSortAndDisplayOperation(){ String expectedsortedLines="1. King George Island"+newLine+"2. Kodiak Island"+newLine+"3. Rangsang"+newLine+"4. Yos Sudarso"+newLine; assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); curr.commandOperations("sort"); String actualLines=curr.commandOperations("display"); assertEquals(expectedsortedLines, actualLines); } @Test public void testClearOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); assertEquals(4, curr.getListSize()); assertEquals(String.format(MSG_CLEAR, fileName), curr.commandOperations("clear")); assertEquals(0, curr.getListSize()); } }
src/TextBuddyTest.java
import static org.junit.Assert.*; import java.util.*; import org.junit.*; public class TextBuddyTest { static TextBuddy curr; private static String MSG_ADD="added to %s: \"%s\"\n"; private static String MSG_CLEAR="all content deleted from %s\n"; private static String MSG_DELETE="deleted from %s: \"%s\"\n"; static String fileName; @BeforeClass public static void setUpBeforeClass() throws Exception { fileName="testfile.txt"; curr=new TextBuddy(fileName); } @After public void tearDown() throws Exception { curr.wipeFileOperation(); } @Test public void testAddOperation() { assertEquals(String.format(MSG_ADD, fileName,"New Guinea"), curr.commandOperations("add New Guinea")); assertEquals(String.format(MSG_ADD, fileName,"Ellesmere Island"), curr.commandOperations("add Ellesmere Island")); System.out.println("out add "+curr.getListSize()); } @Test public void testDeleteOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); System.out.println("in delete "+curr.getListSize()); int randNum=1+(int)(Math.random()*curr.getListSize()); System.out.println("my rand num is "+randNum); String toBeDeletedLine=curr.txtList.get(randNum-1); System.out.println("line to be deleted "+toBeDeletedLine); assertEquals(String.format(MSG_DELETE, fileName, toBeDeletedLine), curr.commandOperations("delete "+ randNum)); } @Test public void testSearchOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); System.out.println("in search "+curr.getListSize()); } @Test public void testSortAndDisplayOperation(){ String newLine=System.lineSeparator(); String sortedString="1. King George Island"+newLine+"2. Kodiak Island"+newLine+"3. Rangsang"+newLine+"4. Yos Sudarso"+newLine; assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); System.out.println("in sort "+curr.getListSize()); curr.commandOperations("sort"); String temp=curr.commandOperations("display"); assertEquals(sortedString, temp); } @Test public void testClearOperation(){ assertEquals(String.format(MSG_ADD, fileName,"Kodiak Island"), curr.commandOperations("add Kodiak Island")); assertEquals(String.format(MSG_ADD, fileName,"King George Island"), curr.commandOperations("add King George Island")); assertEquals(String.format(MSG_ADD, fileName,"Yos Sudarso"), curr.commandOperations("add Yos Sudarso")); assertEquals(String.format(MSG_ADD, fileName,"Rangsang"), curr.commandOperations("add Rangsang")); System.out.println("in clear "+curr.getListSize()); assertEquals(String.format(MSG_CLEAR, fileName), curr.commandOperations("clear")); assertEquals(0, curr.getListSize()); System.out.println("out clear "+curr.getListSize()); } }
refined junit testing
src/TextBuddyTest.java
refined junit testing
Java
mit
28869aeb3992e348c83a284a7844361ea0322718
0
viniciusfernandes/jmockit1,maddingo/jmockit1,russelyang/jmockit1,maddingo/jmockit1,beluchin/jmockit1,viniciusfernandes/jmockit1,russelyang/jmockit1,beluchin/jmockit1
/* * Copyright (c) 2006-2014 Rogério Liesenfeld * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package mockit.internal.util; import java.lang.reflect.*; import org.jetbrains.annotations.*; /** * Provides optimized utility methods to extract stack trace information. */ public final class StackTrace { private static final Method getStackTraceDepth = getThrowableMethod("getStackTraceDepth"); private static final Method getStackTraceElement = getThrowableMethod("getStackTraceElement", int.class); @Nullable private static Method getThrowableMethod(@NotNull String name, @NotNull Class<?>... parameterTypes) { Method method; try { method = Throwable.class.getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException ignore) { return null; } method.setAccessible(true); return method; } @NotNull private final Throwable throwable; @Nullable private final StackTraceElement[] elements; public StackTrace() { this(new Throwable()); } public StackTrace(@NotNull Throwable throwable) { this.throwable = throwable; elements = getStackTraceDepth == null ? throwable.getStackTrace() : null; } public int getDepth() { if (elements != null) { return elements.length; } int depth = 0; try { depth = (Integer) getStackTraceDepth.invoke(throwable); } catch (IllegalAccessException ignore) {} catch (InvocationTargetException ignored) {} return depth; } @NotNull public StackTraceElement getElement(int index) { return elements == null ? getElement(throwable, index) : elements[index]; } @NotNull public static StackTraceElement getElement(@NotNull Throwable throwable, int index) { try { return (StackTraceElement) getStackTraceElement.invoke(throwable, index); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } public static void filterStackTrace(@NotNull Throwable t) { new StackTrace(t).filter(); } public void filter() { int n = getDepth(); StackTraceElement[] filteredST = new StackTraceElement[n]; int j = 0; for (int i = 0; i < n; i++) { StackTraceElement ste = getElement(i); if (ste.getFileName() != null) { String where = ste.getClassName(); if (!isSunMethod(ste) && !isTestFrameworkMethod(where) && !isJMockitMethod(where)) { filteredST[j] = ste; j++; } } } StackTraceElement[] newStackTrace = new StackTraceElement[j]; System.arraycopy(filteredST, 0, newStackTrace, 0, j); throwable.setStackTrace(newStackTrace); Throwable cause = throwable.getCause(); if (cause != null) { new StackTrace(cause).filter(); } } private static boolean isSunMethod(@NotNull StackTraceElement ste) { return ste.getClassName().startsWith("sun.") && !ste.isNativeMethod(); } private static boolean isTestFrameworkMethod(@NotNull String where) { return where.startsWith("org.junit.") || where.startsWith("org.testng."); } private static boolean isJMockitMethod(@NotNull String where) { if (!where.startsWith("mockit.")) { return false; } int p = where.indexOf('$'); if (p < 0) { int q = where.lastIndexOf("Test"); return q < 0 || q + 4 < where.length(); } int q = where.lastIndexOf("Test", p - 4); if (q < 0) { return true; } q += 4; return q < where.length() && where.charAt(q) != '$'; } }
main/src/mockit/internal/util/StackTrace.java
/* * Copyright (c) 2006-2014 Rogério Liesenfeld * This file is subject to the terms of the MIT license (see LICENSE.txt). */ package mockit.internal.util; import java.lang.reflect.*; import org.jetbrains.annotations.*; /** * Provides optimized utility methods to extract stack trace information. */ public final class StackTrace { private static final Method getStackTraceDepth = getThrowableMethod("getStackTraceDepth"); private static final Method getStackTraceElement = getThrowableMethod("getStackTraceElement", int.class); @Nullable private static Method getThrowableMethod(@NotNull String name, @NotNull Class<?>... parameterTypes) { Method method; try { method = Throwable.class.getDeclaredMethod(name, parameterTypes); } catch (NoSuchMethodException ignore) { return null; } method.setAccessible(true); return method; } @NotNull private final Throwable throwable; @Nullable private final StackTraceElement[] elements; public StackTrace() { this(new Throwable()); } public StackTrace(@NotNull Throwable throwable) { this.throwable = throwable; elements = getStackTraceDepth == null ? throwable.getStackTrace() : null; } public int getDepth() { if (elements != null) { return elements.length; } int depth = 0; try { depth = (Integer) getStackTraceDepth.invoke(throwable); } catch (IllegalAccessException ignore) {} catch (InvocationTargetException ignored) {} return depth; } @NotNull public StackTraceElement getElement(int index) { return elements == null ? getElement(throwable, index) : elements[index]; } @NotNull public static StackTraceElement getElement(@NotNull Throwable throwable, int index) { try { return (StackTraceElement) getStackTraceElement.invoke(throwable, index); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } public static void filterStackTrace(@NotNull Throwable t) { new StackTrace(t).filter(); } public void filter() { int n = getDepth(); StackTraceElement[] filteredST = new StackTraceElement[n]; int j = 0; for (int i = 0; i < n; i++) { StackTraceElement ste = getElement(i); if (ste.getFileName() != null) { String where = ste.getClassName(); if (!isSunMethod(ste) && !isTestFrameworkMethod(where) && !isJMockitMethod(where)) { filteredST[j] = ste; j++; } } } StackTraceElement[] newStackTrace = new StackTraceElement[j]; System.arraycopy(filteredST, 0, newStackTrace, 0, j); throwable.setStackTrace(newStackTrace); Throwable cause = throwable.getCause(); if (cause != null) { new StackTrace(cause).filter(); } } private static boolean isSunMethod(@NotNull StackTraceElement ste) { return ste.getClassName().startsWith("sun.") && !ste.isNativeMethod(); } private static boolean isTestFrameworkMethod(@NotNull String where) { return where.startsWith("org.junit.") || where.startsWith("org.testng."); } private static boolean isJMockitMethod(@NotNull String where) { if (!where.startsWith("mockit.")) { return false; } int p = where.lastIndexOf("Test") + 4; if (p < 4) { return true; } return p < where.length() && where.charAt(p) != '$'; } }
Fixed minor bug in stack trace filtering.
main/src/mockit/internal/util/StackTrace.java
Fixed minor bug in stack trace filtering.
Java
mit
045c4794bf6178597c2a4c1673a13f88d86dc502
0
StefanoMartella/GamingPlatform
package model.dao.concrete; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.TreeMap; import model.dao.interfaces.UtenteDaoInterface; import model.database.DB; import model.*; public class UtenteDao implements UtenteDaoInterface{ private static final String INSERT = "INSERT INTO utente(nome, cognome, username, email, password) VALUES (?, ?, ?, ?, ?);"; private static final String DELETE = "DELETE FROM utente WHERE id = ?;"; private static final String ALL = "SELECT * FROM utente;"; private static final String DELETE_ALL = "DELETE FROM utente;"; private static final String FIND_BY_USERNAME = "SELECT * FROM utente WHERE username = ?;"; private static final String PLAY = "UPDATE utente SET puntiExp = ? + ? WHERE username = ?;"; private static final String UPDATE_LEVEL = "UPDATE utente SET livello = ? WHERE username = ?;"; private static final String VOTE_GAME = "INSERT INTO voto(votazione, gioco, utente) VALUES (?, ?, ?);"; private static final String REVIEW_GAME = "INSERT INTO recensione(testo, gioco, utente) VALUES (?, ?, ?);"; private static final String APPROVE_REVIEW = "UPDATE recensione SET approvazione = 1 WHERE id = ?;"; private static final String PROMOTE_USER = "UPDATE utente SET tipo = \"moderatore\" WHERE id = ?;"; private static final String DEMOTE_USER = "UPDATE utente SET tipo = \"utente\" WHERE id = ?;"; private static final String GET_TIMELINE = "SELECT * FROM timeline WHERE utente = ?;"; private static final String GAME_ALREADY_VOTED = "SELECT COUNT(*) AS total FROM voto WHERE utente = ? and gioco = ?;"; private static final String GAME_ALREADY_REVIEWED = "SELECT COUNT(*) AS total FROM recensione WHERE utente = ? and gioco = ?;"; private static final String USERNAME_ALREADY_USED = "SELECT COUNT(*) AS total FROM utente WHERE username = ?;"; private static final String EMAIL_ALREADY_USED = "SELECT COUNT(*) AS total FROM utente WHERE email = ?;"; @Override public void insertUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(INSERT); ps.setString(1, utente.getNome()); ps.setString(2, utente.getCognome()); ps.setString(3, utente.getUsername()); ps.setString(4, utente.getEmail()); ps.setString(5, utente.getPassword()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void deleteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(DELETE); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public ArrayList<Utente> allUsers() throws SQLException{ ArrayList<Utente> all_users = new ArrayList<>(); Connection connection = DB.openConnection(); Statement s = connection.createStatement(); ResultSet rset = s.executeQuery(ALL); while (rset.next()){ Utente utente = new Utente(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getString(6), rset.getString(7), rset.getInt(8), rset.getInt(9)); all_users.add(utente); } s.close(); rset.close(); connection.close(); return all_users; } @Override public void deleteAllUsers() throws SQLException{ Connection connection = DB.openConnection(); Statement s = connection.createStatement(); s.executeUpdate(DELETE_ALL); s.close(); connection.close(); } @Override public Utente findUserByUsername(String username) throws SQLException{ Utente utente; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(FIND_BY_USERNAME); ps.setString(1, username); ResultSet rset = ps.executeQuery(); if (rset.first() == false) return null; utente = new Utente(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getString(6), rset.getString(7), rset.getInt(8), rset.getInt(9)); ps.close(); rset.close(); connection.close(); return utente; } @Override public void play(Utente ut, Gioco g) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(PLAY); ps.setInt(1, ut.getPuntiExp()); ps.setInt(2, g.getExp()); ps.setString(3, ut.getUsername()); ps.executeUpdate(); ps.close(); PreparedStatement ps2 = connection.prepareStatement(UPDATE_LEVEL); if(ut.getPuntiExp()>= 500) ps2.setInt(1, 5); else ps2.setInt(1, (ut.getPuntiExp()+g.getExp())/100); ps2.setString(2, ut.getUsername()); ps2.executeUpdate(); ps2.close(); connection.close(); ut.setPuntiExp(ut.getPuntiExp()+g.getExp()); if(ut.getPuntiExp()>= 500){ ut.setLivello(5); } else ut.setLivello(ut.getPuntiExp()/100); } @Override public void voteGame(int voto, Utente utente, Gioco gioco) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(VOTE_GAME); ps.setInt(1, voto); ps.setInt(2, gioco.getId()); ps.setInt(3, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void reviewGame(String testoRecensione, Utente utente, Gioco gioco) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(REVIEW_GAME); ps.setString(1, testoRecensione); ps.setInt(2, gioco.getId()); ps.setInt(3, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void approveReview(Recensione recensione) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(APPROVE_REVIEW); ps.setInt(1, recensione.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void promoteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(PROMOTE_USER); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void demoteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(DEMOTE_USER); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void disapproveReview(Recensione recensione) throws SQLException{ new RecensioneDao().deleteReview(recensione); } @Override public TreeMap<Integer, String> getTimeline(Utente utente) throws SQLException{ TreeMap<Integer, String> timeline = new TreeMap<>(); Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GET_TIMELINE); ps.setInt(1, utente.getId()); ResultSet rset = ps.executeQuery(); while (rset.next()){ timeline.put(rset.getInt(2), rset.getDate(1).toString()); } ps.close(); rset.close(); connection.close(); return timeline; } @Override public boolean gameAlreadyVotedByUser(Utente utente, Gioco gioco) throws SQLException{ boolean already_voted = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_VOTED); ps.setInt(1, utente.getId()); ps.setInt(2, gioco.getId()); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ already_voted = true; } ps.close(); rset.close(); connection.close(); return already_voted; } @Override public boolean reviewAlreadyMadeByUser(Utente utente, Gioco gioco) throws SQLException{ boolean already_reviewed = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_REVIEWED); ps.setInt(1, utente.getId()); ps.setInt(2, gioco.getId()); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ already_reviewed = true; } ps.close(); rset.close(); connection.close(); return already_reviewed; } public boolean usernameOrEmailAlreadyUsed(String QUERY, String email_or_username) throws SQLException{ boolean username_or_email_used = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(QUERY); ps.setString(1, email_or_username); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ username_or_email_used = true; } ps.close(); rset.close(); connection.close(); return username_or_email_used; } @Override public boolean usernameAlreadyUsed(String username) throws SQLException{ return usernameOrEmailAlreadyUsed(USERNAME_ALREADY_USED, username); } @Override public boolean emailAlreadyUsed(String email) throws SQLException{ return usernameOrEmailAlreadyUsed(EMAIL_ALREADY_USED, email); } }
src/model/dao/concrete/UtenteDao.java
package model.dao.concrete; import java.sql.Connection; import java.sql.Statement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.TreeMap; import model.dao.interfaces.UtenteDaoInterface; import model.database.DB; import model.*; public class UtenteDao implements UtenteDaoInterface{ private static final String INSERT = "INSERT INTO utente(nome, cognome, username, email, password) VALUES (?, ?, ?, ?, ?);"; private static final String DELETE = "DELETE FROM utente WHERE id = ?;"; private static final String ALL = "SELECT * FROM utente;"; private static final String DELETE_ALL = "DELETE FROM utente;"; private static final String FIND_BY_USERNAME = "SELECT * FROM utente WHERE username = ?;"; private static final String PLAY = "UPDATE utente SET puntiExp = ? + ? WHERE username = ?;"; private static final String UPDATE_LEVEL = "UPDATE utente SET livello = ? WHERE username = ?;"; private static final String VOTE_GAME = "INSERT INTO voto(votazione, gioco, utente) VALUES (?, ?, ?);"; private static final String REVIEW_GAME = "INSERT INTO recensione(testo, gioco, utente) VALUES (?, ?, ?);"; private static final String APPROVE_REVIEW = "UPDATE recensione SET approvazione = 1 WHERE id = ?;"; private static final String PROMOTE_USER = "UPDATE utente SET tipo = \"moderatore\" WHERE id = ?;"; private static final String DEMOTE_USER = "UPDATE utente SET tipo = \"utente\" WHERE id = ?;"; private static final String GET_TIMELINE = "SELECT * FROM timeline WHERE utente = ?;"; private static final String GAME_ALREADY_VOTED = "SELECT COUNT(*) AS total FROM voto WHERE utente = ? and gioco = ?;"; private static final String GAME_ALREADY_REVIEWED = "SELECT COUNT(*) AS total FROM recensione WHERE utente = ? and gioco = ?;"; private static final String USERNAME_ALREADY_USED = "SELECT COUNT(*) AS total FROM utente WHERE username = ?;"; private static final String EMAIL_ALREADY_USED = "SELECT COUNT(*) AS total FROM utente WHERE email = ?;"; @Override public void insertUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(INSERT); ps.setString(1, utente.getNome()); ps.setString(2, utente.getCognome()); ps.setString(3, utente.getUsername()); ps.setString(4, utente.getEmail()); ps.setString(5, utente.getPassword()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void deleteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(DELETE); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public ArrayList<Utente> allUsers() throws SQLException{ ArrayList<Utente> all_users = new ArrayList<>(); Connection connection = DB.openConnection(); Statement s = connection.createStatement(); ResultSet rset = s.executeQuery(ALL); while (rset.next()){ Utente utente = new Utente(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getString(6), rset.getString(7), rset.getInt(8), rset.getInt(9)); all_users.add(utente); } s.close(); rset.close(); connection.close(); return all_users; } @Override public void deleteAllUsers() throws SQLException{ Connection connection = DB.openConnection(); Statement s = connection.createStatement(); s.executeUpdate(DELETE_ALL); s.close(); connection.close(); } @Override public Utente findUserByUsername(String username) throws SQLException{ Utente utente; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(FIND_BY_USERNAME); ps.setString(1, username); ResultSet rset = ps.executeQuery(); if (rset.first() == false) return null; utente = new Utente(rset.getInt(1), rset.getString(2), rset.getString(3), rset.getString(4), rset.getString(5), rset.getString(6), rset.getString(7), rset.getInt(8), rset.getInt(9)); ps.close(); rset.close(); connection.close(); return utente; } @Override public void play(Utente ut, Gioco g) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(PLAY); ps.setInt(1, ut.getPuntiExp()); ps.setInt(2, g.getExp()); ps.setString(3, ut.getUsername()); ps.executeUpdate(); ps.close(); PreparedStatement ps2 = connection.prepareStatement(UPDATE_LEVEL); if(ut.getPuntiExp()>= 500) ps2.setInt(1, 5); else ps2.setInt(1, (ut.getPuntiExp()+g.getExp())/100); ps2.setString(2, ut.getUsername()); ps2.executeUpdate(); ps2.close(); connection.close(); ut.setPuntiExp(ut.getPuntiExp()+g.getExp()); if(ut.getPuntiExp()>= 500){ ut.setLivello(5); } else ut.setLivello(ut.getPuntiExp()/100); } @Override public void voteGame(int voto, Utente utente, Gioco gioco) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(VOTE_GAME); ps.setInt(1, voto); ps.setInt(2, gioco.getId()); ps.setInt(3, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void reviewGame(String testoRecensione, Utente utente, Gioco gioco) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(REVIEW_GAME); ps.setString(1, testoRecensione); ps.setInt(2, gioco.getId()); ps.setInt(3, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void approveReview(Recensione recensione) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(APPROVE_REVIEW); ps.setInt(1, recensione.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void promoteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(PROMOTE_USER); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void demoteUser(Utente utente) throws SQLException{ Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(DEMOTE_USER); ps.setInt(1, utente.getId()); ps.executeUpdate(); ps.close(); connection.close(); } @Override public void disapproveReview(Recensione recensione) throws SQLException{ new RecensioneDao().deleteReview(recensione); } @Override public TreeMap<Integer, String> getTimeline(Utente utente) throws SQLException{ TreeMap<Integer, String> timeline = new TreeMap<>(); Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GET_TIMELINE); ps.setInt(1, utente.getId()); ResultSet rset = ps.executeQuery(); while (rset.next()){ timeline.put(rset.getInt(2), rset.getDate(1).toString()); } ps.close(); rset.close(); connection.close(); return timeline; } @Override public boolean gameAlreadyVotedByUser(Utente utente, Gioco gioco) throws SQLException{ boolean already_voted = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_VOTED); ps.setInt(1, utente.getId()); ps.setInt(2, gioco.getId()); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ already_voted = true; } ps.close(); rset.close(); connection.close(); return already_voted; } @Override public boolean reviewAlreadyMadeByUser(Utente utente, Gioco gioco) throws SQLException{ boolean already_reviewed = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(GAME_ALREADY_REVIEWED); ps.setInt(1, utente.getId()); ps.setInt(2, gioco.getId()); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ already_reviewed = true; } ps.close(); rset.close(); connection.close(); return already_reviewed; } public boolean usernameOrEmailAlreadyUsed(String QUERY, String email_or_username) throws SQLException{ boolean username_or_email_used = false; Connection connection = DB.openConnection(); PreparedStatement ps = connection.prepareStatement(QUERY); ps.setString(1, email_or_username); ResultSet rset = ps.executeQuery(); rset.first(); if(rset.getInt(1) == 1){ username_or_email_used = true; } ps.close(); rset.close(); connection.close(); return username_or_email_used; } @Override public boolean usernameAlreadyUsed(String username) throws SQLException{ return usernameOrEmailAlreadyUsed(USERNAME_ALREADY_USED, username); } @Override public boolean emailAlreadyUsed(String email) throws SQLException{ return usernameOrEmailAlreadyUsed(EMAIL_ALREADY_USED, email); } }
Update UtenteDao.java
src/model/dao/concrete/UtenteDao.java
Update UtenteDao.java
Java
mit
924fe8caad336bedfa836b9c7de0ec951a434d52
0
codistmonk/IMJ
package imj2.tools; import static java.awt.Color.RED; import static net.sourceforge.aprog.swing.SwingTools.show; import static net.sourceforge.aprog.tools.Tools.debugPrint; import static org.junit.Assert.*; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import imj2.tools.Image2DComponent.Painter; import imj2.tools.RegionShrinkingTest.AutoMouseAdapter; import imj2.tools.RegionShrinkingTest.SimpleImageView; import net.sourceforge.aprog.tools.Tools; import org.junit.Test; /** * @author codistmonk (creation 2014-02-07) */ public final class MultiresolutionSegmentationTest { @Test public final void test() { final SimpleImageView imageView = new SimpleImageView(); new AutoMouseAdapter(imageView.getImageHolder()) { private BufferedImage[] pyramid; private int cellSize = 32; private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() { private final List<Point> particles = new ArrayList<Point>(); { imageView.getPainters().add(this); } @Override public final void paint(final Graphics2D g, final SimpleImageView component, final int width, final int height) { refreshLODs(); this.particles.clear(); final BufferedImage[] pyramid = getPyramid(); final int s = getCellSize(); int w = 0; int h = 0; for (int lod = pyramid.length - 1; 0 <= lod; --lod) { for (final Point particle : this.particles) { particle.x *= 2; particle.y *= 2; } final BufferedImage image = pyramid[lod]; if (w == 0) { w = image.getWidth(); h = image.getHeight(); } else { w *= 2; h *= 2; } if (s < w && s < h) { debugPrint(lod, w, h); for (int y = s, ky = 1; y < h; y += s, ++ky) { for (int x = s, kx = 1; x < w; x += s, ++kx) { if ((kx & 1) != 0 || (ky & 1) != 0) { this.particles.add(new Point(x, y)); } } } } } debugPrint(this.particles.size()); g.setColor(RED); for (final Point particle : this.particles) { g.drawOval(particle.x - 1, particle.y - 1, 3, 3); } } /** * {@value}. */ private static final long serialVersionUID = -8692596860025480748L; }; @Override public final void mouseWheelMoved(final MouseWheelEvent event) { imageView.refreshBuffer(); } public final boolean refreshLODs() { if (this.getPyramid() == null || this.getPyramid().length == 0 || this.getPyramid()[0] != imageView.getImage()) { this.pyramid = makePyramid(imageView.getImage()); return true; } return false; } public final BufferedImage[] getPyramid() { return this.pyramid; } public final int getCellSize() { return this.cellSize; } @Override protected final void cleanup() { imageView.getPainters().remove(this.painter); } /** * {@value}. */ private static final long serialVersionUID = 3954986726959359787L; }; show(imageView, "Simple Image View", true); } public static final BufferedImage[] makePyramid(final BufferedImage lod0) { final List<BufferedImage> lods = new ArrayList<BufferedImage>(); BufferedImage lod = lod0; int w = lod.getWidth(); int h = lod.getHeight(); do { lods.add(lod); final BufferedImage nextLOD = new BufferedImage(w /= 2, h /= 2, lod.getType()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { final int c00 = lod.getRGB(2 * x + 0, 2 * y + 0); final int c10 = lod.getRGB(2 * x + 1, 2 * y + 0); final int c01 = lod.getRGB(2 * x + 0, 2 * y + 1); final int c11 = lod.getRGB(2 * x + 1, 2 * y + 1); nextLOD.setRGB(x, y, mean(red(c00), red(c10), red(c01), red(c11)) | mean(green(c00), green(c10), green(c01), green(c11)) | mean(blue(c00), blue(c10), blue(c01), blue(c11))); } } lod = nextLOD; } while (1 < w && 1 < h); return lods.toArray(new BufferedImage[0]); } public static final int red(final int rgb) { return rgb & 0x00FF0000; } public static final int green(final int rgb) { return rgb & 0x0000FF00; } public static final int blue(final int rgb) { return rgb & 0x000000FF; } public static final int mean(final int... values) { int sum = 0; for (final int value : values) { sum += value; } return 0 < values.length ? sum / values.length : 0; } }
IMJ/test/imj2/tools/MultiresolutionSegmentationTest.java
package imj2.tools; import static net.sourceforge.aprog.swing.SwingTools.show; import static org.junit.Assert.*; import java.awt.Graphics2D; import java.awt.Point; import java.awt.event.MouseWheelEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; import imj2.tools.Image2DComponent.Painter; import imj2.tools.RegionShrinkingTest.AutoMouseAdapter; import imj2.tools.RegionShrinkingTest.SimpleImageView; import org.junit.Test; /** * @author codistmonk (creation 2014-02-07) */ public final class MultiresolutionSegmentationTest { @Test public final void test() { final SimpleImageView imageView = new SimpleImageView(); new AutoMouseAdapter(imageView.getImageHolder()) { private BufferedImage[] pyramid; private int cellSize; private final Painter<SimpleImageView> painter = new Painter<SimpleImageView>() { private final List<Point> particles = new ArrayList<Point>(); @Override public final void paint(final Graphics2D g, final SimpleImageView component, final int width, final int height) { refreshLODs(); final BufferedImage[] pyramid = getPyramid(); final int s = getCellSize(); for (int lod = pyramid.length - 1; 0 <= lod; --lod) { for (final Point particle : this.particles) { particle.x *= 2; particle.y *= 2; } final BufferedImage image = pyramid[lod]; final int w = image.getWidth(); final int h = image.getHeight(); if (s < w && h < s) { for (int y = s; y < h; y += s) { for (int x = s; x < w; x += s) { if (((x / s) & 1) == 0 && ((y / s) & 1) == 0) { this.particles.add(new Point(x, y)); } } } } } } /** * {@value}. */ private static final long serialVersionUID = -8692596860025480748L; }; @Override public final void mouseWheelMoved(final MouseWheelEvent event) { this.refreshLODs(); } public final void refreshLODs() { if (this.getPyramid() == null || this.getPyramid().length == 0 || this.getPyramid()[0] != imageView.getImage()) { this.pyramid = makePyramid(imageView.getImage()); } } public final BufferedImage[] getPyramid() { return this.pyramid; } public final int getCellSize() { return this.cellSize; } @Override protected final void cleanup() { imageView.getPainters().remove(this.painter); } /** * {@value}. */ private static final long serialVersionUID = 3954986726959359787L; }; show(imageView, "Simple Image View", true); } public static final BufferedImage[] makePyramid(final BufferedImage lod0) { final List<BufferedImage> lods = new ArrayList<BufferedImage>(); BufferedImage lod = lod0; int w = lod.getWidth(); int h = lod.getHeight(); do { lods.add(lod); final BufferedImage nextLOD = new BufferedImage(w /= 2, h /= 2, lod.getType()); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { final int c00 = lod.getRGB(2 * x + 0, 2 * y + 0); final int c10 = lod.getRGB(2 * x + 1, 2 * y + 0); final int c01 = lod.getRGB(2 * x + 0, 2 * y + 1); final int c11 = lod.getRGB(2 * x + 1, 2 * y + 1); nextLOD.setRGB(x, y, mean(red(c00), red(c10), red(c01), red(c11)) | mean(green(c00), green(c10), green(c01), green(c11)) | mean(blue(c00), blue(c10), blue(c01), blue(c11))); } } lods.add(nextLOD); } while (1 < w && 1 < h); return lods.toArray(new BufferedImage[0]); } public static final int red(final int rgb) { return rgb & 0x00FF0000; } public static final int green(final int rgb) { return rgb & 0x0000FF00; } public static final int blue(final int rgb) { return rgb & 0x000000FF; } public static final int mean(final int... values) { int sum = 0; for (final int value : values) { sum += value; } return 0 < values.length ? sum / values.length : 0; } }
[IMJ][imj2] Updated MultiresolutionSegmentationTest.
IMJ/test/imj2/tools/MultiresolutionSegmentationTest.java
[IMJ][imj2] Updated MultiresolutionSegmentationTest.
Java
mit
e52d5eed95ba7e526a80f748869687ed53f77742
0
albertoruibal/jmini3d,albertoruibal/jmini3d,albertoruibal/jmini3d
package jmini3d.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Obj2Class { ArrayList<String> vertexList = new ArrayList<String>(); ArrayList<String> normalsList = new ArrayList<String>(); ArrayList<String> uvsList = new ArrayList<String>(); ArrayList<String> facesList = new ArrayList<String>(); StringBuffer vertexSB = new StringBuffer(); StringBuffer normalsSB = new StringBuffer(); StringBuffer uvsSB = new StringBuffer(); StringBuffer facesSB = new StringBuffer(); public static void main(String args[]) { Obj2Class obj2Class = new Obj2Class(); obj2Class.process(args[0], args[1], args[2]); } public void process(String inFile, String outFile, String packageName) { File file = new File(inFile); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { String tokens[] = line.split("\\s|/"); // System.out.println("line = " + line); // System.out.println("token = " + tokens[0]); if ("v".equals(tokens[0])) { vertexList.add(tokens[1] + "f, " + tokens[2] + "f, " + tokens[3] + "f"); } else if ("vn".equals(tokens[0])) { normalsList.add(tokens[1] + "f, " + tokens[2] + "f, " + tokens[3] + "f"); } else if ("vt".equals(tokens[0])) { uvsList.add(tokens[1] + "f, " + (1f - Float.parseFloat(tokens[2])) + "f"); } else if ("f".equals(tokens[0])) { if (facesSB.length() > 0) { facesSB.append(", "); } facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[1]), Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); facesSB.append(", "); facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[4]), Integer.valueOf(tokens[5]), Integer.valueOf(tokens[6]))); facesSB.append(", "); facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[7]), Integer.valueOf(tokens[8]), Integer.valueOf(tokens[9]))); } } br.close(); System.out.println("Vertex size=" + vertexList.size()); System.out.println("Normals size=" + normalsList.size()); System.out.println("Uvs size=" + uvsList.size()); System.out.println("FaceList (vertex+normals+uvs) size=" + facesList.size()); System.out.println(vertexSB.toString()); System.out.println(normalsSB.toString()); System.out.println(uvsSB.toString()); System.out.println(facesSB.toString()); writeFile(packageName, outFile); } catch (Exception e) { e.printStackTrace(); } } public int addVertexNormalUv(int vertexIndex, int uvIndex, int normalIndex) { String key = vertexIndex + "/" + normalIndex + "/" + uvIndex; //String key = vertexList.get(vertexIndex-1) + "/" + normalsList.get(normalIndex-1) + "/" + uvsList.get(uvIndex-1); if (!facesList.contains(key)) { if (vertexSB.length() > 0) { vertexSB.append(", "); normalsSB.append(", "); uvsSB.append(", "); } vertexSB.append(vertexList.get(vertexIndex - 1)); normalsSB.append(normalsList.get(normalIndex - 1)); uvsSB.append(uvsList.get(uvIndex - 1)); facesList.add(key); } return facesList.indexOf(key); } public void writeFile(String packageName, String fileName) { StringBuilder sb = new StringBuilder(); String className = fileName.substring(fileName.lastIndexOf("/") + 1).replace(".java", ""); System.out.println(className); sb.append("package ").append(packageName).append(";\n"); sb.append("import com.mobialia.jmini3d.Geometry3d;"); sb.append("\n"); sb.append("public class ").append(className).append(" extends Geometry3d {\n"); sb.append("\n"); sb.append("public float[] vertex() {\n"); sb.append(" final float vertex[] = {\n"); sb.append(vertexSB); sb.append(" };\n"); sb.append(" return vertex;\n"); sb.append("}\n"); sb.append("public float[] normals() {\n"); sb.append(" final float normals[] = {\n"); sb.append(normalsSB); sb.append(" };\n"); sb.append(" return normals;\n"); sb.append("}\n"); sb.append("public float[] uvs() {\n"); sb.append(" final float uvs[] = {\n"); sb.append(uvsSB); sb.append(" };\n"); sb.append(" return uvs;\n"); sb.append("}\n"); sb.append("public short[] faces() {\n"); sb.append(" final short faces[] = {\n"); sb.append(facesSB); sb.append(" };\n"); sb.append(" return faces;\n"); sb.append("}\n"); sb.append("}\n"); File file = new File(fileName); if (file.exists()) { file.delete(); } try { file.createNewFile(); FileWriter fos = new FileWriter(file); fos.append(sb.toString()); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
utils/src/main/java/jmini3d/utils/Obj2Class.java
package jmini3d.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; public class Obj2Class { ArrayList<String> vertexList = new ArrayList<String>(); ArrayList<String> normalsList = new ArrayList<String>(); ArrayList<String> uvsList = new ArrayList<String>(); ArrayList<String> facesList = new ArrayList<String>(); StringBuffer vertexSB = new StringBuffer(); StringBuffer normalsSB = new StringBuffer(); StringBuffer uvsSB = new StringBuffer(); StringBuffer facesSB = new StringBuffer(); public static void main(String args[]) { Obj2Class obj2Class = new Obj2Class(); obj2Class.process(args[0], args[1], args[2]); } public void process(String inFile, String outFile, String packageName) { File file = new File(inFile); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while ((line = br.readLine()) != null) { String tokens[] = line.split("\\s|/"); // System.out.println("line = " + line); // System.out.println("token = " + tokens[0]); if ("v".equals(tokens[0])) { vertexList.add(tokens[1] + "f, " + tokens[2] + "f, " + tokens[3] + "f"); } else if ("vn".equals(tokens[0])) { normalsList.add(tokens[1] + "f, " + tokens[2] + "f, " + tokens[3] + "f"); } else if ("vt".equals(tokens[0])) { uvsList.add(tokens[1] + "f, " + (1f - Float.parseFloat(tokens[2])) + "f"); } else if ("f".equals(tokens[0])) { if (facesSB.length() > 0) { facesSB.append(", "); } facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[1]), Integer.valueOf(tokens[2]), Integer.valueOf(tokens[3]))); facesSB.append(", "); facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[4]), Integer.valueOf(tokens[5]), Integer.valueOf(tokens[6]))); facesSB.append(", "); facesSB.append(addVertexNormalUv(Integer.valueOf(tokens[7]), Integer.valueOf(tokens[8]), Integer.valueOf(tokens[9]))); } } br.close(); System.out.println("Vertex size=" + vertexList.size()); System.out.println("Normals size=" + normalsList.size()); System.out.println("Uvs size=" + uvsList.size()); System.out.println("FaceList (vertex+normals+uvs) size=" + facesList.size()); System.out.println(vertexSB.toString()); System.out.println(normalsSB.toString()); System.out.println(uvsSB.toString()); System.out.println(facesSB.toString()); writeFile(packageName, outFile); } catch (Exception e) { e.printStackTrace(); } } public int addVertexNormalUv(int vertexIndex, int uvIndex, int normalIndex) { String key = vertexIndex + "/" + normalIndex + "/" + uvIndex; //String key = vertexList.get(vertexIndex-1) + "/" + normalsList.get(normalIndex-1) + "/" + uvsList.get(uvIndex-1); if (!facesList.contains(key)) { if (vertexSB.length() > 0) { vertexSB.append(", "); normalsSB.append(", "); uvsSB.append(", "); } vertexSB.append(vertexList.get(vertexIndex - 1)); normalsSB.append(normalsList.get(normalIndex - 1)); uvsSB.append(uvsList.get(uvIndex - 1)); facesList.add(key); } return facesList.indexOf(key); } public void writeFile(String packageName, String fileName) { StringBuffer sb = new StringBuffer(); String className = fileName.substring(fileName.lastIndexOf("/") + 1).replace(".java", ""); System.out.println(className); sb.append("package ").append(packageName).append(";\n"); sb.append("import com.mobialia.jmini3d.Geometry3d;"); sb.append("\n"); sb.append("public class ").append(className).append(" extends Geometry3d {\n"); sb.append("\n"); sb.append("public float[] vertex() {\n"); sb.append(" final float vertex[] = {\n"); sb.append(vertexSB); sb.append(" };\n"); sb.append(" return vertex;\n"); sb.append("}\n"); sb.append("public float[] normals() {\n"); sb.append(" final float normals[] = {\n"); sb.append(normalsSB); sb.append(" };\n"); sb.append(" return normals;\n"); sb.append("}\n"); sb.append("public float[] uvs() {\n"); sb.append(" final float uvs[] = {\n"); sb.append(uvsSB); sb.append(" };\n"); sb.append(" return uvs;\n"); sb.append("}\n"); sb.append("public short[] faces() {\n"); sb.append(" final short faces[] = {\n"); sb.append(facesSB); sb.append(" };\n"); sb.append(" return faces;\n"); sb.append("}\n"); sb.append("}\n"); File file = new File(fileName); if (file.exists()) { file.delete(); } try { file.createNewFile(); FileWriter fos = new FileWriter(file); fos.append(sb.toString()); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
StringBuffer->StringBuilder
utils/src/main/java/jmini3d/utils/Obj2Class.java
StringBuffer->StringBuilder
Java
agpl-3.0
c59fe28a0e4cd424cb34d8bacd384e1ba015af60
0
ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne
package be.iminds.iot.dianne.tensor.impl.nd4j; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.osgi.service.component.annotations.Component; import be.iminds.iot.dianne.tensor.TensorFactory; import be.iminds.iot.dianne.tensor.TensorMath; @Component(property={"aiolos.export=false"}) public class ND4JTensorFactory implements TensorFactory<ND4JTensor>{ private final ND4JTensorMath math = new ND4JTensorMath(); public ND4JTensorFactory() { Nd4j.factory().setOrder('c'); } @Override public ND4JTensor createTensor(int... d) { INDArray nd = Nd4j.create(d); return new ND4JTensor(nd); } @Override public ND4JTensor createTensor(float[] data, int... d) { INDArray nd = Nd4j.create(data, d); return new ND4JTensor(nd); } @Override public TensorMath<ND4JTensor> getTensorMath() { return math; } }
be.iminds.iot.dianne.tensor/src/be/iminds/iot/dianne/tensor/impl/nd4j/ND4JTensorFactory.java
package be.iminds.iot.dianne.tensor.impl.nd4j; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.osgi.service.component.annotations.Component; import be.iminds.iot.dianne.tensor.TensorFactory; import be.iminds.iot.dianne.tensor.TensorMath; @Component(property={"aiolos.export=false"}) public class ND4JTensorFactory implements TensorFactory<ND4JTensor>{ public ND4JTensorFactory() { Nd4j.factory().setOrder('c'); } @Override public ND4JTensor createTensor(int... d) { INDArray nd = Nd4j.create(d); return new ND4JTensor(nd); } @Override public ND4JTensor createTensor(float[] data, int... d) { INDArray nd = Nd4j.create(data, d); return new ND4JTensor(nd); } @Override public TensorMath<ND4JTensor> getTensorMath() { return new ND4JTensorMath(); } }
keep nd4j tensormath cached in tensorfactory
be.iminds.iot.dianne.tensor/src/be/iminds/iot/dianne/tensor/impl/nd4j/ND4JTensorFactory.java
keep nd4j tensormath cached in tensorfactory
Java
lgpl-2.1
70b2f7f494ccdb15fd4f94ce5454541e3ec97d73
0
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
// // $Id: MultiFrameAnimation.java,v 1.4 2002/09/17 22:18:42 mdb Exp $ package com.threerings.media.animation; import java.awt.Graphics2D; import com.threerings.media.util.FrameSequencer; import com.threerings.media.util.MultiFrameImage; import java.awt.Rectangle; /** * Animates a sequence of image frames in place with a particular frame * rate. */ public class MultiFrameAnimation extends Animation { /** * Creates a multi-frame animation with the specified source image * frames and the specified target frame rate (in frames per second). * * @param frames the source frames of the animation. * @param fps the target number of frames per second. * @param loop whether the animation should loop indefinitely or * finish after one shot. */ public MultiFrameAnimation ( MultiFrameImage frames, double fps, boolean loop) { this(frames, new FrameSequencer.ConstantRate(fps, loop)); } /** * Creates a multi-frame animation with the specified source image * frames and the specified target frame rate (in frames per second). */ public MultiFrameAnimation (MultiFrameImage frames, FrameSequencer seeker) { // we'll set up our bounds via setLocation() and in reset() super(new Rectangle()); _frames = frames; _seeker = seeker; // reset ourselves to start things off reset(); } // documentation inherited public Rectangle getBounds () { // fill in the bounds with our current animation frame's bounds return _bounds; } /** * If this animation has run to completion, it can be reset to prepare * it for another go. */ public void reset () { super.reset(); // set the frame number to -1 so that we don't ignore the // transition to frame zero on the first call to tick() _fidx = -1; // reset our frame sequencer _seeker.init(_frames); } // documentation inherited public void tick (long tickStamp) { int fidx = _seeker.tick(tickStamp); if (fidx == -1) { _finished = true; } else if (fidx != _fidx) { // update our frame index and bounds setFrameIndex(fidx); // and have ourselves repainted invalidate(); } } /** * Sets the frame index and updates our dimensions. */ protected void setFrameIndex (int fidx) { _fidx = fidx; _bounds.width = _frames.getWidth(_fidx); _bounds.height = _frames.getHeight(_fidx); } // documentation inherited public void paint (Graphics2D gfx) { _frames.paintFrame(gfx, _fidx, _bounds.x, _bounds.y); } // documentation inherited public void fastForward (long timeDelta) { _seeker.fastForward(timeDelta); } protected MultiFrameImage _frames; protected FrameSequencer _seeker; protected int _fidx; }
src/java/com/threerings/media/animation/MultiFrameAnimation.java
// // $Id: MultiFrameAnimation.java,v 1.3 2002/09/17 22:06:26 ray Exp $ package com.threerings.media.animation; import java.awt.Graphics2D; import com.threerings.media.util.FrameSequencer; import com.threerings.media.util.MultiFrameImage; import java.awt.Rectangle; /** * Animates a sequence of image frames in place with a particular frame * rate. */ public class MultiFrameAnimation extends Animation { /** * Creates a multi-frame animation with the specified source image * frames and the specified target frame rate (in frames per second). * * @param frames the source frames of the animation. * @param fps the target number of frames per second. * @param loop whether the animation should loop indefinitely or * finish after one shot. */ public MultiFrameAnimation ( MultiFrameImage frames, double fps, boolean loop) { this(frames, new FrameSequencer.ConstantRate(fps, loop)); } /** * Creates a multi-frame animation with the specified source image * frames and the specified target frame rate (in frames per second). */ public MultiFrameAnimation (MultiFrameImage frames, FrameSequencer seeker) { // we'll set up our bounds via setLocation() and in reset() super(new Rectangle()); _frames = frames; _seeker = seeker; // reset ourselves to start things off reset(); } // documentation inherited public Rectangle getBounds () { // fill in the bounds with our current animation frame's bounds return _bounds; } /** * If this animation has run to completion, it can be reset to prepare * it for another go. */ public void reset () { super.reset(); // reset ourselves to a frame number that indicates that we're starting setFrameIndex(-1); // reset our frame sequencer _seeker.init(_frames); } // documentation inherited public void tick (long tickStamp) { int fidx = _seeker.tick(tickStamp); if (fidx == -1) { _finished = true; } else if (fidx != _fidx) { // update our frame index and bounds setFrameIndex(fidx); // and have ourselves repainted invalidate(); } } /** * Sets the frame index and updates our dimensions. */ protected void setFrameIndex (int fidx) { _fidx = fidx; int frame = Math.max(0, _fidx); _bounds.width = _frames.getWidth(frame); _bounds.height = _frames.getHeight(frame); } // documentation inherited public void paint (Graphics2D gfx) { _frames.paintFrame(gfx, Math.max(0, _fidx), _bounds.x, _bounds.y); } // documentation inherited public void fastForward (long timeDelta) { _seeker.fastForward(timeDelta); } protected MultiFrameImage _frames; protected FrameSequencer _seeker; protected int _fidx; }
Slightly less expensive jockeying to ensure that we do the right thing when starting up and being told to switch to frame zero. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@1706 542714f4-19e9-0310-aa3c-eee0fc999fb1
src/java/com/threerings/media/animation/MultiFrameAnimation.java
Slightly less expensive jockeying to ensure that we do the right thing when starting up and being told to switch to frame zero.
Java
lgpl-2.1
9af57bbc1a09850e4b825ffda04cbb901b095e26
0
samskivert/samskivert,samskivert/samskivert
// // $Id: Collections.java,v 1.4 2002/11/07 18:40:40 ray Exp $ package com.samskivert.util; import java.util.*; /** * Provides functionality for the samskivert collections that the * <code>java.util</code> class of the same name provides for the standard * Java collections. Collections-related functionality that is different * from the standard support provided for the Java collections should go * into {@link CollectionUtil}. */ public class Collections { /** * Returns an Iterator that iterates over all the elements contained * within the Collections within the specified Collection. * * @param metaCollection a collection of either other Collections and/or * of Iterators. */ public static Iterator getMetaIterator (Collection metaCollection) { return new MetaIterator(metaCollection); } /** * Get an Iterator over the supplied Collection that returns the * elements in their natural order. */ public static Iterator getSortedIterator (Collection coll) { return getSortedIterator(coll.iterator(), Comparators.COMPARABLE); } /** * Get an Iterator over the supplied Collection that returns the * elements in the order dictated by the supplied Comparator. */ public static Iterator getSortedIterator (Collection coll, Comparator comparator) { return getSortedIterator(coll.iterator(), comparator); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in their natural order. */ public static Iterator getSortedIterator (Iterator itr) { return getSortedIterator(itr, Comparators.COMPARABLE); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in the order dictated by the supplied * Comparator. */ public static Iterator getSortedIterator (Iterator itr, Comparator comparator) { SortableArrayList list = new SortableArrayList(); CollectionUtil.addAll(list, itr); list.sort(comparator); return getUnmodifiableIterator(list); } /** * Get an Iterator over the supplied Collection that returns * the elements in a completely random order. Normally Iterators * return elements in an undefined order, but it is usually the same * between different invocations as long as the underlying Collection * has not changed. This method mixes things up. */ public static Iterator getRandomIterator (Collection c) { return getRandomIterator(c.iterator()); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in a completely random order. */ public static Iterator getRandomIterator (Iterator itr) { ArrayList list = new ArrayList(); CollectionUtil.addAll(list, itr); java.util.Collections.shuffle(list); return getUnmodifiableIterator(list); } /** * Get an Iterator that returns the elements in the supplied * Collection but blocks removal. */ public static Iterator getUnmodifiableIterator (Collection c) { return getUnmodifiableIterator(c.iterator()); } /** * Get an iterator that returns the same elements as the supplied * iterator but blocks removal. */ public static Iterator getUnmodifiableIterator (final Iterator itr) { return new Iterator() { public boolean hasNext () { return itr.hasNext(); } public Object next () { return itr.next(); } public void remove () { throw new UnsupportedOperationException( "Cannot remove from an UnmodifiableIterator!"); } }; } /** * Returns a synchronized (thread-safe) int map backed by the * specified int map. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing int map is * accomplished through the returned int map. * * <p> It is imperative that the user manually synchronize on the * returned int map when iterating over any of its collection views: * * <pre> * IntMap m = Collections.synchronizedIntMap(new HashIntMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * * Failure to follow this advice may result in non-deterministic * behavior. * * <p> The returned map will be serializable if the specified map is * serializable. * * @param m the int map to be "wrapped" in a synchronized int map. * * @return a synchronized view of the specified int map. */ public static IntMap synchronizedIntMap (IntMap m) { return new SynchronizedIntMap(m); } /** * Returns a synchronized (thread-safe) int set backed by the * specified int set. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing int map is * accomplished through the returned int map. * * <p> It is imperative that the user manually synchronize on the * returned int map when iterating over any of its collection views: * * <pre> * IntSet s = Collections.synchronizedIntSet(new ArrayIntSet()); * ... * synchronized(s) { // Synchronizing on s! * Interator i = s.interator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.nextInt()); * } * </pre> * * Failure to follow this advice may result in non-deterministic * behavior. * * <p> The returned set will be serializable if the specified set is * serializable. * * @param s the int set to be "wrapped" in a synchronized int set. * * @return a synchronized view of the specified int set. */ public static IntSet synchronizedIntSet (IntSet s) { return new SychronizedIntSet(s); } /** * Horked from the Java util class and extended for <code>IntMap</code>. */ protected static class SynchronizedIntMap implements IntMap { private IntMap m; // Backing Map private Object mutex; // Object on which to synchronize SynchronizedIntMap(IntMap m) { if (m == null) { throw new NullPointerException(); } this.m = m; mutex = this; } SynchronizedIntMap(IntMap m, Object mutex) { if (m == null) { throw new NullPointerException(); } this.m = m; this.mutex = mutex; } public int size() { synchronized(mutex) {return m.size();} } public boolean isEmpty(){ synchronized(mutex) {return m.isEmpty();} } public boolean containsKey(int key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsKey(Object key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsValue(Object value){ synchronized(mutex) {return m.containsValue(value);} } public Object get(int key) { synchronized(mutex) {return m.get(key);} } public Object get(Object key) { synchronized(mutex) {return m.get(key);} } public Object put(int key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object put(Object key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object remove(int key) { synchronized(mutex) {return m.remove(key);} } public Object remove(Object key) { synchronized(mutex) {return m.remove(key);} } public void putAll(Map map) { synchronized(mutex) {m.putAll(map);} } public void clear() { synchronized(mutex) {m.clear();} } private transient IntSet keySet = null; private transient Set entrySet = null; private transient Collection values = null; public Set keySet() { return intKeySet(); } public IntSet intKeySet () { synchronized(mutex) { if (keySet==null) keySet = new SynchronizedIntSet(m.intKeySet(), mutex); return keySet; } } public Set entrySet() { synchronized(mutex) { if (entrySet==null) entrySet = new SynchronizedSet(m.entrySet(), mutex); return entrySet; } } public Collection values() { synchronized(mutex) { if (values==null) values = new SynchronizedCollection(m.values(), mutex); return values; } } public boolean equals(Object o) { synchronized(mutex) {return m.equals(o);} } public int hashCode() { synchronized(mutex) {return m.hashCode();} } public String toString() { synchronized(mutex) {return m.toString();} } } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedSet extends SynchronizedCollection implements Set { SynchronizedSet(Set s) { super(s); } SynchronizedSet(Set s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { synchronized(mutex) {return c.equals(o);} } public int hashCode() { synchronized(mutex) {return c.hashCode();} } } protected static class SynchronizedIntSet extends SynchronizedSet implements IntSet { SynchronizedIntSet (IntSet s) { super(s); _i = s; } SynchronizedIntSet (IntSet s, Object mutex) { super(s, mutex); _i = s; } public boolean contains (int value) { synchronized(mutex) {return _i.contains(value);} } public boolean add (int value) { synchronized(mutex) {return _i.add(value);} } public boolean remove (int value) { synchronized(mutex) {return _i.remove(value);} } public Interator interator () { // must be manually sync'd by user return _i.interator(); } public int[] toIntArray () { synchronized(mutex) {return _i.toIntArray();} } /** Properly casted reference to our backing set. */ protected IntSet _i; } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedCollection implements Collection { Collection c; // Backing Collection Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection c, Object mutex) { this.c = c; this.mutex = mutex; } public int size() { synchronized(mutex) {return c.size();} } public boolean isEmpty() { synchronized(mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized(mutex) {return c.contains(o);} } public Object[] toArray() { synchronized(mutex) {return c.toArray();} } public Object[] toArray(Object[] a) { synchronized(mutex) {return c.toArray(a);} } public Iterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(Object o) { synchronized(mutex) {return c.add(o);} } public boolean remove(Object o) { synchronized(mutex) {return c.remove(o);} } public boolean containsAll(Collection coll) { synchronized(mutex) {return c.containsAll(coll);} } public boolean addAll(Collection coll) { synchronized(mutex) {return c.addAll(coll);} } public boolean removeAll(Collection coll) { synchronized(mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection coll) { synchronized(mutex) {return c.retainAll(coll);} } public void clear() { synchronized(mutex) {c.clear();} } public String toString() { synchronized(mutex) {return c.toString();} } } /** * An iterator that iterates over the union of the iterators provided by a * collection of collections. */ protected static class MetaIterator implements Iterator { /** * @param collections a Collection containing more Collections * whose elements we are to iterate over. */ public MetaIterator (Collection collections) { _meta = collections.iterator(); } // documentation inherited from interface Iterator public boolean hasNext () { while ((_current == null) || (!_current.hasNext())) { if (_meta.hasNext()) { Object o = _meta.next(); if (o instanceof Iterator) { _current = (Iterator) o; // TODO: jdk1.5, // (obsoletes the Collection case, below) //} else if (o instanceof Iterable) { // _current = ((Iterable) o).iterator(); } else if (o instanceof Collection) { _current = ((Collection) o).iterator(); } else { throw new IllegalArgumentException( "MetaIterator must be constructed with a " + "collection of Iterators or other collections."); } } else { return false; } } return true; } // documentation inherited from interface Iterator public Object next () { if (hasNext()) { return _current.next(); } else { throw new NoSuchElementException(); } } // documentation inherited from interface Iterator public void remove () { if (_current != null) { _current.remove(); } else { throw new IllegalStateException(); } } /** The iterator through the collection we were constructed with. */ protected Iterator _meta; /** The current sub-collection's iterator. */ protected Iterator _current; } }
projects/samskivert/src/java/com/samskivert/util/Collections.java
// // $Id: Collections.java,v 1.4 2002/11/07 18:40:40 ray Exp $ package com.samskivert.util; import java.util.*; /** * Provides functionality for the samskivert collections that the * <code>java.util</code> class of the same name provides for the standard * Java collections. Collections-related functionality that is different * from the standard support provided for the Java collections should go * into {@link CollectionUtil}. */ public class Collections { /** * Returns an Iterator that iterates over all the elements contained * within the Collections within the specified Collection. * * @param metaCollection a collection of either other Collections and/or * of Iterators. */ public static Iterator getMetaIterator (Collection metaCollection) { return new MetaIterator(metaCollection); } /** * Get an Iterator over the supplied Collection that returns the * elements in their natural order. */ public static Iterator getSortedIterator (Collection coll) { return getSortedIterator(coll.iterator(), Comparators.COMPARABLE); } /** * Get an Iterator over the supplied Collection that returns the * elements in the order dictated by the supplied Comparator. */ public static Iterator getSortedIterator (Collection coll, Comparator comparator) { return getSortedIterator(coll.iterator(), comparator); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in their natural order. */ public static Iterator getSortedIterator (Iterator itr) { return getSortedIterator(itr, Comparators.COMPARABLE); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in the order dictated by the supplied * Comparator. */ public static Iterator getSortedIterator (Iterator itr, Comparator comparator) { SortableArrayList list = new SortableArrayList(); CollectionUtil.addAll(list, itr); list.sort(comparator); return getUnmodifiableIterator(list); } /** * Get an Iterator over the supplied Collection that returns * the elements in a completely random order. Normally Iterators * return elements in an undefined order, but it is usually the same * between different invocations as long as the underlying Collection * has not changed. This method mixes things up. */ public static Iterator getRandomIterator (Collection c) { return getRandomIterator(c.iterator()); } /** * Get an Iterator that returns the same elements returned by * the supplied Iterator, but in a completely random order. */ public static Iterator getRandomIterator (Iterator itr) { ArrayList list = new ArrayList(); CollectionUtil.addAll(list, itr); java.util.Collections.shuffle(list); return getUnmodifiableIterator(list); } /** * Get an Iterator that returns the elements in the supplied * Collection but blocks removal. */ public static Iterator getUnmodifiableIterator (Collection c) { return getUnmodifiableIterator(c.iterator()); } /** * Get an iterator that returns the same elements as the supplied * iterator but blocks removal. */ public static Iterator getUnmodifiableIterator (final Iterator itr) { return new Iterator() { public boolean hasNext () { return itr.hasNext(); } public Object next () { return itr.next(); } public void remove () { throw new UnsupportedOperationException( "Cannot remove from an UnmodifiableIterator!"); } }; } /** * Returns a synchronized (thread-safe) int map backed by the * specified int map. In order to guarantee serial access, it is * critical that <strong>all</strong> access to the backing int map is * accomplished through the returned int map. * * <p> It is imperative that the user manually synchronize on the * returned int map when iterating over any of its collection views: * * <pre> * IntMap m = Collections.synchronizedIntMap(new HashIntMap()); * ... * Set s = m.keySet(); // Needn't be in synchronized block * ... * synchronized(m) { // Synchronizing on m, not s! * Iterator i = s.iterator(); // Must be in synchronized block * while (i.hasNext()) * foo(i.next()); * } * </pre> * * Failure to follow this advice may result in non-deterministic * behavior. * * <p> The returned map will be serializable if the specified map is * serializable. * * @param m the int map to be "wrapped" in a synchronized int map. * * @return a synchronized view of the specified int map. */ public static IntMap synchronizedIntMap(IntMap m) { return new SynchronizedIntMap(m); } /** * Horked from the Java util class and extended for <code>IntMap</code>. */ protected static class SynchronizedIntMap implements IntMap { private IntMap m; // Backing Map private Object mutex; // Object on which to synchronize SynchronizedIntMap(IntMap m) { if (m == null) { throw new NullPointerException(); } this.m = m; mutex = this; } SynchronizedIntMap(IntMap m, Object mutex) { if (m == null) { throw new NullPointerException(); } this.m = m; this.mutex = mutex; } public int size() { synchronized(mutex) {return m.size();} } public boolean isEmpty(){ synchronized(mutex) {return m.isEmpty();} } public boolean containsKey(int key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsKey(Object key) { synchronized(mutex) {return m.containsKey(key);} } public boolean containsValue(Object value){ synchronized(mutex) {return m.containsValue(value);} } public Object get(int key) { synchronized(mutex) {return m.get(key);} } public Object get(Object key) { synchronized(mutex) {return m.get(key);} } public Object put(int key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object put(Object key, Object value) { synchronized(mutex) {return m.put(key, value);} } public Object remove(int key) { synchronized(mutex) {return m.remove(key);} } public Object remove(Object key) { synchronized(mutex) {return m.remove(key);} } public void putAll(Map map) { synchronized(mutex) {m.putAll(map);} } public void clear() { synchronized(mutex) {m.clear();} } private transient IntSet keySet = null; private transient Set entrySet = null; private transient Collection values = null; public Set keySet() { return intKeySet(); } public IntSet intKeySet () { synchronized(mutex) { if (keySet==null) keySet = new SynchronizedIntSet(m.intKeySet(), mutex); return keySet; } } public Set entrySet() { synchronized(mutex) { if (entrySet==null) entrySet = new SynchronizedSet(m.entrySet(), mutex); return entrySet; } } public Collection values() { synchronized(mutex) { if (values==null) values = new SynchronizedCollection(m.values(), mutex); return values; } } public boolean equals(Object o) { synchronized(mutex) {return m.equals(o);} } public int hashCode() { synchronized(mutex) {return m.hashCode();} } public String toString() { synchronized(mutex) {return m.toString();} } } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedSet extends SynchronizedCollection implements Set { SynchronizedSet(Set s) { super(s); } SynchronizedSet(Set s, Object mutex) { super(s, mutex); } public boolean equals(Object o) { synchronized(mutex) {return c.equals(o);} } public int hashCode() { synchronized(mutex) {return c.hashCode();} } } protected static class SynchronizedIntSet extends SynchronizedSet implements IntSet { SynchronizedIntSet (IntSet s) { super(s); _i = s; } SynchronizedIntSet (IntSet s, Object mutex) { super(s, mutex); _i = s; } public boolean contains (int value) { synchronized(mutex) {return _i.contains(value);} } public boolean add (int value) { synchronized(mutex) {return _i.add(value);} } public boolean remove (int value) { synchronized(mutex) {return _i.remove(value);} } public Interator interator () { // must be manually sync'd by user return _i.interator(); } public int[] toIntArray () { synchronized(mutex) {return _i.toIntArray();} } /** Pre-casted version of our backing set. */ protected IntSet _i; } /** * I wish I could use this from the <code>java.util.Collections</code> * class, but those crazy kids at Sun are always using private and * default access and pointlessly preventing people from properly * reusing their code. Yay! */ protected static class SynchronizedCollection implements Collection { Collection c; // Backing Collection Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } SynchronizedCollection(Collection c, Object mutex) { this.c = c; this.mutex = mutex; } public int size() { synchronized(mutex) {return c.size();} } public boolean isEmpty() { synchronized(mutex) {return c.isEmpty();} } public boolean contains(Object o) { synchronized(mutex) {return c.contains(o);} } public Object[] toArray() { synchronized(mutex) {return c.toArray();} } public Object[] toArray(Object[] a) { synchronized(mutex) {return c.toArray(a);} } public Iterator iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(Object o) { synchronized(mutex) {return c.add(o);} } public boolean remove(Object o) { synchronized(mutex) {return c.remove(o);} } public boolean containsAll(Collection coll) { synchronized(mutex) {return c.containsAll(coll);} } public boolean addAll(Collection coll) { synchronized(mutex) {return c.addAll(coll);} } public boolean removeAll(Collection coll) { synchronized(mutex) {return c.removeAll(coll);} } public boolean retainAll(Collection coll) { synchronized(mutex) {return c.retainAll(coll);} } public void clear() { synchronized(mutex) {c.clear();} } public String toString() { synchronized(mutex) {return c.toString();} } } /** * An iterator that iterates over the union of the iterators provided by a * collection of collections. */ protected static class MetaIterator implements Iterator { /** * @param collections a Collection containing more Collections * whose elements we are to iterate over. */ public MetaIterator (Collection collections) { _meta = collections.iterator(); } // documentation inherited from interface Iterator public boolean hasNext () { while ((_current == null) || (!_current.hasNext())) { if (_meta.hasNext()) { Object o = _meta.next(); if (o instanceof Iterator) { _current = (Iterator) o; // TODO: jdk1.5, // (obsoletes the Collection case, below) //} else if (o instanceof Iterable) { // _current = ((Iterable) o).iterator(); } else if (o instanceof Collection) { _current = ((Collection) o).iterator(); } else { throw new IllegalArgumentException( "MetaIterator must be constructed with a " + "collection of Iterators or other collections."); } } else { return false; } } return true; } // documentation inherited from interface Iterator public Object next () { if (hasNext()) { return _current.next(); } else { throw new NoSuchElementException(); } } // documentation inherited from interface Iterator public void remove () { if (_current != null) { _current.remove(); } else { throw new IllegalStateException(); } } /** The iterator through the collection we were constructed with. */ protected Iterator _meta; /** The current sub-collection's iterator. */ protected Iterator _current; } }
Added synchronizedIntSet(). git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@1704 6335cc39-0255-0410-8fd6-9bcaacd3b74c
projects/samskivert/src/java/com/samskivert/util/Collections.java
Added synchronizedIntSet().
Java
lgpl-2.1
e784ba0652669b4ca8cd43a8b3dd2fd1314281c4
0
fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui
package to.etc.domui.converter; import java.math.*; import java.text.*; import java.util.*; import to.etc.webapp.nls.*; /** * Utility class to handle all kinds of monetary value presentation and conversion. * This parses a monetary amount entered in a string in a very lax way, to allow * for maximal ease of use in entering currency amounts. It obeys most of the rules * for european (euro) amounts but has a few specials: * <ul> * <li>Any leading currency sign (euro sign) is skipped. Only the euro sign is allowed before the amount!</li> * <li>The dot and comma can both be used as either decimal point and thousands separator. If you use the * one as decimal point then the other, when present, <i>must</i> represent the thousands separator and * it is only allowed at the correct positions in the number.</li> * <li>If a decimal point (comma or dot) is present it can be followed by no digits, one digit like .5 which will be translated * as .50 or two digits. Anything else is an error.</li> * <li>If thousands separators are present they must be fully valid, meaning if one exists all others must exist too, and * all of them <i>must</i> be present at the correct location in the string.</li> * </ul> * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jul 29, 2009 */ public class MoneyUtil { /** * Used for money scaling at two decimal precision. */ public static final int MONEY_SCALE = 2; /** * Parse into a double; return 0.0d for empty input. * @param input * @return */ static public double parseEuroToDouble(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return 0.0d; return Double.parseDouble(ms.getStringResult()); } /** * Parse into a double; return null for empty input. * * @param input * @return */ static public Double parseEuroToDoubleW(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return null; return Double.valueOf(ms.getStringResult()); } /** * Parse into a BigDecimal, return null for empty input. * @param input * @return */ static public BigDecimal parseEuroToBigDecimal(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return null; return new BigDecimal(ms.getStringResult()); } /** * Renders the value as a simple amount with the dot as a decimal point and always followed by * 2 digits after the dot, rounded even (0.005 = +.01). * @param v * @return */ static public String renderAsSimpleDotted(double v) { BigDecimal bd = BigDecimal.valueOf(v); return bd.setScale(MONEY_SCALE, RoundingMode.HALF_EVEN).toString(); } /** * * @param v * @param thousands * @param symbol * @param trunk * @return */ static public String render(double v, boolean thousands, boolean symbol, boolean trunk) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } String s; if(symbol && thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(symbol) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); s = df.format(v); } else { //-- No symbol, no thousands separators; just a # DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); s = df.format(v); } if(trunk) { if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); } return s; } /** * * @param v * @param thousands * @param symbol * @param trunk * @return */ static public String render(BigDecimal v, boolean thousands, boolean symbol, boolean trunk) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } String s; if(symbol && thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(symbol) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); s = df.format(v); } else { //-- No symbol, no thousands separators; just a # DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); s = df.format(v); } if(trunk) { if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); } return s; } /** * Render as a full value: [C -###,###,###.00], including currency sign, thousands separator and all, using the * specified currency locale. It always renders the fraction. * formatters suck. * @param v * @return */ static public String renderFullWithSign(double v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); return s; } /** * Render as a full value: [C -###,###,###.00], including currency sign, thousands separator and all, using the * specified currency locale. It always renders the fraction. * formatters suck. * @param v * @return */ static public String renderFullWithSign(BigDecimal v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } /** * Renders as a full value [C -###,###,###.##], but removes the fraction if it is all zeroes. * @param v * @return */ static public String renderTruncatedWithSign(double v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } /** * Renders as a full value [C -###,###,###.##], but removes the fraction if it is all zeroes. * @param v * @return */ static public String renderTruncatedWithSign(BigDecimal v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } public static void main(String[] args) { Locale l = new Locale("nl", "NL"); NlsContext.setLocale(l); NlsContext.setCurrencyLocale(l); String s = renderFullWithSign(new BigDecimal("123.45")); System.out.println(">> " + s); } }
to.etc.domui/src/to/etc/domui/converter/MoneyUtil.java
package to.etc.domui.converter; import java.math.*; import java.text.*; import java.util.*; import to.etc.webapp.nls.*; /** * Utility class to handle all kinds of monetary value presentation and conversion. * This parses a monetary amount entered in a string in a very lax way, to allow * for maximal ease of use in entering currency amounts. It obeys most of the rules * for european (euro) amounts but has a few specials: * <ul> * <li>Any leading currency sign (euro sign) is skipped. Only the euro sign is allowed before the amount!</li> * <li>The dot and comma can both be used as either decimal point and thousands separator. If you use the * one as decimal point then the other, when present, <i>must</i> represent the thousands separator and * it is only allowed at the correct positions in the number.</li> * <li>If a decimal point (comma or dot) is present it can be followed by no digits, one digit like .5 which will be translated * as .50 or two digits. Anything else is an error.</li> * <li>If thousands separators are present they must be fully valid, meaning if one exists all others must exist too, and * all of them <i>must</i> be present at the correct location in the string.</li> * </ul> * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jul 29, 2009 */ public class MoneyUtil { /** * Parse into a double; return 0.0d for empty input. * @param input * @return */ static public double parseEuroToDouble(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return 0.0d; return Double.parseDouble(ms.getStringResult()); } /** * Parse into a double; return null for empty input. * * @param input * @return */ static public Double parseEuroToDoubleW(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return null; return Double.valueOf(ms.getStringResult()); } /** * Parse into a BigDecimal, return null for empty input. * @param input * @return */ static public BigDecimal parseEuroToBigDecimal(String input) { MiniScanner ms = MiniScanner.getInstance(); if(!ms.scanLaxEuro(input)) // Empty input returned as 0.0d return null; return new BigDecimal(ms.getStringResult()); } /** * Renders the value as a simple amount with the dot as a decimal point and always followed by * 2 digits after the dot, rounded even (0.005 = +.01). * @param v * @return */ static public String renderAsSimpleDotted(double v) { BigDecimal bd = BigDecimal.valueOf(v); return bd.setScale(2, RoundingMode.HALF_EVEN).toString(); } /** * * @param v * @param thousands * @param symbol * @param trunk * @return */ static public String render(double v, boolean thousands, boolean symbol, boolean trunk) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } String s; if(symbol && thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(symbol) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); s = df.format(v); } else { //-- No symbol, no thousands separators; just a # DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); s = df.format(v); } if(trunk) { if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); } return s; } /** * * @param v * @param thousands * @param symbol * @param trunk * @return */ static public String render(BigDecimal v, boolean thousands, boolean symbol, boolean trunk) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } String s; if(symbol && thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(symbol) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); s = sb.toString(); } else if(thousands) { DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); s = df.format(v); } else { //-- No symbol, no thousands separators; just a # DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("##############0.00", dfs); s = df.format(v); } if(trunk) { if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); } return s; } /** * Render as a full value: [C -###,###,###.00], including currency sign, thousands separator and all, using the * specified currency locale. It always renders the fraction. * formatters suck. * @param v * @return */ static public String renderFullWithSign(double v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); return s; } /** * Render as a full value: [C -###,###,###.00], including currency sign, thousands separator and all, using the * specified currency locale. It always renders the fraction. * formatters suck. * @param v * @return */ static public String renderFullWithSign(BigDecimal v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } /** * Renders as a full value [C -###,###,###.##], but removes the fraction if it is all zeroes. * @param v * @return */ static public String renderTruncatedWithSign(double v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } /** * Renders as a full value [C -###,###,###.##], but removes the fraction if it is all zeroes. * @param v * @return */ static public String renderTruncatedWithSign(BigDecimal v) { if(!NlsContext.getCurrency().getCurrencyCode().equalsIgnoreCase("EUR")) { return NumberFormat.getCurrencyInstance(NlsContext.getCurrencyLocale()).format(v); } DecimalFormatSymbols dfs = new DecimalFormatSymbols(NlsContext.getLocale()); // Get numeric format symbols for the locale DecimalFormat df = new DecimalFormat("###,###,###,###,##0.00", dfs); StringBuilder sb = new StringBuilder(20); sb.append(NlsContext.getCurrencySymbol()); sb.append('\u00a0'); sb.append(df.format(v)); String s = sb.toString(); if(s.endsWith(".00") || s.endsWith(",00")) return s.substring(0, s.length() - 3); return s; } public static void main(String[] args) { Locale l = new Locale("nl", "NL"); NlsContext.setLocale(l); NlsContext.setCurrencyLocale(l); String s = renderFullWithSign(new BigDecimal("123.45")); System.out.println(">> " + s); } }
Add MONEY_SCALE constant.
to.etc.domui/src/to/etc/domui/converter/MoneyUtil.java
Add MONEY_SCALE constant.
Java
apache-2.0
8871737f3466bcd7a8f5f66f2049483a2dfe2a0f
0
froop/checkdep
package checkdep.value.depend; import java.util.Collection; import java.util.Iterator; import com.google.common.collect.ImmutableList; public class Dependencies implements Iterable<Dependency> { private final ImmutableList<Dependency> list; public Dependencies(Collection<Dependency> list) { this.list = new ImmutableList.Builder<Dependency>().addAll(list).build(); } @Override public Iterator<Dependency> iterator() { return list.iterator(); } }
src/main/java/checkdep/value/depend/Dependencies.java
package checkdep.value.depend; import java.util.Iterator; import java.util.List; import com.google.common.collect.ImmutableList; public class Dependencies implements Iterable<Dependency> { private final ImmutableList<Dependency> list; public Dependencies(List<Dependency> list) { this.list = new ImmutableList.Builder<Dependency>().addAll(list).build(); } @Override public Iterator<Dependency> iterator() { return list.iterator(); } }
refactoring
src/main/java/checkdep/value/depend/Dependencies.java
refactoring
Java
apache-2.0
c5f6760c6804b5f0dfbec1ddd2953b3c58db58ce
0
purplefox/netty-4.0.2.8-hacked,kiril-me/netty,SinaTadayon/netty,KatsuraKKKK/netty,Scottmitch/netty,fengjiachun/netty,yrcourage/netty,NiteshKant/netty,luyiisme/netty,bryce-anderson/netty,louxiu/netty,golovnin/netty,joansmith/netty,golovnin/netty,louxiu/netty,windie/netty,NiteshKant/netty,doom369/netty,Spikhalskiy/netty,ejona86/netty,imangry/netty-zh,tbrooks8/netty,jchambers/netty,netty/netty,joansmith/netty,mcobrien/netty,bryce-anderson/netty,yipen9/netty,jchambers/netty,golovnin/netty,chanakaudaya/netty,KatsuraKKKK/netty,skyao/netty,zer0se7en/netty,ngocdaothanh/netty,netty/netty,maliqq/netty,yrcourage/netty,imangry/netty-zh,chanakaudaya/netty,fengjiachun/netty,Squarespace/netty,fenik17/netty,doom369/netty,luyiisme/netty,s-gheldd/netty,johnou/netty,luyiisme/netty,blucas/netty,fengjiachun/netty,maliqq/netty,mcobrien/netty,SinaTadayon/netty,zer0se7en/netty,jchambers/netty,idelpivnitskiy/netty,andsel/netty,s-gheldd/netty,joansmith/netty,Spikhalskiy/netty,mikkokar/netty,imangry/netty-zh,skyao/netty,fenik17/netty,johnou/netty,KatsuraKKKK/netty,zer0se7en/netty,DavidAlphaFox/netty,andsel/netty,mikkokar/netty,Squarespace/netty,Squarespace/netty,ejona86/netty,SinaTadayon/netty,cnoldtree/netty,bryce-anderson/netty,DavidAlphaFox/netty,artgon/netty,blucas/netty,mx657649013/netty,netty/netty,joansmith/netty,idelpivnitskiy/netty,joansmith/netty,johnou/netty,Spikhalskiy/netty,SinaTadayon/netty,yrcourage/netty,windie/netty,yipen9/netty,tbrooks8/netty,bryce-anderson/netty,maliqq/netty,carl-mastrangelo/netty,purplefox/netty-4.0.2.8-hacked,kiril-me/netty,purplefox/netty-4.0.2.8-hacked,fenik17/netty,artgon/netty,golovnin/netty,ngocdaothanh/netty,doom369/netty,ejona86/netty,luyiisme/netty,Techcable/netty,ngocdaothanh/netty,fengjiachun/netty,windie/netty,yrcourage/netty,bryce-anderson/netty,Squarespace/netty,louxiu/netty,blucas/netty,kiril-me/netty,Spikhalskiy/netty,ichaki5748/netty,Techcable/netty,s-gheldd/netty,NiteshKant/netty,NiteshKant/netty,ejona86/netty,chanakaudaya/netty,tbrooks8/netty,artgon/netty,Scottmitch/netty,jongyeol/netty,zer0se7en/netty,maliqq/netty,andsel/netty,idelpivnitskiy/netty,mikkokar/netty,mcobrien/netty,Apache9/netty,s-gheldd/netty,imangry/netty-zh,doom369/netty,Scottmitch/netty,netty/netty,chanakaudaya/netty,gerdriesselmann/netty,windie/netty,ngocdaothanh/netty,netty/netty,Apache9/netty,Squarespace/netty,Apache9/netty,mx657649013/netty,DavidAlphaFox/netty,idelpivnitskiy/netty,cnoldtree/netty,imangry/netty-zh,Apache9/netty,gerdriesselmann/netty,mx657649013/netty,KatsuraKKKK/netty,blucas/netty,ichaki5748/netty,mikkokar/netty,NiteshKant/netty,cnoldtree/netty,skyao/netty,skyao/netty,cnoldtree/netty,doom369/netty,andsel/netty,mx657649013/netty,kyle-liu/netty4study,SinaTadayon/netty,andsel/netty,mcobrien/netty,fenik17/netty,jongyeol/netty,carl-mastrangelo/netty,idelpivnitskiy/netty,johnou/netty,kiril-me/netty,artgon/netty,kiril-me/netty,carl-mastrangelo/netty,skyao/netty,ichaki5748/netty,jongyeol/netty,Techcable/netty,zer0se7en/netty,Scottmitch/netty,Techcable/netty,jchambers/netty,yipen9/netty,tbrooks8/netty,jongyeol/netty,louxiu/netty,DavidAlphaFox/netty,mcobrien/netty,louxiu/netty,golovnin/netty,jongyeol/netty,gerdriesselmann/netty,carl-mastrangelo/netty,Scottmitch/netty,purplefox/netty-4.0.2.8-hacked,fengjiachun/netty,gerdriesselmann/netty,artgon/netty,mx657649013/netty,s-gheldd/netty,kyle-liu/netty4study,fenik17/netty,yipen9/netty,ichaki5748/netty,cnoldtree/netty,Apache9/netty,blucas/netty,gerdriesselmann/netty,chanakaudaya/netty,mikkokar/netty,johnou/netty,maliqq/netty,Techcable/netty,ngocdaothanh/netty,jchambers/netty,KatsuraKKKK/netty,tbrooks8/netty,Spikhalskiy/netty,ejona86/netty,ichaki5748/netty,carl-mastrangelo/netty,windie/netty,yrcourage/netty,luyiisme/netty
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.stream; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.nio.channels.ClosedChannelException; import java.util.ArrayDeque; import java.util.Queue; /** * A {@link ChannelHandler} that adds support for writing a large data stream * asynchronously neither spending a lot of memory nor getting * {@link OutOfMemoryError}. Large data streaming such as file * transfer requires complicated state management in a {@link ChannelHandler} * implementation. {@link ChunkedWriteHandler} manages such complicated states * so that you can send a large data stream without difficulties. * <p> * To use {@link ChunkedWriteHandler} in your application, you have to insert * a new {@link ChunkedWriteHandler} instance: * <pre> * {@link ChannelPipeline} p = ...; * p.addLast("streamer", <b>new {@link ChunkedWriteHandler}()</b>); * p.addLast("handler", new MyHandler()); * </pre> * Once inserted, you can write a {@link ChunkedInput} so that the * {@link ChunkedWriteHandler} can pick it up and fetch the content of the * stream chunk by chunk and write the fetched chunk downstream: * <pre> * {@link Channel} ch = ...; * ch.write(new {@link ChunkedFile}(new File("video.mkv")); * </pre> * * <h3>Sending a stream which generates a chunk intermittently</h3> * * Some {@link ChunkedInput} generates a chunk on a certain event or timing. * Such {@link ChunkedInput} implementation often returns {@code null} on * {@link ChunkedInput#readChunk(ChannelHandlerContext)}, resulting in the indefinitely suspended * transfer. To resume the transfer when a new chunk is available, you have to * call {@link #resumeTransfer()}. */ public class ChunkedWriteHandler extends ChannelDuplexHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChunkedWriteHandler.class); private final Queue<PendingWrite> queue = new ArrayDeque<PendingWrite>(); private volatile ChannelHandlerContext ctx; private PendingWrite currentWrite; public ChunkedWriteHandler() { } /** * @deprecated use {@link #ChunkedWriteHandler()} */ @Deprecated public ChunkedWriteHandler(int maxPendingWrites) { if (maxPendingWrites <= 0) { throw new IllegalArgumentException( "maxPendingWrites: " + maxPendingWrites + " (expected: > 0)"); } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } /** * Continues to fetch the chunks from the input. */ public void resumeTransfer() { final ChannelHandlerContext ctx = this.ctx; if (ctx == null) { return; } if (ctx.executor().inEventLoop()) { try { doFlush(ctx); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception while sending chunks.", e); } } } else { // let the transfer resume on the next event loop round ctx.executor().execute(new Runnable() { @Override public void run() { try { doFlush(ctx); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception while sending chunks.", e); } } } }); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { queue.add(new PendingWrite(msg, promise)); } @Override public void flush(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); if (channel.isWritable() || !channel.isActive()) { doFlush(ctx); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { doFlush(ctx); super.channelInactive(ctx); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isWritable()) { // channel is writable again try to continue flushing doFlush(ctx); } ctx.fireChannelWritabilityChanged(); } private void discard(Throwable cause) { for (;;) { PendingWrite currentWrite = this.currentWrite; if (this.currentWrite == null) { currentWrite = queue.poll(); } else { this.currentWrite = null; } if (currentWrite == null) { break; } Object message = currentWrite.msg; if (message instanceof ChunkedInput) { ChunkedInput<?> in = (ChunkedInput<?>) message; try { if (!in.isEndOfInput()) { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } else { currentWrite.success(); } closeInput(in); } catch (Exception e) { currentWrite.fail(e); logger.warn(ChunkedInput.class.getSimpleName() + ".isEndOfInput() failed", e); closeInput(in); } } else { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } } } private void doFlush(final ChannelHandlerContext ctx) throws Exception { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null); return; } boolean needsFlush; while (channel.isWritable()) { if (currentWrite == null) { currentWrite = queue.poll(); } if (currentWrite == null) { break; } needsFlush = true; final PendingWrite currentWrite = this.currentWrite; final Object pendingMessage = currentWrite.msg; if (pendingMessage instanceof ChunkedInput) { final ChunkedInput<?> chunks = (ChunkedInput<?>) pendingMessage; boolean endOfInput; boolean suspend; Object message = null; try { message = chunks.readChunk(ctx); endOfInput = chunks.isEndOfInput(); if (message == null) { // No need to suspend when reached at the end. suspend = !endOfInput; } else { suspend = false; } } catch (final Throwable t) { this.currentWrite = null; if (message != null) { ReferenceCountUtil.release(message); } currentWrite.fail(t); if (ctx.executor().inEventLoop()) { ctx.fireExceptionCaught(t); } else { ctx.executor().execute(new Runnable() { @Override public void run() { ctx.fireExceptionCaught(t); } }); } closeInput(chunks); break; } if (suspend) { // ChunkedInput.nextChunk() returned null and it has // not reached at the end of input. Let's wait until // more chunks arrive. Nothing to write or notify. break; } if (message == null) { // If message is null write an empty ByteBuf. // See https://github.com/netty/netty/issues/1671 message = Unpooled.EMPTY_BUFFER; } final int amount = amount(message); ChannelFuture f = ctx.write(message); if (endOfInput) { this.currentWrite = null; // Register a listener which will close the input once the write is complete. // This is needed because the Chunk may have some resource bound that can not // be closed before its not written. // // See https://github.com/netty/netty/issues/303 f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { currentWrite.progress(amount); currentWrite.success(); closeInput(chunks); } }); } else if (channel.isWritable()) { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { closeInput((ChunkedInput<?>) pendingMessage); currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); } } }); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { closeInput((ChunkedInput<?>) pendingMessage); currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); if (channel.isWritable()) { resumeTransfer(); } } } }); } } else { ctx.write(pendingMessage, currentWrite.promise); this.currentWrite = null; } if (needsFlush) { ctx.flush(); } if (!channel.isActive()) { discard(new ClosedChannelException()); return; } } } static void closeInput(ChunkedInput<?> chunks) { try { chunks.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close a chunked input.", t); } } } private static final class PendingWrite { final Object msg; final ChannelPromise promise; private long progress; PendingWrite(Object msg, ChannelPromise promise) { this.msg = msg; this.promise = promise; } void fail(Throwable cause) { ReferenceCountUtil.release(msg); if (promise != null) { promise.tryFailure(cause); } } void success() { if (promise instanceof ChannelProgressivePromise) { // Now we know what the total is. ((ChannelProgressivePromise) promise).tryProgress(progress, progress); } promise.setSuccess(); } void progress(int amount) { progress += amount; if (promise instanceof ChannelProgressivePromise) { ((ChannelProgressivePromise) promise).tryProgress(progress, -1); } } } private static int amount(Object msg) { if (msg instanceof ByteBuf) { return ((ByteBuf) msg).readableBytes(); } if (msg instanceof ByteBufHolder) { return ((ByteBufHolder) msg).content().readableBytes(); } return 1; } }
handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java
/* * Copyright 2012 The Netty Project * * The Netty Project licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.handler.stream; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelProgressivePromise; import io.netty.channel.ChannelPromise; import io.netty.util.ReferenceCountUtil; import io.netty.util.internal.logging.InternalLogger; import io.netty.util.internal.logging.InternalLoggerFactory; import java.nio.channels.ClosedChannelException; import java.util.ArrayDeque; import java.util.Queue; /** * A {@link ChannelHandler} that adds support for writing a large data stream * asynchronously neither spending a lot of memory nor getting * {@link OutOfMemoryError}. Large data streaming such as file * transfer requires complicated state management in a {@link ChannelHandler} * implementation. {@link ChunkedWriteHandler} manages such complicated states * so that you can send a large data stream without difficulties. * <p> * To use {@link ChunkedWriteHandler} in your application, you have to insert * a new {@link ChunkedWriteHandler} instance: * <pre> * {@link ChannelPipeline} p = ...; * p.addLast("streamer", <b>new {@link ChunkedWriteHandler}()</b>); * p.addLast("handler", new MyHandler()); * </pre> * Once inserted, you can write a {@link ChunkedInput} so that the * {@link ChunkedWriteHandler} can pick it up and fetch the content of the * stream chunk by chunk and write the fetched chunk downstream: * <pre> * {@link Channel} ch = ...; * ch.write(new {@link ChunkedFile}(new File("video.mkv")); * </pre> * * <h3>Sending a stream which generates a chunk intermittently</h3> * * Some {@link ChunkedInput} generates a chunk on a certain event or timing. * Such {@link ChunkedInput} implementation often returns {@code null} on * {@link ChunkedInput#readChunk(ChannelHandlerContext)}, resulting in the indefinitely suspended * transfer. To resume the transfer when a new chunk is available, you have to * call {@link #resumeTransfer()}. */ public class ChunkedWriteHandler extends ChannelDuplexHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChunkedWriteHandler.class); private final Queue<PendingWrite> queue = new ArrayDeque<PendingWrite>(); private volatile ChannelHandlerContext ctx; private PendingWrite currentWrite; public ChunkedWriteHandler() { } /** * @deprecated use {@link #ChunkedWriteHandler()} */ @Deprecated public ChunkedWriteHandler(int maxPendingWrites) { if (maxPendingWrites <= 0) { throw new IllegalArgumentException( "maxPendingWrites: " + maxPendingWrites + " (expected: > 0)"); } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; } /** * Continues to fetch the chunks from the input. */ public void resumeTransfer() { final ChannelHandlerContext ctx = this.ctx; if (ctx == null) { return; } if (ctx.executor().inEventLoop()) { try { doFlush(ctx); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception while sending chunks.", e); } } } else { // let the transfer resume on the next event loop round ctx.executor().execute(new Runnable() { @Override public void run() { try { doFlush(ctx); } catch (Exception e) { if (logger.isWarnEnabled()) { logger.warn("Unexpected exception while sending chunks.", e); } } } }); } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { queue.add(new PendingWrite(msg, promise)); } @Override public void flush(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.channel(); if (channel.isWritable() || !channel.isActive()) { doFlush(ctx); } } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { doFlush(ctx); super.channelInactive(ctx); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if (ctx.channel().isWritable()) { // channel is writable again try to continue flushing doFlush(ctx); } ctx.fireChannelWritabilityChanged(); } private void discard(Throwable cause) { for (;;) { PendingWrite currentWrite = this.currentWrite; if (this.currentWrite == null) { currentWrite = queue.poll(); } else { this.currentWrite = null; } if (currentWrite == null) { break; } Object message = currentWrite.msg; if (message instanceof ChunkedInput) { ChunkedInput<?> in = (ChunkedInput<?>) message; try { if (!in.isEndOfInput()) { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } else { currentWrite.success(); } closeInput(in); } catch (Exception e) { currentWrite.fail(e); logger.warn(ChunkedInput.class.getSimpleName() + ".isEndOfInput() failed", e); closeInput(in); } } else { if (cause == null) { cause = new ClosedChannelException(); } currentWrite.fail(cause); } } } private void doFlush(final ChannelHandlerContext ctx) throws Exception { final Channel channel = ctx.channel(); if (!channel.isActive()) { discard(null); return; } boolean needsFlush; while (channel.isWritable()) { if (currentWrite == null) { currentWrite = queue.poll(); } if (currentWrite == null) { break; } needsFlush = true; final PendingWrite currentWrite = this.currentWrite; final Object pendingMessage = currentWrite.msg; if (pendingMessage instanceof ChunkedInput) { final ChunkedInput<?> chunks = (ChunkedInput<?>) pendingMessage; boolean endOfInput; boolean suspend; Object message = null; try { message = chunks.readChunk(ctx); endOfInput = chunks.isEndOfInput(); if (message == null) { // No need to suspend when reached at the end. suspend = !endOfInput; } else { suspend = false; } } catch (final Throwable t) { this.currentWrite = null; if (message != null) { ReferenceCountUtil.release(message); } currentWrite.fail(t); if (ctx.executor().inEventLoop()) { ctx.fireExceptionCaught(t); } else { ctx.executor().execute(new Runnable() { @Override public void run() { ctx.fireExceptionCaught(t); } }); } closeInput(chunks); break; } if (suspend) { // ChunkedInput.nextChunk() returned null and it has // not reached at the end of input. Let's wait until // more chunks arrive. Nothing to write or notify. break; } if (message == null) { // If message is null write an empty ByteBuf. // See https://github.com/netty/netty/issues/1671 message = Unpooled.EMPTY_BUFFER; } final int amount = amount(message); ChannelFuture f = ctx.write(message); if (endOfInput) { this.currentWrite = null; // Register a listener which will close the input once the write is complete. // This is needed because the Chunk may have some resource bound that can not // be closed before its not written. // // See https://github.com/netty/netty/issues/303 f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { currentWrite.progress(amount); currentWrite.success(); closeInput(chunks); } }); } else if (channel.isWritable()) { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { closeInput((ChunkedInput<?>) pendingMessage); currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); } } }); } else { f.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { closeInput((ChunkedInput<?>) pendingMessage); currentWrite.fail(future.cause()); } else { currentWrite.progress(amount); if (channel.isWritable()) { resumeTransfer(); } } } }); } } else { ctx.write(pendingMessage, currentWrite.promise); this.currentWrite = null; } if (needsFlush) { ctx.flush(); } if (!channel.isActive()) { discard(new ClosedChannelException()); return; } } } static void closeInput(ChunkedInput<?> chunks) { try { chunks.close(); } catch (Throwable t) { if (logger.isWarnEnabled()) { logger.warn("Failed to close a chunked input.", t); } } } private static final class PendingWrite { final Object msg; final ChannelPromise promise; private long progress; PendingWrite(Object msg, ChannelPromise promise) { this.msg = msg; this.promise = promise; } void fail(Throwable cause) { ReferenceCountUtil.release(msg); if (promise != null) { promise.setFailure(cause); } } void success() { if (promise instanceof ChannelProgressivePromise) { // Now we know what the total is. ((ChannelProgressivePromise) promise).tryProgress(progress, progress); } promise.setSuccess(); } void progress(int amount) { progress += amount; if (promise instanceof ChannelProgressivePromise) { ((ChannelProgressivePromise) promise).tryProgress(progress, -1); } } } private static int amount(Object msg) { if (msg instanceof ByteBuf) { return ((ByteBuf) msg).readableBytes(); } if (msg instanceof ByteBufHolder) { return ((ByteBufHolder) msg).content().readableBytes(); } return 1; } }
[#1895] Fix IllegalStateException which was produced during failing ChunkedWrite after the channel was closed
handler/src/main/java/io/netty/handler/stream/ChunkedWriteHandler.java
[#1895] Fix IllegalStateException which was produced during failing ChunkedWrite after the channel was closed
Java
apache-2.0
0012076bf0d861c07d713b915797c526c6dc21d6
0
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
package no.priv.bang.ukelonn.tests; import static org.junit.Assert.*; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.*; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.inject.Inject; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.web.itest.base.client.HttpTestClient; import org.ops4j.pax.web.itest.base.client.HttpTestClientFactory; import no.priv.bang.ukelonn.UkelonnService; import no.priv.bang.ukelonn.UkelonnDatabase; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class UkelonnServiceIntegrationTest extends UkelonnServiceIntegrationTestBase { public static final String RMI_SERVER_PORT = "44445"; public static final String RMI_REG_PORT = "1100"; @Inject private UkelonnService ukelonnService; @Inject private UkelonnDatabase database; @Configuration public Option[] config() { final String jmxPort = freePortAsString(); final String httpPort = freePortAsString(); final String httpsPort = freePortAsString(); final MavenArtifactUrlReference karafUrl = maven().groupId("org.apache.karaf").artifactId("apache-karaf-minimal").type("zip").versionAsInProject(); final MavenArtifactUrlReference paxJdbcRepo = maven().groupId("org.ops4j.pax.jdbc").artifactId("pax-jdbc-features").versionAsInProject().type("xml").classifier("features"); final MavenArtifactUrlReference ukelonnFeatureRepo = maven().groupId("no.priv.bang.ukelonn").artifactId("ukelonn.karaf").versionAsInProject().type("xml").classifier("features"); return options( karafDistributionConfiguration().frameworkUrl(karafUrl).unpackDirectory(new File("target/exam")).useDeployFolder(false).runEmbedded(true), configureConsole().ignoreLocalConsole().ignoreRemoteShell(), systemTimeout(720000), logLevel(LogLevel.DEBUG), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiRegistryPort", RMI_REG_PORT), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiServerPort", RMI_SERVER_PORT), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port", httpPort), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port.secure", httpsPort), vmOptions("-Dtest-jmx-port=" + jmxPort), junitBundles(), mavenBundle("org.apache.shiro", "shiro-core").versionAsInProject(), features(paxJdbcRepo), features(ukelonnFeatureRepo, "ukelonn-db-derby-test", "ukelonn")); } @Test public void ukelonnServiceIntegrationTest() { // Verify that the service could be injected assertNotNull(ukelonnService); assertEquals("Hello world!", ukelonnService.getMessage()); } @Test public void testDerbyTestDatabase() throws SQLException { PreparedStatement statement = database.prepareStatement("select * from accounts_view where username=?"); statement.setString(1, "jad"); ResultSet onAccount = database.query(statement); assertNotNull(onAccount); assertTrue(onAccount.next()); // Verify that there is at least one result int account_id = onAccount.getInt("account_id"); int user_id = onAccount.getInt("user_id"); String username = onAccount.getString("username"); String first_name = onAccount.getString("first_name"); String last_name = onAccount.getString("last_name"); assertEquals(4, account_id); assertEquals(4, user_id); assertEquals("jad", username); assertEquals("Jane", first_name); assertEquals("Doe", last_name); } @Ignore @Test public void webappAccessTest() throws Exception { Thread.sleep(20*1000); HttpTestClient testclient = HttpTestClientFactory.createDefaultTestClient(); try { testclient.doGET("http://localhost:8081/ukelonn/").withReturnCode(404); String response = testclient.executeTest(); assertEquals("", response); } finally { testclient = null; } } }
ukelonn.tests/src/test/java/no/priv/bang/ukelonn/tests/UkelonnServiceIntegrationTest.java
package no.priv.bang.ukelonn.tests; import static org.junit.Assert.*; import static org.ops4j.pax.exam.CoreOptions.*; import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.*; import java.io.File; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import no.priv.bang.ukelonn.UkelonnService; import no.priv.bang.ukelonn.UkelonnDatabase; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class UkelonnServiceIntegrationTest extends UkelonnServiceIntegrationTestBase { public static final String RMI_SERVER_PORT = "44445"; public static final String RMI_REG_PORT = "1100"; @Inject private UkelonnService ukelonnService; @Inject private UkelonnDatabase database; @Configuration public Option[] config() { final String jmxPort = freePortAsString(); final String httpPort = freePortAsString(); final String httpsPort = freePortAsString(); final MavenArtifactUrlReference karafUrl = maven().groupId("org.apache.karaf").artifactId("apache-karaf-minimal").type("zip").versionAsInProject(); final MavenArtifactUrlReference paxJdbcRepo = maven().groupId("org.ops4j.pax.jdbc").artifactId("pax-jdbc-features").versionAsInProject().type("xml").classifier("features"); final MavenArtifactUrlReference ukelonnFeatureRepo = maven().groupId("no.priv.bang.ukelonn").artifactId("ukelonn.karaf").versionAsInProject().type("xml").classifier("features"); return options( karafDistributionConfiguration().frameworkUrl(karafUrl).unpackDirectory(new File("target/exam")).useDeployFolder(false).runEmbedded(true), configureConsole().ignoreLocalConsole().ignoreRemoteShell(), systemTimeout(720000), logLevel(LogLevel.DEBUG), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiRegistryPort", RMI_REG_PORT), editConfigurationFilePut("etc/org.apache.karaf.management.cfg", "rmiServerPort", RMI_SERVER_PORT), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port", httpPort), editConfigurationFilePut("etc/org.ops4j.pax.web.cfg", "org.osgi.service.http.port.secure", httpsPort), vmOptions("-Dtest-jmx-port=" + jmxPort), junitBundles(), mavenBundle("org.apache.shiro", "shiro-core").versionAsInProject(), features(paxJdbcRepo), features(ukelonnFeatureRepo, "ukelonn-db-derby-test", "ukelonn")); } @Test public void ukelonnServiceIntegrationTest() { // Verify that the service could be injected assertNotNull(ukelonnService); assertEquals("Hello world!", ukelonnService.getMessage()); } @Test public void testDerbyTestDatabase() throws SQLException { PreparedStatement statement = database.prepareStatement("select * from accounts_view where username=?"); statement.setString(1, "jad"); ResultSet onAccount = database.query(statement); assertNotNull(onAccount); assertTrue(onAccount.next()); // Verify that there is at least one result int account_id = onAccount.getInt("account_id"); int user_id = onAccount.getInt("user_id"); String username = onAccount.getString("username"); String first_name = onAccount.getString("first_name"); String last_name = onAccount.getString("last_name"); assertEquals(4, account_id); assertEquals(4, user_id); assertEquals("jad", username); assertEquals("Jane", first_name); assertEquals("Doe", last_name); } @Ignore @Test public void webappAccessTest() throws Exception { Thread.sleep(20*1000); HttpTestClient testclient = HttpTestClientFactory.createDefaultTestClient(); try { testclient.doGET("http://localhost:8081/ukelonn/").withReturnCode(404); String response = testclient.executeTest(); assertEquals("", response); } finally { testclient = null; } } }
Add missing imports to the ukelonn integration tests.
ukelonn.tests/src/test/java/no/priv/bang/ukelonn/tests/UkelonnServiceIntegrationTest.java
Add missing imports to the ukelonn integration tests.
Java
apache-2.0
b04a003b063d21f963798c9449859a743c980bed
0
oboehm/gdv.xport,oboehm/gdv.xport,oboehm/gdv.xport
/* * $Id$ * * Copyright (c) 2009 by Oliver Boehm * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 04.10.2009 by oliver ([email protected]) */ package gdv.xport.feld; import gdv.xport.annotation.FeldInfo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import net.sf.oval.ConstraintViolation; import net.sf.oval.constraint.MatchPatternCheck; import net.sf.oval.context.ClassContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The Class Datum. * * @author oliver * @since 04.10.2009 * @version $Revision$ */ public final class Datum extends Feld { private static final Log log = LogFactory.getLog(Feld.class); private final DateFormat dateFormat; /** * Legt ein neues Datums-Feld an. Die Informationen dazu werden * aus der uebergebenen Enum bezogen. * * @param feldX Enum mit den Feldinformationen * @since 0.9 */ public Datum(final Enum<?> feldX) { this(feldX, Feld.getFeldInfo(feldX)); } /** * Instantiiert ein neues Datum. * * @param feldX Feld * @param info mit Angabe der Start-Adresse * @since 0.6 */ public Datum(final Enum<?> feldX, final FeldInfo info) { super(feldX, info); this.dateFormat = getDateFormat(info.anzahlBytes()); } /** * Instantiates a new datum. * * @param name the name * @param start the start */ public Datum(final String name, final int start) { this(name, 8, start); } /** * Instantiates a new datum. * * @param name the name * @param inhalt Datum der Form "ddmmjjjj" oder "ddjjjj" oder "dd" */ public Datum(final String name, final String inhalt) { this(name, inhalt.length(), 1, inhalt); } /** * Instantiates a new datum. * * @param name the name * @param length the length * @param start the start */ public Datum(final String name, final int length, final int start) { super(name, length, start, Align.RIGHT); dateFormat = getDateFormat(length); } /** * Instantiiert ein neues Datum. * * @param name Bezeichner * @param info mit der Start-Adresse und weiteren Angaben * @since 0.6 */ public Datum(final String name, final FeldInfo info) { super(name, info.anzahlBytes(), info.byteAdresse(), info.align() == Align.UNKNOWN ? Align.RIGHT : info.align()); dateFormat = getDateFormat(info.anzahlBytes()); } /** * Instantiates a new datum. * * @param name the name * @param length the length * @param start the start * @param inhalt Datum der Form "ddmmjjjj" oder "ddjjjj" oder "dd" */ public Datum(final String name, final int length, final int start, final String inhalt) { this(name, length, start); this.setInhalt(inhalt); } /** * Instantiates a new datum. */ public Datum() { this(1); } /** * Instantiates a new datum. * * @param start the start */ public Datum(final int start) { this(8, start); } /** * Instantiates a new datum. * * @param length the length * @param start the start */ public Datum(final int length, final int start) { super(length, start, Align.RIGHT); dateFormat = getDateFormat(length); } private static DateFormat getDateFormat(final int length) { return getDateFormat(length, ""); } private static DateFormat getDateFormat(final int length, final String separator) { switch (length) { case 2: return new SimpleDateFormat("dd"); case 4: return new SimpleDateFormat("MM" + separator + "yy"); case 6: return new SimpleDateFormat("MM" + separator + "yyyy"); case 8: return new SimpleDateFormat("dd" + separator + "MM" + separator + "yyyy"); default: throw new IllegalArgumentException("length=" + length + " not allowed - only 2, 4, 6 or 8"); } } /** * Sets the inhalt. * * @param d the new inhalt */ public void setInhalt(final Datum d) { this.setInhalt(d.getInhalt()); } /** * Sets the inhalt. * * @param d the new inhalt */ public void setInhalt(final Date d) { this.setInhalt(dateFormat.format(d)); } /** * To date. * * @return the date */ public Date toDate() { try { return dateFormat.parse(this.getInhalt()); } catch (ParseException e) { throw new IllegalStateException(this + " has an invalid date (\"" + this.getInhalt() + "\")"); } } /** * Heute. * * @return the datum */ public static Datum heute() { Datum d = new Datum(); d.setInhalt(new Date()); return d; } /* (non-Javadoc) * @see gdv.xport.feld.Feld#isEmpty() */ @Override public boolean isEmpty() { if (super.isEmpty()) { return true; } try { int n = Integer.parseInt(this.getInhalt()); return n == 0; } catch (NumberFormatException e) { return false; } } /** * Aus Performance-Gruenden verwenden wir hier nicht die * validate()-Methode. * * @return true/false * * @see gdv.xport.feld.Feld#isValid() */ @Override public boolean isValid() { if (this.isEmpty()) { return true; } if (!super.isValid()) { return false; } return this.hasValidDate(); } /* (non-Javadoc) * @see gdv.xport.feld.Feld#isInvalid() */ @Override public boolean isInvalid() { return !this.isValid(); } private boolean hasValidDate() { String orig = this.getInhalt(); if (orig.startsWith("00")) { return true; } try { Date date = this.toDate(); String conv = this.dateFormat.format(date); return conv.equals(orig); } catch (RuntimeException e) { log.info(e + " -> mapped to false"); return false; } } /* (non-Javadoc) * @see gdv.xport.feld.Feld#validate() */ @Override public List<ConstraintViolation> validate() { List<ConstraintViolation> violations = super.validate(); if (!this.isEmpty() && !this.hasValidDate()) { ConstraintViolation cv = new ConstraintViolation(new MatchPatternCheck(), "'" + this.getInhalt() + "' is not a valid date", this, this.getInhalt(), new ClassContext(this.getClass())); violations.add(cv); } return violations; } /* (non-Javadoc) * @see gdv.xport.feld.Feld#format() */ @Override public String format() { DateFormat df = getDateFormat(this.getAnzahlBytes(), "."); return df.format(this.toDate()); } }
src/main/java/gdv/xport/feld/Datum.java
/* * $Id$ * * Copyright (c) 2009 by Oliver Boehm * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 04.10.2009 by oliver ([email protected]) */ package gdv.xport.feld; import gdv.xport.annotation.FeldInfo; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import net.sf.oval.ConstraintViolation; import net.sf.oval.constraint.MatchPatternCheck; import net.sf.oval.context.ClassContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * The Class Datum. * * @author oliver * @since 04.10.2009 * @version $Revision$ */ public final class Datum extends Feld { private static final Log log = LogFactory.getLog(Feld.class); private final DateFormat dateFormat; /** * Legt ein neues Datums-Feld an. Die Informationen dazu werden * aus der uebergebenen Enum bezogen. * * @param feldX Enum mit den Feldinformationen * @since 0.9 */ public Datum(final Enum<?> feldX) { this(feldX, Feld.getFeldInfo(feldX)); } /** * Instantiiert ein neues Datum. * * @param feldX Feld * @param info mit Angabe der Start-Adresse * @since 0.6 */ public Datum(final Enum<?> feldX, final FeldInfo info) { super(feldX, info); this.dateFormat = getDateFormat(info.anzahlBytes()); } /** * Instantiates a new datum. * * @param name the name * @param start the start */ public Datum(final String name, final int start) { this(name, 8, start); } /** * Instantiates a new datum. * * @param name the name * @param inhalt Datum der Form "ddmmjjjj" oder "ddjjjj" oder "dd" */ public Datum(final String name, final String inhalt) { this(name, inhalt.length(), 1, inhalt); } /** * Instantiates a new datum. * * @param name the name * @param length the length * @param start the start */ public Datum(final String name, final int length, final int start) { super(name, length, start, Align.RIGHT); dateFormat = getDateFormat(length); } /** * Instantiiert ein neues Datum. * * @param name Bezeichner * @param info mit der Start-Adresse und weiteren Angaben * @since 0.6 */ public Datum(final String name, final FeldInfo info) { super(name, info.anzahlBytes(), info.byteAdresse(), info.align() == Align.UNKNOWN ? Align.RIGHT : info.align()); dateFormat = getDateFormat(info.anzahlBytes()); } /** * Instantiates a new datum. * * @param name the name * @param length the length * @param start the start * @param inhalt Datum der Form "ddmmjjjj" oder "ddjjjj" oder "dd" */ public Datum(final String name, final int length, final int start, final String inhalt) { this(name, length, start); this.setInhalt(inhalt); } /** * Instantiates a new datum. */ public Datum() { this(1); } /** * Instantiates a new datum. * * @param start the start */ public Datum(final int start) { this(8, start); } /** * Instantiates a new datum. * * @param length the length * @param start the start */ public Datum(final int length, final int start) { super(length, start, Align.RIGHT); dateFormat = getDateFormat(length); } private static DateFormat getDateFormat(final int length) { return getDateFormat(length, ""); } private static DateFormat getDateFormat(final int length, final String separator) { switch (length) { case 2: return new SimpleDateFormat("dd"); case 4: return new SimpleDateFormat("MM" + separator + "yy"); case 6: return new SimpleDateFormat("MM" + separator + "yyyy"); case 8: return new SimpleDateFormat("dd" + separator + "MM" + separator + "yyyy"); default: throw new IllegalArgumentException("length=" + length + " not allowed - only 2, 4, 6 or 8"); } } /** * Sets the inhalt. * * @param d the new inhalt */ public void setInhalt(final Datum d) { this.setInhalt(d.getInhalt()); } /** * Sets the inhalt. * * @param d the new inhalt */ public void setInhalt(final Date d) { this.setInhalt(dateFormat.format(d)); } /** * To date. * * @return the date */ public Date toDate() { try { return dateFormat.parse(this.getInhalt()); } catch (ParseException e) { throw new IllegalStateException(this + " has an invalid date (\"" + this.getInhalt() + "\")"); } } /** * Heute. * * @return the datum */ public static Datum heute() { Datum d = new Datum(); d.setInhalt(new Date()); return d; } /* (non-Javadoc) * @see gdv.xport.feld.Feld#isEmpty() */ @Override public boolean isEmpty() { if (super.isEmpty()) { return true; } try { int n = Integer.parseInt(this.getInhalt()); return n == 0; } catch (NumberFormatException e) { return false; } } /** * Aus Performance-Gruenden verwenden wir hier nicht die * validate()-Methode. * * @return true/false * * @see gdv.xport.feld.Feld#isValid() */ @Override public boolean isValid() { if (this.isEmpty()) { return true; } if (!super.isValid()) { return false; } return this.hasValidDate(); } /* (non-Javadoc) * @see gdv.xport.feld.Feld#isInvalid() */ @Override public boolean isInvalid() { return !this.isValid(); } private boolean hasValidDate() { String orig = this.getInhalt(); if (orig.startsWith("00")) { return true; } try { Date date = this.toDate(); String conv = this.dateFormat.format(date); return conv.equals(orig); } catch (RuntimeException e) { log.info(e + " -> mapped to false"); return false; } } /* (non-Javadoc) * @see gdv.xport.feld.Feld#validate() */ @Override public List<ConstraintViolation> validate() { List<ConstraintViolation> violations = super.validate(); if (this.isEmpty()) { return violations; } try { if (!this.hasValidDate()) { throw new RuntimeException(this.getInhalt() + " is not a valid date"); } } catch (RuntimeException e) { ConstraintViolation cv = new ConstraintViolation(new MatchPatternCheck(), e .getLocalizedMessage(), this, this.getInhalt(), new ClassContext(this .getClass())); violations.add(cv); } return violations; } /* (non-Javadoc) * @see gdv.xport.feld.Feld#format() */ @Override public String format() { DateFormat df = getDateFormat(this.getAnzahlBytes(), "."); return df.format(this.toDate()); } }
validate()-Methode vereinfacht
src/main/java/gdv/xport/feld/Datum.java
validate()-Methode vereinfacht
Java
apache-2.0
ca4b1daa0952d9537da61d7a03da59699bbb5f43
0
FITeagle/api
package org.fiteagle.api.core; public interface MessageFilters { String FILTER_ORCHESTRATOR = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_ORCHESTRATOR + "' " + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"') " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_INFORM+"'"; String FILTER_RESERVATION = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_RESERVATION + "' " + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR " +IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"')"; String FILTER_RESOURCE_ADAPTER_MANAGER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_RESOURCE_ADAPTER_MANAGER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; String FILTER_FEDERATION_MANAGER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_FEDERATION_MANAGER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; String FILTER_ADAPTER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_ADAPTER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; }
src/main/java/org/fiteagle/api/core/MessageFilters.java
package org.fiteagle.api.core; public interface MessageFilters { String FILTER_ORCHESTRATOR = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_ORCHESTRATOR + "' " + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; String FILTER_RESERVATION = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_RESERVATION + "' " + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR " +IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"')"; String FILTER_RESOURCE_ADAPTER_MANAGER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_RESOURCE_ADAPTER_MANAGER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; String FILTER_FEDERATION_MANAGER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_FEDERATION_MANAGER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; String FILTER_ADAPTER = IMessageBus.METHOD_TARGET + " = '" + IMessageBus.TARGET_ADAPTER + "'" + "AND ("+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CREATE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_CONFIGURE+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_GET+"' " + "OR "+IMessageBus.METHOD_TYPE+" = '"+IMessageBus.TYPE_DELETE+"')"; }
modfied orchestrator filter
src/main/java/org/fiteagle/api/core/MessageFilters.java
modfied orchestrator filter
Java
apache-2.0
872a68c7dc01385bd147975fcc513b0fa0df19e8
0
redlink-gmbh/redlink-java-sdk
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.redlink.sdk; import com.google.code.tempusfugit.concurrency.ConcurrentRule; import com.google.code.tempusfugit.concurrency.RepeatingRule; import com.google.code.tempusfugit.concurrency.annotations.Concurrent; import com.google.code.tempusfugit.concurrency.annotations.Repeating; import org.apache.commons.lang3.RandomStringUtils; import org.junit.*; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.openrdf.model.*; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.TreeModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.rio.RDFHandlerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.MalformedURLException; import java.util.Random; /** * Add file description here! * * @author Sebastian Schaffert ([email protected]) */ public class DataConcurrencyTest extends GenericTest { private static Logger log = LoggerFactory.getLogger(DataConcurrencyTest.class); private static final String TEST_DATASET = "test"; private RedLink.Data redlink; protected static Random rnd; @Rule public ConcurrentRule crule = new ConcurrentRule(); @Rule public RepeatingRule rrule = new RepeatingRule(); @Rule public TestWatcher watchman = new TestWatcher() { /** * Invoked when a test is about to start */ @Override protected void starting(Description description) { log.info("{} being run...", description.getMethodName()); } /** * Invoked when a test method finishes (whether passing or failing) */ @Override protected void finished(Description description) { log.info("{}: {} added triples, {} removed triples, {} resources reused, {} objects reused", new Object[] { description.getMethodName(), tripleAddCount, tripleRemoveCount, resourcesReused, objectsReused}); } }; long tripleAddCount = 0; long tripleRemoveCount = 0; long resourcesReused = 0; long objectsReused = 0; private ValueFactory valueFactory; @Before public void setupTest() throws MalformedURLException { Credentials credentials = buildCredentials(DataTest.class); redlink = RedLinkFactory.createDataClient(credentials); valueFactory = new ValueFactoryImpl(); rnd = new Random(); } @BeforeClass public static void cleanUp() throws Exception { Credentials credentials = buildCredentials(DataTest.class); Assume.assumeNotNull(credentials); Assume.assumeNotNull(credentials.getVersion()); Assume.assumeTrue(credentials.verify()); RedLink.Data redlink = RedLinkFactory.createDataClient(credentials); Assume.assumeTrue(redlink.cleanDataset(TEST_DATASET)); } @Test @Concurrent(count = 5) @Repeating(repetition = 20) public void testConcurrently() throws IOException, RDFHandlerException, InterruptedException { try { Model model = new TreeModel(); // create random triples for(int i=0; i < rnd.nextInt(100) + 1; i++) { model.add(new StatementImpl(randomURI(), randomURI(), randomObject())); } log.debug("created {} random triples", model.size()); redlink.importDataset(model, TEST_DATASET); Model exported = redlink.exportDataset(TEST_DATASET); Assert.assertFalse(exported.isEmpty()); for(Statement stmt : model) { Assert.assertTrue("triple "+stmt+" not contained in exported data", exported.contains(stmt)); } for(Resource r : model.subjects()) { redlink.deleteResource(r.stringValue(), TEST_DATASET); } Model deleted = redlink.exportDataset(TEST_DATASET); for(Statement stmt : model) { Assert.assertFalse("triple "+stmt+" still contained in exported data", deleted.contains(stmt)); Assert.assertFalse("triple "+stmt+" still containrnded in exported data", deleted.contains(stmt)); } } catch (RuntimeException ex) { log.error("exception: ",ex); Assert.fail(ex.getMessage()); } } /** * Return a random URI, with a 10% chance of returning a URI that has already been used. * @return */ protected URI randomURI() { return getValueFactory().createURI("http://localhost/"+ RandomStringUtils.randomAlphanumeric(16)); } /** * Return a random RDF value, either a reused object (10% chance) or of any other kind. * @return */ protected Value randomObject() { Value object; switch(rnd.nextInt(6)) { case 0: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; case 2: object = getValueFactory().createLiteral(RandomStringUtils.randomAscii(40)); break; case 3: object = getValueFactory().createLiteral(rnd.nextInt()); break; case 4: object = getValueFactory().createLiteral(rnd.nextDouble()); break; case 5: object = getValueFactory().createLiteral(rnd.nextBoolean()); break; default: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; } return object; } protected ValueFactory getValueFactory() { return valueFactory; } }
src/test/java/io/redlink/sdk/DataConcurrencyTest.java
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.redlink.sdk; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.openrdf.model.Model; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.StatementImpl; import org.openrdf.model.impl.TreeModel; import org.openrdf.model.impl.ValueFactoryImpl; import org.openrdf.rio.RDFHandlerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.code.tempusfugit.concurrency.ConcurrentRule; import com.google.code.tempusfugit.concurrency.RepeatingRule; import com.google.code.tempusfugit.concurrency.annotations.Concurrent; import com.google.code.tempusfugit.concurrency.annotations.Repeating; /** * Add file description here! * * @author Sebastian Schaffert ([email protected]) */ public class DataConcurrencyTest extends GenericTest { private static final String TEST_DATASET = "test"; private RedLink.Data redlink; @Rule public ConcurrentRule crule = new ConcurrentRule(); @Rule public RepeatingRule rrule = new RepeatingRule(); protected static Random rnd; private static long runs = 0; private static Logger log = LoggerFactory.getLogger(DataConcurrencyTest.class); private List<URI> resources = new ArrayList<>(); private List<Value> objects = new ArrayList<>(); private Set<Statement> allAddedTriples = new HashSet<>(); @Rule public TestWatcher watchman = new TestWatcher() { /** * Invoked when a test is about to start */ @Override protected void starting(Description description) { log.info("{} being run...", description.getMethodName()); } /** * Invoked when a test method finishes (whether passing or failing) */ @Override protected void finished(Description description) { log.info("{}: {} added triples, {} removed triples, {} resources reused, {} objects reused", new Object[] { description.getMethodName(), tripleAddCount, tripleRemoveCount, resourcesReused, objectsReused}); } }; long tripleAddCount = 0; long tripleRemoveCount = 0; long resourcesReused = 0; long objectsReused = 0; private ValueFactory valueFactory; @Before public void setupTest() throws MalformedURLException { Credentials credentials = buildCredentials(DataTest.class); redlink = RedLinkFactory.createDataClient(credentials); valueFactory = new ValueFactoryImpl(); rnd = new Random(); } @BeforeClass public static void cleanUp() throws Exception { Credentials credentials = buildCredentials(DataTest.class); Assume.assumeNotNull(credentials); Assume.assumeNotNull(credentials.getVersion()); Assume.assumeTrue(credentials.verify()); RedLink.Data redlink = RedLinkFactory.createDataClient(credentials); Assume.assumeTrue(redlink.cleanDataset(TEST_DATASET)); } @Test @Concurrent(count = 5) @Repeating(repetition = 20) public void testConcurrently() throws IOException, RDFHandlerException, InterruptedException { try { Model model = new TreeModel(); // create random triples for(int i=0; i < rnd.nextInt(100) + 1; i++) { model.add(new StatementImpl(randomURI(), randomURI(), randomObject())); } log.debug("created {} random triples", model.size()); redlink.importDataset(model, TEST_DATASET); Model exported = redlink.exportDataset(TEST_DATASET); Assert.assertFalse(exported.isEmpty()); for(Statement stmt : model) { Assert.assertTrue("triple "+stmt+" not contained in exported data", exported.contains(stmt)); } for(Resource r : model.subjects()) { redlink.deleteResource(r.stringValue(), TEST_DATASET); } Model deleted = redlink.exportDataset(TEST_DATASET); for(Statement stmt : model) { Assert.assertFalse("triple "+stmt+" still contained in exported data", deleted.contains(stmt)); Assert.assertFalse("triple "+stmt+" still containrnded in exported data", deleted.contains(stmt)); } } catch (RuntimeException ex) { log.error("exception: ",ex); Assert.fail(ex.getMessage()); } } /** * Return a random URI, with a 10% chance of returning a URI that has already been used. * @return */ protected URI randomURI() { return getValueFactory().createURI("http://localhost/"+ RandomStringUtils.randomAlphanumeric(16)); } /** * Return a random RDF value, either a reused object (10% chance) or of any other kind. * @return */ protected Value randomObject() { Value object; switch(rnd.nextInt(6)) { case 0: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; case 2: object = getValueFactory().createLiteral(RandomStringUtils.randomAscii(40)); break; case 3: object = getValueFactory().createLiteral(rnd.nextInt()); break; case 4: object = getValueFactory().createLiteral(rnd.nextDouble()); break; case 5: object = getValueFactory().createLiteral(rnd.nextBoolean()); break; default: object = getValueFactory().createURI("http://data.redlink.io/"+ RandomStringUtils.randomAlphanumeric(8)); break; } return object; } protected ValueFactory getValueFactory() { return valueFactory; } }
cleanup
src/test/java/io/redlink/sdk/DataConcurrencyTest.java
cleanup
Java
apache-2.0
9c44f769c4dcef997e6c7ffb9e7e024360fc34bb
0
fossamagna/liquibase,mattbertolini/liquibase,jimmycd/liquibase,liquibase/liquibase,jimmycd/liquibase,fossamagna/liquibase,fossamagna/liquibase,jimmycd/liquibase,jimmycd/liquibase,mattbertolini/liquibase,liquibase/liquibase,mattbertolini/liquibase,mattbertolini/liquibase,liquibase/liquibase
package liquibase.database.core; import liquibase.CatalogAndSchema; import liquibase.database.AbstractJdbcDatabase; import liquibase.database.DatabaseConnection; import liquibase.database.OfflineConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.ExecutorService; import liquibase.logging.LogService; import liquibase.logging.LogType; import liquibase.statement.core.RawSqlStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Index; import liquibase.structure.core.PrimaryKey; import liquibase.util.StringUtils; import java.math.BigInteger; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.Set; /** * Encapsulates MySQL database support. */ public class MySQLDatabase extends AbstractJdbcDatabase { private static final String PRODUCT_NAME = "MySQL"; private static final Set<String> RESERVED_WORDS = createReservedWords(); private Boolean hasJdbcConstraintDeferrableBug; public MySQLDatabase() { super.setCurrentDateTimeFunction("NOW()"); setHasJdbcConstraintDeferrableBug(null); } @Override public String getShortName() { return "mysql"; } @Override public String correctObjectName(String name, Class<? extends DatabaseObject> objectType) { if (objectType.equals(PrimaryKey.class) && "PRIMARY".equals(name)) { return null; } else { name = super.correctObjectName(name, objectType); if (name == null) { return null; } if (!this.isCaseSensitive()) { return name.toLowerCase(Locale.US); } return name; } } @Override protected String getDefaultDatabaseProductName() { return "MySQL"; } @Override public Integer getDefaultPort() { return 3306; } @Override public int getPriority() { return PRIORITY_DEFAULT; } @Override public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException { // If it looks like a MySQL, swims like a MySQL and quacks like a MySQL, // it may still not be a MySQL, but a MariaDB. return ( (PRODUCT_NAME.equalsIgnoreCase(conn.getDatabaseProductName())) && (!conn.getDatabaseProductVersion().toLowerCase().contains("mariadb")) ); } @Override public String getDefaultDriver(String url) { if (url != null && url.toLowerCase().startsWith("jdbc:mysql")) { String cjDriverClassName = "com.mysql.cj.jdbc.Driver"; try { //make sure we don't have an old jdbc driver that doesn't have this class Class.forName(cjDriverClassName); return cjDriverClassName; } catch (ClassNotFoundException e) { // // Try to load the class again with the current thread classloader // ClassLoader cl = Thread.currentThread().getContextClassLoader(); try { Class.forName(cjDriverClassName, true, cl); return cjDriverClassName; } catch (ClassNotFoundException cnfe) { return "com.mysql.jdbc.Driver"; } } } return null; } @Override public boolean supportsSequences() { return false; } @Override public boolean supportsInitiallyDeferrableColumns() { return false; } @Override protected boolean mustQuoteObjectName(String objectName, Class<? extends DatabaseObject> objectType) { return super.mustQuoteObjectName(objectName, objectType) || (!objectName.contains("(") && !objectName.matches("\\w+")); } @Override public String getLineComment() { return "-- "; } @Override protected String getAutoIncrementClause() { return "AUTO_INCREMENT"; } @Override protected boolean generateAutoIncrementStartWith(final BigInteger startWith) { // startWith not supported here. StartWith has to be set as table option. return false; } public String getTableOptionAutoIncrementStartWithClause(BigInteger startWith) { String startWithClause = String.format(getAutoIncrementStartWithClause(), (startWith == null) ? defaultAutoIncrementStartWith : startWith); return getAutoIncrementClause() + startWithClause; } @Override protected boolean generateAutoIncrementBy(BigInteger incrementBy) { // incrementBy not supported return false; } @Override protected String getAutoIncrementOpening() { return ""; } @Override protected String getAutoIncrementClosing() { return ""; } @Override protected String getAutoIncrementStartWithClause() { return "=%d"; } @Override public String getConcatSql(String... values) { StringBuilder returnString = new StringBuilder(); returnString.append("CONCAT_WS("); for (String value : values) { returnString.append(value).append(", "); } return returnString.toString().replaceFirst(", $", ")"); } @Override public boolean supportsTablespaces() { return false; } @Override public boolean supportsSchemas() { return false; } @Override public boolean supportsCatalogs() { return true; } @Override public String escapeIndexName(String catalogName, String schemaName, String indexName) { return escapeObjectName(indexName, Index.class); } @Override public boolean supportsForeignKeyDisable() { return true; } @Override public boolean disableForeignKeyChecks() throws DatabaseException { boolean enabled = ExecutorService.getInstance().getExecutor(this).queryForInt(new RawSqlStatement("SELECT @@FOREIGN_KEY_CHECKS")) == 1; ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=0")); return enabled; } @Override public void enableForeignKeyChecks() throws DatabaseException { ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=1")); } @Override public CatalogAndSchema getSchemaFromJdbcInfo(String rawCatalogName, String rawSchemaName) { return new CatalogAndSchema(rawCatalogName, null).customize(this); } @Override public String escapeStringForDatabase(String string) { string = super.escapeStringForDatabase(string); if (string == null) { return null; } return string.replace("\\", "\\\\"); } @Override public boolean createsIndexesForForeignKeys() { return true; } @Override public boolean isReservedWord(String string) { if (RESERVED_WORDS.contains(string.toUpperCase())) { return true; } return super.isReservedWord(string); } public int getDatabasePatchVersion() throws DatabaseException { String databaseProductVersion = this.getDatabaseProductVersion(); if (databaseProductVersion == null) { return 0; } String versionStrings[] = databaseProductVersion.split("\\."); try { return Integer.parseInt(versionStrings[2].replaceFirst("\\D.*", "")); } catch (IndexOutOfBoundsException | NumberFormatException e) { return 0; } } /** * Tests if this MySQL / MariaDB database has a bug where the JDBC driver returns constraints as * DEFERRABLE INITIAL IMMEDIATE even though neither MySQL nor MariaDB support DEFERRABLE CONSTRAINTs at all. * We need to know about this because this could lead to errors in database snapshots. * @return true if this database is affected, false if not, null if we cannot tell (e.g. OfflineConnection) */ @SuppressWarnings("squid:S2447") // null is explicitly documented as a possible return value. // TODO: MariaDB connector 2.0.2 appearantly fixes this problem, and MySQL-ConnectorJ 6.0.6 did not have it in // the first place.. Replace this crude workaround with a proper JDBC driver version check public Boolean hasBugJdbcConstraintsDeferrable() throws DatabaseException { if (getConnection() instanceof OfflineConnection) return null; if (getHasJdbcConstraintDeferrableBug() != null) // cached value return getHasJdbcConstraintDeferrableBug(); String randomIdentifier = "TMP_" + StringUtils.randomIdentifer(16); try { // Get the real connection and metadata reference java.sql.Connection conn = ((JdbcConnection) getConnection()).getUnderlyingConnection(); java.sql.DatabaseMetaData metaData = conn.getMetaData(); String sql = "CREATE TABLE " + randomIdentifier + " (\n" + " id INT PRIMARY KEY,\n" + " self_ref INT NOT NULL,\n" + " CONSTRAINT c_self_ref FOREIGN KEY(self_ref) REFERENCES " + randomIdentifier + "(id)\n" + ")"; ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement(sql)); try ( ResultSet rs = metaData.getImportedKeys(getDefaultCatalogName(), getDefaultSchemaName(), randomIdentifier) ) { if (!rs.next()) { throw new UnexpectedLiquibaseException("Error during testing for MySQL/MariaDB JDBC driver bug: " + "could not retrieve JDBC metadata information for temporary table '" + randomIdentifier + "'"); } if (rs.getShort("DEFERRABILITY") != DatabaseMetaData.importedKeyNotDeferrable) { setHasJdbcConstraintDeferrableBug(true); LogService.getLog(getClass()).warning(LogType.LOG, "Your MySQL/MariaDB database JDBC driver might have " + "a bug where constraints are reported as DEFERRABLE, even though MySQL/MariaDB do not " + "support this feature. A workaround for this problem will be used. Please check with " + "MySQL/MariaDB for availability of fixed JDBC drivers to avoid this warning."); } else { setHasJdbcConstraintDeferrableBug(false); } } } catch (DatabaseException|SQLException e) { throw new UnexpectedLiquibaseException("Error during testing for MySQL/MariaDB JDBC driver bug.", e); } finally { ExecutorService.getInstance().reset(); ExecutorService.getInstance().getExecutor(this).execute( new RawSqlStatement("DROP TABLE " + randomIdentifier)); } return getHasJdbcConstraintDeferrableBug(); } /** * returns true if the JDBC drivers suffers from a bug where constraints are reported as DEFERRABLE, even though * MySQL/MariaDB do not support this feature. * @return true if the JDBC is probably affected, false if not. */ protected Boolean getHasJdbcConstraintDeferrableBug() { return hasJdbcConstraintDeferrableBug; } protected void setHasJdbcConstraintDeferrableBug(Boolean hasJdbcConstraintDeferrableBug) { this.hasJdbcConstraintDeferrableBug = hasJdbcConstraintDeferrableBug; } @Override public int getMaxFractionalDigitsForTimestamp() { int major = 0; int minor = 0; int patch = 0; try { major = getDatabaseMajorVersion(); minor = getDatabaseMinorVersion(); patch = getDatabasePatchVersion(); } catch (DatabaseException x) { LogService.getLog(getClass()).warning( LogType.LOG, "Unable to determine exact database server version" + " - specified TIMESTAMP precision" + " will not be set: ", x); return 0; } String minimumVersion = getMinimumVersionForFractionalDigitsForTimestamp(); if (StringUtils.isMinimumVersion(minimumVersion, major, minor, patch)) return 6; else return 0; } protected String getMinimumVersionForFractionalDigitsForTimestamp() { // MySQL 5.6.4 introduced fractional support... // https://dev.mysql.com/doc/refman/5.7/en/data-types.html return "5.6.4"; } @Override protected String getQuotingStartCharacter() { return "`"; // objects in mysql are always case sensitive } @Override protected String getQuotingEndCharacter() { return "`"; // objects in mysql are always case sensitive } /** * <p>Returns the default timestamp fractional digits if nothing is specified.</p> * https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html : * "The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional part. * If omitted, the default precision is 0. (This differs from the STANDARD SQL default of 6, for compatibility * with previous MySQL versions.)" * * @return always 0 */ @Override public int getDefaultFractionalDigitsForTimestamp() { return 0; } /* * list from http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html */ private static Set<String> createReservedWords() { return new HashSet<String>(Arrays.asList("ACCESSIBLE", "ADD", "ADMIN", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BUCKETS", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE", "COLUMN", "CONDITION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CLONE", "COMPONENT", "CUME_DIST", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFINITION", "DELAYED", "DELETE", "DENSE_RANK", "DESC", "DESCRIBE", "DESCRIPTION", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "EMPTY", "ENCLOSED", "ESCAPED", "EXCEPT", "EXCLUDE", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FIRST_VALUE", "FLOAT", "FLOAT4", "FLOAT8", "FOLLOWING", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GEOMCOLLECTION", "GENERATED", "GET", "GET_MASTER_PUBLIC_KEY", "GRANT", "GROUP", "GROUPING", "GROUPS", "HAVING", "HIGH_PRIORITY", "HISTOGRAM", "HISTORY", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "IS", "ITERATE", "INVISIBLE", "JOIN", "JSON_TABLE", "KEY", "KEYS", "KILL", "LAG", "LAST_VALUE", "LEAD", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LOCKED", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MASTER_PUBLIC_KEY_PATH", "MASTER_SSL_VERIFY_SERVER_CERT", "MATCH", "MAXVALUE", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NESTED", "NOT", "NOWAIT", "NO_WRITE_TO_BINLOG", "NTH_VALUE", "NTILE", "NULL", "NULLS", "NUMERIC", "OF", "ON", "OPTIMIZE", "OPTIMIZER_COSTS", "OPTION", "OPTIONALLY", "OR", "ORDER", "ORDINALITY", "ORGANIZATION", "OUT", "OUTER", "OUTFILE", "OTHERS", "OVER", "PARTITION", "PATH", "PERCENT_RANK", "PERSIST", "PERSIST_ONLY", "PRECEDING", "PRECISION", "PRIMARY", "PROCEDURE", "PROCESS", "PURGE", "RANGE", "RANK", "READ", "READS", "READ_WRITE", "REAL", "RECURSIVE", "REFERENCE", "REFERENCES", "REGEXP", "RELEASE", "REMOTE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESIGNAL", "RESOURCE", "RESPECT", "RESTART", "RESTRICT", "RETURN", "REUSE", "REVOKE", "RIGHT", "RLIKE", "ROLE", "ROW_NUMBER", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET", "SHOW", "SIGNAL", "SKIP", "SMALLINT", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SRID", "SSL", "STARTING", "STORED", "STRAIGHT_JOIN", "SYSTEM", "TABLE", "TERMINATED", "THEN", "THREAD_PRIORITY", "TIES", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNBOUNDED", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "VCPU", "VISIBLE", "VIRTUAL", "WHEN", "WHERE", "WHILE", "WINDOW", "WITH", "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL" )); } }
liquibase-core/src/main/java/liquibase/database/core/MySQLDatabase.java
package liquibase.database.core; import liquibase.CatalogAndSchema; import liquibase.database.AbstractJdbcDatabase; import liquibase.database.DatabaseConnection; import liquibase.database.OfflineConnection; import liquibase.database.jvm.JdbcConnection; import liquibase.exception.DatabaseException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.ExecutorService; import liquibase.logging.LogService; import liquibase.logging.LogType; import liquibase.statement.core.RawSqlStatement; import liquibase.structure.DatabaseObject; import liquibase.structure.core.Index; import liquibase.structure.core.PrimaryKey; import liquibase.util.StringUtils; import java.math.BigInteger; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.HashSet; import java.util.Locale; import java.util.Set; /** * Encapsulates MySQL database support. */ public class MySQLDatabase extends AbstractJdbcDatabase { private static final String PRODUCT_NAME = "MySQL"; private static final Set<String> RESERVED_WORDS = createReservedWords(); private Boolean hasJdbcConstraintDeferrableBug; public MySQLDatabase() { super.setCurrentDateTimeFunction("NOW()"); setHasJdbcConstraintDeferrableBug(null); } @Override public String getShortName() { return "mysql"; } @Override public String correctObjectName(String name, Class<? extends DatabaseObject> objectType) { if (objectType.equals(PrimaryKey.class) && "PRIMARY".equals(name)) { return null; } else { name = super.correctObjectName(name, objectType); if (name == null) { return null; } if (!this.isCaseSensitive()) { return name.toLowerCase(Locale.US); } return name; } } @Override protected String getDefaultDatabaseProductName() { return "MySQL"; } @Override public Integer getDefaultPort() { return 3306; } @Override public int getPriority() { return PRIORITY_DEFAULT; } @Override public boolean isCorrectDatabaseImplementation(DatabaseConnection conn) throws DatabaseException { // If it looks like a MySQL, swims like a MySQL and quacks like a MySQL, // it may still not be a MySQL, but a MariaDB. return ( (PRODUCT_NAME.equalsIgnoreCase(conn.getDatabaseProductName())) && (!conn.getDatabaseProductVersion().toLowerCase().contains("mariadb")) ); } @Override public String getDefaultDriver(String url) { if (url != null && url.toLowerCase().startsWith("jdbc:mysql")) { try { String cjDriverClassName = "com.mysql.cj.jdbc.Driver"; //make sure we don't have an old jdbc driver that doesn't have this class Class.forName(cjDriverClassName); return cjDriverClassName; } catch (ClassNotFoundException e) { return "com.mysql.jdbc.Driver"; } } return null; } @Override public boolean supportsSequences() { return false; } @Override public boolean supportsInitiallyDeferrableColumns() { return false; } @Override protected boolean mustQuoteObjectName(String objectName, Class<? extends DatabaseObject> objectType) { return super.mustQuoteObjectName(objectName, objectType) || (!objectName.contains("(") && !objectName.matches("\\w+")); } @Override public String getLineComment() { return "-- "; } @Override protected String getAutoIncrementClause() { return "AUTO_INCREMENT"; } @Override protected boolean generateAutoIncrementStartWith(final BigInteger startWith) { // startWith not supported here. StartWith has to be set as table option. return false; } public String getTableOptionAutoIncrementStartWithClause(BigInteger startWith) { String startWithClause = String.format(getAutoIncrementStartWithClause(), (startWith == null) ? defaultAutoIncrementStartWith : startWith); return getAutoIncrementClause() + startWithClause; } @Override protected boolean generateAutoIncrementBy(BigInteger incrementBy) { // incrementBy not supported return false; } @Override protected String getAutoIncrementOpening() { return ""; } @Override protected String getAutoIncrementClosing() { return ""; } @Override protected String getAutoIncrementStartWithClause() { return "=%d"; } @Override public String getConcatSql(String... values) { StringBuilder returnString = new StringBuilder(); returnString.append("CONCAT_WS("); for (String value : values) { returnString.append(value).append(", "); } return returnString.toString().replaceFirst(", $", ")"); } @Override public boolean supportsTablespaces() { return false; } @Override public boolean supportsSchemas() { return false; } @Override public boolean supportsCatalogs() { return true; } @Override public String escapeIndexName(String catalogName, String schemaName, String indexName) { return escapeObjectName(indexName, Index.class); } @Override public boolean supportsForeignKeyDisable() { return true; } @Override public boolean disableForeignKeyChecks() throws DatabaseException { boolean enabled = ExecutorService.getInstance().getExecutor(this).queryForInt(new RawSqlStatement("SELECT @@FOREIGN_KEY_CHECKS")) == 1; ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=0")); return enabled; } @Override public void enableForeignKeyChecks() throws DatabaseException { ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement("SET FOREIGN_KEY_CHECKS=1")); } @Override public CatalogAndSchema getSchemaFromJdbcInfo(String rawCatalogName, String rawSchemaName) { return new CatalogAndSchema(rawCatalogName, null).customize(this); } @Override public String escapeStringForDatabase(String string) { string = super.escapeStringForDatabase(string); if (string == null) { return null; } return string.replace("\\", "\\\\"); } @Override public boolean createsIndexesForForeignKeys() { return true; } @Override public boolean isReservedWord(String string) { if (RESERVED_WORDS.contains(string.toUpperCase())) { return true; } return super.isReservedWord(string); } public int getDatabasePatchVersion() throws DatabaseException { String databaseProductVersion = this.getDatabaseProductVersion(); if (databaseProductVersion == null) { return 0; } String versionStrings[] = databaseProductVersion.split("\\."); try { return Integer.parseInt(versionStrings[2].replaceFirst("\\D.*", "")); } catch (IndexOutOfBoundsException | NumberFormatException e) { return 0; } } /** * Tests if this MySQL / MariaDB database has a bug where the JDBC driver returns constraints as * DEFERRABLE INITIAL IMMEDIATE even though neither MySQL nor MariaDB support DEFERRABLE CONSTRAINTs at all. * We need to know about this because this could lead to errors in database snapshots. * @return true if this database is affected, false if not, null if we cannot tell (e.g. OfflineConnection) */ @SuppressWarnings("squid:S2447") // null is explicitly documented as a possible return value. // TODO: MariaDB connector 2.0.2 appearantly fixes this problem, and MySQL-ConnectorJ 6.0.6 did not have it in // the first place.. Replace this crude workaround with a proper JDBC driver version check public Boolean hasBugJdbcConstraintsDeferrable() throws DatabaseException { if (getConnection() instanceof OfflineConnection) return null; if (getHasJdbcConstraintDeferrableBug() != null) // cached value return getHasJdbcConstraintDeferrableBug(); String randomIdentifier = "TMP_" + StringUtils.randomIdentifer(16); try { // Get the real connection and metadata reference java.sql.Connection conn = ((JdbcConnection) getConnection()).getUnderlyingConnection(); java.sql.DatabaseMetaData metaData = conn.getMetaData(); String sql = "CREATE TABLE " + randomIdentifier + " (\n" + " id INT PRIMARY KEY,\n" + " self_ref INT NOT NULL,\n" + " CONSTRAINT c_self_ref FOREIGN KEY(self_ref) REFERENCES " + randomIdentifier + "(id)\n" + ")"; ExecutorService.getInstance().getExecutor(this).execute(new RawSqlStatement(sql)); try ( ResultSet rs = metaData.getImportedKeys(getDefaultCatalogName(), getDefaultSchemaName(), randomIdentifier) ) { if (!rs.next()) { throw new UnexpectedLiquibaseException("Error during testing for MySQL/MariaDB JDBC driver bug: " + "could not retrieve JDBC metadata information for temporary table '" + randomIdentifier + "'"); } if (rs.getShort("DEFERRABILITY") != DatabaseMetaData.importedKeyNotDeferrable) { setHasJdbcConstraintDeferrableBug(true); LogService.getLog(getClass()).warning(LogType.LOG, "Your MySQL/MariaDB database JDBC driver might have " + "a bug where constraints are reported as DEFERRABLE, even though MySQL/MariaDB do not " + "support this feature. A workaround for this problem will be used. Please check with " + "MySQL/MariaDB for availability of fixed JDBC drivers to avoid this warning."); } else { setHasJdbcConstraintDeferrableBug(false); } } } catch (DatabaseException|SQLException e) { throw new UnexpectedLiquibaseException("Error during testing for MySQL/MariaDB JDBC driver bug.", e); } finally { ExecutorService.getInstance().reset(); ExecutorService.getInstance().getExecutor(this).execute( new RawSqlStatement("DROP TABLE " + randomIdentifier)); } return getHasJdbcConstraintDeferrableBug(); } /** * returns true if the JDBC drivers suffers from a bug where constraints are reported as DEFERRABLE, even though * MySQL/MariaDB do not support this feature. * @return true if the JDBC is probably affected, false if not. */ protected Boolean getHasJdbcConstraintDeferrableBug() { return hasJdbcConstraintDeferrableBug; } protected void setHasJdbcConstraintDeferrableBug(Boolean hasJdbcConstraintDeferrableBug) { this.hasJdbcConstraintDeferrableBug = hasJdbcConstraintDeferrableBug; } @Override public int getMaxFractionalDigitsForTimestamp() { int major = 0; int minor = 0; int patch = 0; try { major = getDatabaseMajorVersion(); minor = getDatabaseMinorVersion(); patch = getDatabasePatchVersion(); } catch (DatabaseException x) { LogService.getLog(getClass()).warning( LogType.LOG, "Unable to determine exact database server version" + " - specified TIMESTAMP precision" + " will not be set: ", x); return 0; } String minimumVersion = getMinimumVersionForFractionalDigitsForTimestamp(); if (StringUtils.isMinimumVersion(minimumVersion, major, minor, patch)) return 6; else return 0; } protected String getMinimumVersionForFractionalDigitsForTimestamp() { // MySQL 5.6.4 introduced fractional support... // https://dev.mysql.com/doc/refman/5.7/en/data-types.html return "5.6.4"; } @Override protected String getQuotingStartCharacter() { return "`"; // objects in mysql are always case sensitive } @Override protected String getQuotingEndCharacter() { return "`"; // objects in mysql are always case sensitive } /** * <p>Returns the default timestamp fractional digits if nothing is specified.</p> * https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html : * "The fsp value, if given, must be in the range 0 to 6. A value of 0 signifies that there is no fractional part. * If omitted, the default precision is 0. (This differs from the STANDARD SQL default of 6, for compatibility * with previous MySQL versions.)" * * @return always 0 */ @Override public int getDefaultFractionalDigitsForTimestamp() { return 0; } /* * list from http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html */ private static Set<String> createReservedWords() { return new HashSet<String>(Arrays.asList("ACCESSIBLE", "ADD", "ADMIN", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ASENSITIVE", "BEFORE", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BUCKETS", "BY", "CALL", "CASCADE", "CASE", "CHANGE", "CHAR", "CHARACTER", "CHECK", "COLLATE", "COLUMN", "CONDITION", "CONSTRAINT", "CONTINUE", "CONVERT", "CREATE", "CROSS", "CLONE", "COMPONENT", "CUME_DIST", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MICROSECOND", "DAY_MINUTE", "DAY_SECOND", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFINITION", "DELAYED", "DELETE", "DENSE_RANK", "DESC", "DESCRIBE", "DESCRIPTION", "DETERMINISTIC", "DISTINCT", "DISTINCTROW", "DIV", "DOUBLE", "DROP", "DUAL", "EACH", "ELSE", "ELSEIF", "EMPTY", "ENCLOSED", "ESCAPED", "EXCEPT", "EXCLUDE", "EXISTS", "EXIT", "EXPLAIN", "FALSE", "FETCH", "FIRST_VALUE", "FLOAT", "FLOAT4", "FLOAT8", "FOLLOWING", "FOR", "FORCE", "FOREIGN", "FROM", "FULLTEXT", "GEOMCOLLECTION", "GENERATED", "GET", "GET_MASTER_PUBLIC_KEY", "GRANT", "GROUP", "GROUPING", "GROUPS", "HAVING", "HIGH_PRIORITY", "HISTOGRAM", "HISTORY", "HOUR_MICROSECOND", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "IN", "INDEX", "INFILE", "INNER", "INOUT", "INSENSITIVE", "INSERT", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "INTEGER", "INTERVAL", "INTO", "IS", "ITERATE", "INVISIBLE", "JOIN", "JSON_TABLE", "KEY", "KEYS", "KILL", "LAG", "LAST_VALUE", "LEAD", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LINEAR", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LOCKED", "LONG", "LONGBLOB", "LONGTEXT", "LOOP", "LOW_PRIORITY", "MASTER_PUBLIC_KEY_PATH", "MASTER_SSL_VERIFY_SERVER_CERT", "MATCH", "MAXVALUE", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_MICROSECOND", "MINUTE_SECOND", "MOD", "MODIFIES", "NATURAL", "NESTED", "NOT", "NOWAIT", "NO_WRITE_TO_BINLOG", "NTH_VALUE", "NTILE", "NULL", "NULLS", "NUMERIC", "OF", "ON", "OPTIMIZE", "OPTIMIZER_COSTS", "OPTION", "OPTIONALLY", "OR", "ORDER", "ORDINALITY", "ORGANIZATION", "OUT", "OUTER", "OUTFILE", "OTHERS", "OVER", "PARTITION", "PATH", "PERCENT_RANK", "PERSIST", "PERSIST_ONLY", "PRECEDING", "PRECISION", "PRIMARY", "PROCEDURE", "PROCESS", "PURGE", "RANGE", "RANK", "READ", "READS", "READ_WRITE", "REAL", "RECURSIVE", "REFERENCE", "REFERENCES", "REGEXP", "RELEASE", "REMOTE", "RENAME", "REPEAT", "REPLACE", "REQUIRE", "RESIGNAL", "RESOURCE", "RESPECT", "RESTART", "RESTRICT", "RETURN", "REUSE", "REVOKE", "RIGHT", "RLIKE", "ROLE", "ROW_NUMBER", "SCHEMA", "SCHEMAS", "SECOND_MICROSECOND", "SELECT", "SENSITIVE", "SEPARATOR", "SET", "SHOW", "SIGNAL", "SKIP", "SMALLINT", "SPATIAL", "SPECIFIC", "SQL", "SQLEXCEPTION", "SQLSTATE", "SQLWARNING", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SRID", "SSL", "STARTING", "STORED", "STRAIGHT_JOIN", "SYSTEM", "TABLE", "TERMINATED", "THEN", "THREAD_PRIORITY", "TIES", "TINYBLOB", "TINYINT", "TINYTEXT", "TO", "TRAILING", "TRIGGER", "TRUE", "UNBOUNDED", "UNDO", "UNION", "UNIQUE", "UNLOCK", "UNSIGNED", "UPDATE", "USAGE", "USE", "USING", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "VALUES", "VARBINARY", "VARCHAR", "VARCHARACTER", "VARYING", "VCPU", "VISIBLE", "VIRTUAL", "WHEN", "WHERE", "WHILE", "WINDOW", "WITH", "WRITE", "XOR", "YEAR_MONTH", "ZEROFILL" )); } }
Handle issue with defaulting of MySQL driver class DAT-4104
liquibase-core/src/main/java/liquibase/database/core/MySQLDatabase.java
Handle issue with defaulting of MySQL driver class DAT-4104
Java
apache-2.0
f688f2edd9ee2b4f7d2d99ae166ae2ee8d2c6073
0
ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.NullableNotNullManager; import com.intellij.codeInsight.PsiEquivalenceUtil; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.intention.impl.AddNotNullAnnotationFix; import com.intellij.codeInsight.intention.impl.AddNullableAnnotationFix; import com.intellij.codeInspection.*; import com.intellij.codeInspection.dataFlow.NullabilityProblemKind.NullabilityProblem; import com.intellij.codeInspection.dataFlow.fix.RedundantInstanceofFix; import com.intellij.codeInspection.dataFlow.fix.ReplaceWithConstantValueFix; import com.intellij.codeInspection.dataFlow.fix.ReplaceWithObjectsEqualsFix; import com.intellij.codeInspection.dataFlow.fix.SimplifyToAssignmentFix; import com.intellij.codeInspection.dataFlow.instructions.*; import com.intellij.codeInspection.dataFlow.value.DfaConstValue; import com.intellij.codeInspection.dataFlow.value.DfaValue; import com.intellij.codeInspection.nullable.NullableStuffInspectionBase; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.siyeh.ig.psiutils.ComparisonUtils; import com.siyeh.ig.psiutils.ControlFlowUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.TestUtils; import one.util.streamex.StreamEx; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; @SuppressWarnings("ConditionalExpressionWithIdenticalBranches") public class DataFlowInspectionBase extends AbstractBaseJavaLocalInspectionTool { static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.DataFlowInspection"); @NonNls private static final String SHORT_NAME = "ConstantConditions"; public boolean SUGGEST_NULLABLE_ANNOTATIONS; public boolean DONT_REPORT_TRUE_ASSERT_STATEMENTS; public boolean TREAT_UNKNOWN_MEMBERS_AS_NULLABLE; public boolean IGNORE_ASSERT_STATEMENTS; public boolean REPORT_CONSTANT_REFERENCE_VALUES = true; public boolean REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER = true; public boolean REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL = true; public boolean REPORT_UNCHECKED_OPTIONALS = true; @Override public JComponent createOptionsPanel() { throw new RuntimeException("no UI in headless mode"); } @Override public void writeSettings(@NotNull Element node) throws WriteExternalException { node.addContent(new Element("option").setAttribute("name", "SUGGEST_NULLABLE_ANNOTATIONS").setAttribute("value", String.valueOf(SUGGEST_NULLABLE_ANNOTATIONS))); node.addContent(new Element("option").setAttribute("name", "DONT_REPORT_TRUE_ASSERT_STATEMENTS").setAttribute("value", String.valueOf(DONT_REPORT_TRUE_ASSERT_STATEMENTS))); if (IGNORE_ASSERT_STATEMENTS) { node.addContent(new Element("option").setAttribute("name", "IGNORE_ASSERT_STATEMENTS").setAttribute("value", "true")); } if (!REPORT_CONSTANT_REFERENCE_VALUES) { node.addContent(new Element("option").setAttribute("name", "REPORT_CONSTANT_REFERENCE_VALUES").setAttribute("value", "false")); } if (TREAT_UNKNOWN_MEMBERS_AS_NULLABLE) { node.addContent(new Element("option").setAttribute("name", "TREAT_UNKNOWN_MEMBERS_AS_NULLABLE").setAttribute("value", "true")); } if (!REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER) { node.addContent(new Element("option").setAttribute("name", "REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER").setAttribute("value", "false")); } if (!REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL) { node.addContent(new Element("option").setAttribute("name", "REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL").setAttribute("value", "false")); } if (!REPORT_UNCHECKED_OPTIONALS) { node.addContent(new Element("option").setAttribute("name", "REPORT_UNCHECKED_OPTIONALS").setAttribute("value", "false")); } } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitClass(PsiClass aClass) { if (aClass instanceof PsiTypeParameter) return; analyzeCodeBlock(aClass, holder); } @Override public void visitMethod(PsiMethod method) { analyzeCodeBlock(method.getBody(), holder); analyzeNullLiteralMethodArguments(method, holder); } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { super.visitMethodReferenceExpression(expression); final PsiElement resolve = expression.resolve(); if (resolve instanceof PsiMethod) { final PsiType methodReturnType = ((PsiMethod)resolve).getReturnType(); if (TypeConversionUtil.isPrimitiveWrapper(methodReturnType) && NullableNotNullManager.isNullable((PsiMethod)resolve)) { final PsiType returnType = LambdaUtil.getFunctionalInterfaceReturnType(expression); if (TypeConversionUtil.isPrimitiveAndNotNull(returnType)) { holder.registerProblem(expression, InspectionsBundle.message("dataflow.message.unboxing.method.reference")); } } } } @Override public void visitIfStatement(PsiIfStatement statement) { PsiExpression condition = PsiUtil.skipParenthesizedExprDown(statement.getCondition()); if (BranchingInstruction.isBoolConst(condition)) { LocalQuickFix fix = createSimplifyBooleanExpressionFix(condition, condition.textMatches(PsiKeyword.TRUE)); holder.registerProblem(condition, "Condition is always " + condition.getText(), fix); } } @Override public void visitWhileStatement(PsiWhileStatement statement) { checkLoopCondition(statement.getCondition()); } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { checkLoopCondition(statement.getCondition()); } @Override public void visitForStatement(PsiForStatement statement) { checkLoopCondition(statement.getCondition()); } private void checkLoopCondition(PsiExpression condition) { condition = PsiUtil.skipParenthesizedExprDown(condition); if (condition != null && condition.textMatches(PsiKeyword.FALSE)) { holder.registerProblem(condition, "Condition is always false", createSimplifyBooleanExpressionFix(condition, false)); } } }; } protected LocalQuickFix createNavigateToNullParameterUsagesFix(PsiParameter parameter) { return null; } private void analyzeNullLiteralMethodArguments(PsiMethod method, ProblemsHolder holder) { if (REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER && holder.isOnTheFly()) { for (PsiParameter parameter : NullParameterConstraintChecker.checkMethodParameters(method)) { PsiIdentifier name = parameter.getNameIdentifier(); if (name != null) { holder.registerProblem(name, InspectionsBundle.message("dataflow.method.fails.with.null.argument"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, createNavigateToNullParameterUsagesFix(parameter)); } } } } private void analyzeCodeBlock(@Nullable final PsiElement scope, ProblemsHolder holder) { if (scope == null) return; PsiClass containingClass = PsiTreeUtil.getNonStrictParentOfType(scope, PsiClass.class); if (containingClass != null && PsiUtil.isLocalOrAnonymousClass(containingClass) && !(containingClass instanceof PsiEnumConstantInitializer)) return; final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner(TREAT_UNKNOWN_MEMBERS_AS_NULLABLE, !DfaUtil.isInsideConstructorOrInitializer(scope)); analyzeDfaWithNestedClosures(scope, holder, dfaRunner, Collections.singletonList(dfaRunner.createMemoryState())); } private void analyzeDfaWithNestedClosures(PsiElement scope, ProblemsHolder holder, StandardDataFlowRunner dfaRunner, Collection<? extends DfaMemoryState> initialStates) { final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(); final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates); if (rc == RunnerResult.OK) { createDescription(dfaRunner, holder, visitor, scope); dfaRunner.forNestedClosures((closure, states) -> analyzeDfaWithNestedClosures(closure, holder, dfaRunner, states)); } else if (rc == RunnerResult.TOO_COMPLEX) { PsiIdentifier name = null; String message = null; if(scope.getParent() instanceof PsiMethod) { name = ((PsiMethod)scope.getParent()).getNameIdentifier(); message = InspectionsBundle.message("dataflow.too.complex"); } else if(scope instanceof PsiClass) { name = ((PsiClass)scope).getNameIdentifier(); message = InspectionsBundle.message("dataflow.too.complex.class"); } if (name != null) { // Might be null for synthetic methods like JSP page. holder.registerProblem(name, message, ProblemHighlightType.WEAK_WARNING); } } } @NotNull protected List<LocalQuickFix> createNPEFixes(PsiExpression qualifier, PsiExpression expression, boolean onTheFly) { return Collections.emptyList(); } protected List<LocalQuickFix> createMethodReferenceNPEFixes(PsiMethodReferenceExpression methodRef) { return Collections.emptyList(); } @Nullable protected LocalQuickFix createIntroduceVariableFix(PsiExpression expression) { return null; } protected LocalQuickFix createRemoveAssignmentFix(PsiAssignmentExpression assignment) { return null; } protected LocalQuickFix createReplaceWithTrivialLambdaFix(Object value) { return null; } private void createDescription(StandardDataFlowRunner runner, ProblemsHolder holder, final DataFlowInstructionVisitor visitor, PsiElement scope) { Pair<Set<Instruction>, Set<Instruction>> constConditions = runner.getConstConditionalExpressions(); Set<Instruction> trueSet = constConditions.getFirst(); Set<Instruction> falseSet = constConditions.getSecond(); ArrayList<Instruction> allProblems = new ArrayList<>(); allProblems.addAll(trueSet); allProblems.addAll(falseSet); allProblems.addAll(visitor.getClassCastExceptionInstructions()); allProblems.addAll(ContainerUtil.filter(runner.getInstructions(), instruction1 -> instruction1 instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction)instruction1))); HashSet<PsiElement> reportedAnchors = new HashSet<>(); for (Instruction instruction : allProblems) { if (instruction instanceof TypeCastInstruction && reportedAnchors.add(((TypeCastInstruction)instruction).getCastExpression().getCastType())) { reportCastMayFail(holder, (TypeCastInstruction)instruction); } else if (instruction instanceof BranchingInstruction) { handleBranchingInstruction(holder, visitor, trueSet, falseSet, reportedAnchors, (BranchingInstruction)instruction); } } reportAlwaysFailingCalls(holder, visitor, reportedAnchors); reportConstantPushes(runner, holder, reportedAnchors); reportNullabilityProblems(holder, visitor, reportedAnchors); reportNullableReturns(visitor, holder, reportedAnchors, scope); if (SUGGEST_NULLABLE_ANNOTATIONS) { reportNullableArgumentsPassedToNonAnnotated(visitor, holder, reportedAnchors); } reportOptionalOfNullableImprovements(holder, reportedAnchors, visitor.getOfNullableCalls()); reportUncheckedOptionalGet(holder, visitor.getOptionalCalls(), visitor.getOptionalQualifiers()); visitor.getBooleanCalls().forEach((call, state) -> { if (state != ThreeState.UNSURE && reportedAnchors.add(call)) { reportConstantCondition(holder, call, state.toBoolean()); } }); reportMethodReferenceProblems(holder, visitor); reportArrayAccessProblems(holder, visitor); reportArrayStoreProblems(holder, visitor); if (REPORT_CONSTANT_REFERENCE_VALUES) { reportConstantReferenceValues(holder, visitor, reportedAnchors); } if (REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL && visitor.isAlwaysReturnsNotNull(runner.getInstructions())) { reportAlwaysReturnsNotNull(holder, scope); } reportMutabilityViolations(holder, reportedAnchors, visitor.getMutabilityViolations(true), InspectionsBundle.message("dataflow.message.immutable.modified")); reportMutabilityViolations(holder, reportedAnchors, visitor.getMutabilityViolations(false), InspectionsBundle.message("dataflow.message.immutable.passed")); reportDuplicateAssignments(holder, reportedAnchors, visitor); } private void reportDuplicateAssignments(ProblemsHolder holder, HashSet<PsiElement> reportedAnchors, DataFlowInstructionVisitor visitor) { visitor.sameValueAssignments().forEach(expr -> { if(!reportedAnchors.add(expr)) return; PsiAssignmentExpression assignment = PsiTreeUtil.getParentOfType(expr, PsiAssignmentExpression.class); PsiElement context = PsiTreeUtil.getParentOfType(expr, PsiForStatement.class, PsiClassInitializer.class); if (context instanceof PsiForStatement && PsiTreeUtil.isAncestor(((PsiForStatement)context).getInitialization(), expr, true)) { return; } if (context instanceof PsiClassInitializer && expr instanceof PsiReferenceExpression) { if (assignment != null) { Object constValue = ExpressionUtils.computeConstantExpression(assignment.getRExpression()); if (constValue == PsiTypesUtil.getDefaultValue(expr.getType())) { PsiReferenceExpression ref = (PsiReferenceExpression)expr; PsiElement target = ref.resolve(); if (target instanceof PsiField && (((PsiField)target).hasModifierProperty(PsiModifier.STATIC) || ExpressionUtils.isEffectivelyUnqualified(ref)) && ((PsiField)target).getContainingClass() == ((PsiClassInitializer)context).getContainingClass()) { return; } } } } holder.registerProblem(expr, InspectionsBundle.message("dataflow.message.redundant.assignment"), createRemoveAssignmentFix(assignment)); }); } private static void reportMutabilityViolations(ProblemsHolder holder, Set<PsiElement> reportedAnchors, Set<PsiElement> violations, String message) { for (PsiElement violation : violations) { if (reportedAnchors.add(violation)) { holder.registerProblem(violation, message); } } } private void reportNullabilityProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor, HashSet<PsiElement> reportedAnchors) { visitor.problems().forEach(problem -> { if (NullabilityProblemKind.passingNullableArgumentToNonAnnotatedParameter.isMyProblem(problem) || NullabilityProblemKind.nullableReturn.isMyProblem(problem)) { // these two kinds are still reported separately return; } if (!reportedAnchors.add(problem.getAnchor())) return; NullabilityProblemKind.innerClassNPE.ifMyProblem(problem, newExpression -> { List<LocalQuickFix> fixes = createNPEFixes(newExpression.getQualifier(), newExpression, holder.isOnTheFly()); holder.registerProblem(getElementToHighlight(newExpression), problem.getMessage(), fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); }); NullabilityProblemKind.callMethodRefNPE.ifMyProblem(problem, methodRef -> holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.npe.methodref.invocation"), createMethodReferenceNPEFixes(methodRef).toArray(LocalQuickFix.EMPTY_ARRAY))); NullabilityProblemKind.callNPE.ifMyProblem(problem, call -> reportCallMayProduceNpe(holder, call)); NullabilityProblemKind.passingNullableToNotNullParameter.ifMyProblem(problem, expr -> reportNullableArgument(holder, expr)); NullabilityProblemKind.arrayAccessNPE.ifMyProblem(problem, expression -> { LocalQuickFix[] fix = createNPEFixes(expression.getArrayExpression(), expression, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY); holder.registerProblem(expression, problem.getMessage(), fix); }); NullabilityProblemKind.fieldAccessNPE.ifMyProblem(problem, element -> { PsiElement parent = element.getParent(); PsiExpression fieldAccess = parent instanceof PsiReferenceExpression ? (PsiExpression)parent : element; LocalQuickFix[] fix = createNPEFixes(element, fieldAccess, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY); holder.registerProblem(element, problem.getMessage(), fix); }); NullabilityProblemKind.unboxingNullable.ifMyProblem(problem, element -> holder.registerProblem(element, problem.getMessage())); NullabilityProblemKind.nullableFunctionReturn.ifMyProblem(problem, expr -> holder.registerProblem(expr, problem.getMessage())); NullabilityProblemKind.assigningToNotNull.ifMyProblem(problem, expr -> reportNullabilityProblem(holder, problem, expr)); NullabilityProblemKind.storingToNotNullArray.ifMyProblem(problem, expr -> reportNullabilityProblem(holder, problem, expr)); }); } private void reportNullabilityProblem(ProblemsHolder holder, NullabilityProblem<?> problem, PsiExpression expr) { holder.registerProblem(expr, problem.getMessage(), createNPEFixes(expr, expr, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY)); } private static void reportArrayAccessProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.outOfBoundsArrayAccesses().forEach(access -> { PsiExpression indexExpression = access.getIndexExpression(); if (indexExpression != null) { holder.registerProblem(indexExpression, InspectionsBundle.message("dataflow.message.array.index.out.of.bounds")); } }); } private static void reportArrayStoreProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.getArrayStoreProblems().forEach( (assignment, types) -> holder.registerProblem(assignment.getOperationSign(), InspectionsBundle .message("dataflow.message.arraystore", types.getFirst().getCanonicalText(), types.getSecond().getCanonicalText()))); } private void reportMethodReferenceProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.getMethodReferenceResults().forEach((methodRef, dfaValue) -> { if (dfaValue instanceof DfaConstValue) { Object value = ((DfaConstValue)dfaValue).getValue(); if(value instanceof Boolean) { holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.constant.method.reference", value), createReplaceWithTrivialLambdaFix(value)); } } }); } private void reportUncheckedOptionalGet(ProblemsHolder holder, Map<PsiMethodCallExpression, ThreeState> calls, List<PsiExpression> qualifiers) { if (!REPORT_UNCHECKED_OPTIONALS) return; for (Map.Entry<PsiMethodCallExpression, ThreeState> entry : calls.entrySet()) { ThreeState state = entry.getValue(); if (state != ThreeState.UNSURE) continue; PsiMethodCallExpression call = entry.getKey(); PsiMethod method = call.resolveMethod(); if (method == null) continue; PsiClass optionalClass = method.getContainingClass(); if (optionalClass == null) continue; PsiExpression qualifier = PsiUtil.skipParenthesizedExprDown(call.getMethodExpression().getQualifierExpression()); if (qualifier instanceof PsiMethodCallExpression && qualifiers.stream().anyMatch(q -> PsiEquivalenceUtil.areElementsEquivalent(q, qualifier))) { // Conservatively do not report methodCall().get() cases if methodCall().isPresent() was found in the same method // without deep correspondence analysis continue; } LocalQuickFix fix = holder.isOnTheFly() ? new SetInspectionOptionFix(this, "REPORT_UNCHECKED_OPTIONALS", InspectionsBundle .message("inspection.data.flow.turn.off.unchecked.optional.get.quickfix"), false) : null; holder.registerProblem(getElementToHighlight(call), InspectionsBundle.message("dataflow.message.optional.get.without.is.present", optionalClass.getName()), fix); } } private void reportAlwaysReturnsNotNull(ProblemsHolder holder, PsiElement scope) { if (!(scope.getParent() instanceof PsiMethod)) return; PsiMethod method = (PsiMethod)scope.getParent(); if (PsiUtil.canBeOverridden(method)) return; PsiAnnotation nullableAnno = NullableNotNullManager.getInstance(scope.getProject()).getNullableAnnotation(method, false); if (nullableAnno == null || !nullableAnno.isPhysical()) return; PsiJavaCodeReferenceElement annoName = nullableAnno.getNameReferenceElement(); assert annoName != null; String msg = "@" + NullableStuffInspectionBase.getPresentableAnnoName(nullableAnno) + " method '" + method.getName() + "' always returns a non-null value"; LocalQuickFix[] fixes = {new AddNotNullAnnotationFix(method)}; if (holder.isOnTheFly()) { fixes = ArrayUtil.append(fixes, new SetInspectionOptionFix(this, "REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL", InspectionsBundle .message( "inspection.data.flow.turn.off.nullable.returning.notnull.quickfix"), false)); } holder.registerProblem(annoName, msg, fixes); } private static void reportAlwaysFailingCalls(ProblemsHolder holder, DataFlowInstructionVisitor visitor, HashSet<PsiElement> reportedAnchors) { visitor.getAlwaysFailingCalls().forEach((call, contracts) -> { if (TestUtils.isExceptionExpected(call)) return; PsiMethod method = call.resolveMethod(); if (method != null && reportedAnchors.add(call)) { holder.registerProblem(getElementToHighlight(call), getContractMessage(contracts)); } }); } @NotNull private static String getContractMessage(List<MethodContract> contracts) { if (contracts.stream().allMatch(mc -> mc.getConditions().stream().allMatch(cv -> cv.isBoundCheckingCondition()))) { return InspectionsBundle.message("dataflow.message.contract.fail.index"); } return InspectionsBundle.message("dataflow.message.contract.fail"); } @NotNull private static PsiElement getElementToHighlight(@NotNull PsiCall call) { PsiJavaCodeReferenceElement ref; if (call instanceof PsiNewExpression) { ref = ((PsiNewExpression)call).getClassReference(); } else if (call instanceof PsiMethodCallExpression) { ref = ((PsiMethodCallExpression)call).getMethodExpression(); } else { return call; } if (ref != null) { PsiElement name = ref.getReferenceNameElement(); return name != null ? name : ref; } return call; } private void reportConstantPushes(StandardDataFlowRunner runner, ProblemsHolder holder, Set<PsiElement> reportedAnchors) { for (Instruction instruction : runner.getInstructions()) { if (instruction instanceof PushInstruction) { PsiExpression place = ((PushInstruction)instruction).getPlace(); DfaValue value = ((PushInstruction)instruction).getValue(); Object constant = value instanceof DfaConstValue ? ((DfaConstValue)value).getValue() : null; if (place instanceof PsiPolyadicExpression && constant instanceof Boolean && !isFlagCheck(place) && reportedAnchors.add(place)) { reportConstantCondition(holder, place, (Boolean)constant); } } } } private static void reportOptionalOfNullableImprovements(ProblemsHolder holder, Set<PsiElement> reportedAnchors, Map<MethodCallInstruction, ThreeState> nullArgs) { nullArgs.forEach((call, nullArg) -> { PsiElement arg = call.getArgumentAnchor(0); if (reportedAnchors.add(arg)) { switch (nullArg) { case YES: holder.registerProblem(arg, "Passing <code>null</code> argument to <code>Optional</code>", DfaOptionalSupport.createReplaceOptionalOfNullableWithEmptyFix(arg)); break; case NO: holder.registerProblem(arg, "Passing a non-null argument to <code>Optional</code>", DfaOptionalSupport.createReplaceOptionalOfNullableWithOfFix(arg)); break; default: } } }); } private void reportConstantReferenceValues(ProblemsHolder holder, DataFlowInstructionVisitor visitor, Set<PsiElement> reportedAnchors) { for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) { PsiReferenceExpression ref = pair.first; if (ref.getParent() instanceof PsiReferenceExpression || !reportedAnchors.add(ref)) { continue; } final Object value = pair.second.getValue(); PsiVariable constant = pair.second.getConstant(); final String presentableName = constant != null ? constant.getName() : String.valueOf(value); final String exprText = String.valueOf(value); if (presentableName == null || exprText == null) { continue; } LocalQuickFix[] fixes = {new ReplaceWithConstantValueFix(presentableName, exprText)}; if (holder.isOnTheFly()) { fixes = ArrayUtil.append(fixes, new SetInspectionOptionFix(this, "REPORT_CONSTANT_REFERENCE_VALUES", InspectionsBundle .message("inspection.data.flow.turn.off.constant.references.quickfix"), false)); } holder.registerProblem(ref, "Value <code>#ref</code> #loc is always '" + presentableName + "'", fixes); } } private void reportNullableArgumentsPassedToNonAnnotated(DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) { for (PsiElement expr : visitor.problems() .map(NullabilityProblemKind.passingNullableArgumentToNonAnnotatedParameter::asMyProblem).nonNull() .map(NullabilityProblem::getAnchor)) { if (reportedAnchors.contains(expr)) continue; if (expr.getParent() instanceof PsiMethodReferenceExpression) { holder.registerProblem(expr.getParent(), "Method reference argument might be null but passed to non annotated parameter"); continue; } final String text = isNullLiteralExpression(expr) ? "Passing <code>null</code> argument to non annotated parameter" : "Argument <code>#ref</code> #loc might be null but passed to non annotated parameter"; List<LocalQuickFix> fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly()); final PsiElement parent = expr.getParent(); if (parent instanceof PsiExpressionList) { final int idx = ArrayUtilRt.find(((PsiExpressionList)parent).getExpressions(), expr); if (idx > -1) { final PsiElement gParent = parent.getParent(); if (gParent instanceof PsiCallExpression) { final PsiMethod psiMethod = ((PsiCallExpression)gParent).resolveMethod(); if (psiMethod != null && psiMethod.getManager().isInProject(psiMethod) && AnnotationUtil.isAnnotatingApplicable(psiMethod)) { final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); if (idx < parameters.length) { fixes.add(new AddNullableAnnotationFix(parameters[idx])); holder.registerProblem(expr, text, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); reportedAnchors.add(expr); } } } } } } } private void reportCallMayProduceNpe(ProblemsHolder holder, PsiMethodCallExpression callExpression) { PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); List<LocalQuickFix> fixes = createNPEFixes(methodExpression.getQualifierExpression(), callExpression, holder.isOnTheFly()); ContainerUtil.addIfNotNull(fixes, ReplaceWithObjectsEqualsFix.createFix(callExpression, methodExpression)); PsiElement toHighlight = getElementToHighlight(callExpression); holder.registerProblem(toHighlight, InspectionsBundle.message("dataflow.message.npe.method.invocation"), fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } private static void reportCastMayFail(ProblemsHolder holder, TypeCastInstruction instruction) { PsiTypeCastExpression typeCast = instruction.getCastExpression(); PsiExpression operand = typeCast.getOperand(); PsiTypeElement castType = typeCast.getCastType(); assert castType != null; assert operand != null; holder.registerProblem(castType, InspectionsBundle.message("dataflow.message.cce", operand.getText())); } private void handleBranchingInstruction(ProblemsHolder holder, StandardInstructionVisitor visitor, Set<Instruction> trueSet, Set<Instruction> falseSet, HashSet<PsiElement> reportedAnchors, BranchingInstruction instruction) { PsiElement psiAnchor = instruction.getPsiAnchor(); if (instruction instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction)instruction)) { if (visitor.canBeNull((BinopInstruction)instruction)) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.redundant.instanceof"), new RedundantInstanceofFix()); } else { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true); String message = InspectionsBundle.message(isAtRHSOfBooleanAnd(psiAnchor) ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(true)); holder.registerProblem(psiAnchor, message, localQuickFix); } } else if (psiAnchor instanceof PsiSwitchLabelStatement) { if (falseSet.contains(instruction)) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label")); } } else if (psiAnchor != null && !reportedAnchors.contains(psiAnchor) && !isFlagCheck(psiAnchor)) { boolean evaluatesToTrue = trueSet.contains(instruction); final PsiElement parent = psiAnchor.getParent(); if (parent instanceof PsiAssignmentExpression && ((PsiAssignmentExpression)parent).getLExpression() == psiAnchor) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.pointless.assignment.expression", Boolean.toString(evaluatesToTrue)), createConditionalAssignmentFixes(evaluatesToTrue, (PsiAssignmentExpression)parent, holder.isOnTheFly()) ); } else { reportConstantCondition(holder, psiAnchor, evaluatesToTrue); } reportedAnchors.add(psiAnchor); } } private void reportConstantCondition(ProblemsHolder holder, PsiElement psiAnchor, boolean evaluatesToTrue) { if (psiAnchor.getParent() instanceof PsiForeachStatement) { // highlighted for-each iterated value means evaluatesToTrue == "collection is always empty" if (!evaluatesToTrue) { // loop on always non-empty collection -- nothing to report return; } boolean array = psiAnchor instanceof PsiExpression && ((PsiExpression)psiAnchor).getType() instanceof PsiArrayType; holder.registerProblem(psiAnchor, array ? InspectionsBundle.message("dataflow.message.loop.on.empty.array") : InspectionsBundle.message("dataflow.message.loop.on.empty.collection")); } else if (psiAnchor instanceof PsiMethodReferenceExpression) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.constant.method.reference", evaluatesToTrue), createReplaceWithTrivialLambdaFix(evaluatesToTrue)); } else { boolean isAssertion = isAssertionEffectively(psiAnchor, evaluatesToTrue); if (!DONT_REPORT_TRUE_ASSERT_STATEMENTS || !isAssertion) { List<LocalQuickFix> fixes = new ArrayList<>(); ContainerUtil.addIfNotNull(fixes, createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue)); if (isAssertion && holder.isOnTheFly()) { fixes.add(new SetInspectionOptionFix(this, "DONT_REPORT_TRUE_ASSERT_STATEMENTS", InspectionsBundle.message("inspection.data.flow.turn.off.true.asserts.quickfix"), true)); } String message = InspectionsBundle.message(isAtRHSOfBooleanAnd(psiAnchor) ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(evaluatesToTrue)); holder.registerProblem(psiAnchor, message, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } } } protected LocalQuickFix[] createConditionalAssignmentFixes(boolean evaluatesToTrue, PsiAssignmentExpression parent, final boolean onTheFly) { return LocalQuickFix.EMPTY_ARRAY; } private void reportNullableArgument(ProblemsHolder holder, PsiElement expr) { if (expr.getParent() instanceof PsiMethodReferenceExpression) { PsiMethodReferenceExpression methodRef = (PsiMethodReferenceExpression)expr.getParent(); holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.passing.nullable.argument.methodref"), createMethodReferenceNPEFixes(methodRef).toArray(LocalQuickFix.EMPTY_ARRAY)); } else { final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.passing.null.argument") : InspectionsBundle.message("dataflow.message.passing.nullable.argument"); List<LocalQuickFix> fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly()); holder.registerProblem(expr, text, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } } @Nullable private static PsiMethod getScopeMethod(PsiElement block) { PsiElement parent = block.getParent(); if (parent instanceof PsiMethod) return (PsiMethod)parent; if (parent instanceof PsiLambdaExpression) return LambdaUtil.getFunctionalInterfaceMethod(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); return null; } private void reportNullableReturns(DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors, @NotNull PsiElement block) { final PsiMethod method = getScopeMethod(block); if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return; PsiAnnotation notNullAnno = NullableNotNullManager.getInstance(method.getProject()).getNotNullAnnotation(method, true); if (notNullAnno == null && (!SUGGEST_NULLABLE_ANNOTATIONS || block.getParent() instanceof PsiLambdaExpression)) return; PsiType returnType = method.getReturnType(); // no warnings in void lambdas, where the expression is not returned anyway if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && PsiType.VOID.equals(returnType)) return; // no warnings for Void methods, where only null can be possibly returned if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return; for (NullabilityProblem<PsiExpression> problem : visitor.problems().map(NullabilityProblemKind.nullableReturn::asMyProblem).nonNull()) { final PsiExpression expr = problem.getAnchor(); if (!reportedAnchors.add(expr)) continue; if (notNullAnno != null) { String presentable = NullableStuffInspectionBase.getPresentableAnnoName(notNullAnno); final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.return.null.from.notnull", presentable) : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull", presentable); holder.registerProblem(expr, text); } else if (AnnotationUtil.isAnnotatingApplicable(expr)) { final NullableNotNullManager manager = NullableNotNullManager.getInstance(expr.getProject()); final String defaultNullable = manager.getDefaultNullable(); final String presentableNullable = StringUtil.getShortName(defaultNullable); final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.return.null.from.notnullable", presentableNullable) : InspectionsBundle.message("dataflow.message.return.nullable.from.notnullable", presentableNullable); final LocalQuickFix[] fixes = PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class) instanceof PsiLambdaExpression ? LocalQuickFix.EMPTY_ARRAY : new LocalQuickFix[]{ new AnnotateMethodFix(defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls()))}; holder.registerProblem(expr, text, fixes); } } } private static boolean isAssertionEffectively(PsiElement psiAnchor, boolean evaluatesToTrue) { PsiElement parent = PsiUtil.skipParenthesizedExprUp(psiAnchor.getParent()); if (parent instanceof PsiAssertStatement) { return evaluatesToTrue; } if (parent instanceof PsiIfStatement && psiAnchor == ((PsiIfStatement)parent).getCondition()) { PsiStatement thenBranch = ControlFlowUtils.stripBraces(((PsiIfStatement)parent).getThenBranch()); if (thenBranch instanceof PsiThrowStatement) { return !evaluatesToTrue; } } return false; } private static boolean isAtRHSOfBooleanAnd(PsiElement expr) { PsiElement cur = expr; while (cur != null && !(cur instanceof PsiMember)) { PsiElement parent = cur.getParent(); if (parent instanceof PsiBinaryExpression && cur == ((PsiBinaryExpression)parent).getROperand()) { return true; } cur = parent; } return false; } private static boolean isFlagCheck(PsiElement element) { PsiElement scope = PsiTreeUtil.getParentOfType(element, PsiStatement.class, PsiVariable.class); PsiExpression topExpression = scope instanceof PsiIfStatement ? ((PsiIfStatement)scope).getCondition() : scope instanceof PsiVariable ? ((PsiVariable)scope).getInitializer() : null; if (!PsiTreeUtil.isAncestor(topExpression, element, false)) return false; return StreamEx.<PsiElement>ofTree(topExpression, e -> StreamEx.of(e.getChildren())) .anyMatch(DataFlowInspectionBase::isCompileTimeFlagCheck); } private static boolean isCompileTimeFlagCheck(PsiElement element) { if(element instanceof PsiBinaryExpression) { PsiBinaryExpression binOp = (PsiBinaryExpression)element; if(ComparisonUtils.isComparisonOperation(binOp.getOperationTokenType())) { PsiExpression comparedWith = null; if(ExpressionUtils.isLiteral(binOp.getROperand())) { comparedWith = binOp.getLOperand(); } else if(ExpressionUtils.isLiteral(binOp.getLOperand())) { comparedWith = binOp.getROperand(); } comparedWith = PsiUtil.skipParenthesizedExprDown(comparedWith); if (isConstantOfType(comparedWith, PsiType.INT, PsiType.LONG)) { // like "if(DEBUG_LEVEL > 2)" return true; } if(comparedWith instanceof PsiBinaryExpression) { PsiBinaryExpression subOp = (PsiBinaryExpression)comparedWith; if(subOp.getOperationTokenType().equals(JavaTokenType.AND)) { PsiExpression left = PsiUtil.skipParenthesizedExprDown(subOp.getLOperand()); PsiExpression right = PsiUtil.skipParenthesizedExprDown(subOp.getROperand()); if(isConstantOfType(left, PsiType.INT, PsiType.LONG) || isConstantOfType(right, PsiType.INT, PsiType.LONG)) { // like "if((FLAGS & SOME_FLAG) != 0)" return true; } } } } } // like "if(DEBUG)" return isConstantOfType(element, PsiType.BOOLEAN); } private static boolean isConstantOfType(PsiElement element, PsiPrimitiveType... types) { PsiElement resolved = element instanceof PsiReferenceExpression ? ((PsiReferenceExpression)element).resolve() : null; if (!(resolved instanceof PsiField)) return false; PsiVariable field = (PsiVariable)resolved; return field.hasModifierProperty(PsiModifier.STATIC) && PsiUtil.isCompileTimeConstant(field) && ArrayUtil.contains(field.getType(), types); } private static boolean isNullLiteralExpression(PsiElement expr) { return expr instanceof PsiExpression && ExpressionUtils.isNullLiteral((PsiExpression)expr); } @Nullable private LocalQuickFix createSimplifyBooleanExpressionFix(PsiElement element, final boolean value) { LocalQuickFixOnPsiElement fix = createSimplifyBooleanFix(element, value); if (fix == null) return null; final String text = fix.getText(); return new LocalQuickFix() { @Override @NotNull public String getName() { return text; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement == null) return; final LocalQuickFixOnPsiElement fix = createSimplifyBooleanFix(psiElement, value); if (fix == null) return; try { LOG.assertTrue(psiElement.isValid()); fix.applyFix(); } catch (IncorrectOperationException e) { LOG.error(e); } } @Override @NotNull public String getFamilyName() { return InspectionsBundle.message("inspection.data.flow.simplify.boolean.expression.quickfix"); } }; } @NotNull protected static LocalQuickFix createSimplifyToAssignmentFix() { return new SimplifyToAssignmentFix(); } protected LocalQuickFixOnPsiElement createSimplifyBooleanFix(PsiElement element, boolean value) { return null; } @Override @NotNull public String getDisplayName() { return InspectionsBundle.message("inspection.data.flow.display.name"); } @Override @NotNull public String getGroupDisplayName() { return GroupNames.BUGS_GROUP_NAME; } @Override @NotNull public String getShortName() { return SHORT_NAME; } }
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInspection.dataFlow; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.NullableNotNullManager; import com.intellij.codeInsight.PsiEquivalenceUtil; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.intention.impl.AddNotNullAnnotationFix; import com.intellij.codeInsight.intention.impl.AddNullableAnnotationFix; import com.intellij.codeInspection.*; import com.intellij.codeInspection.dataFlow.NullabilityProblemKind.NullabilityProblem; import com.intellij.codeInspection.dataFlow.fix.RedundantInstanceofFix; import com.intellij.codeInspection.dataFlow.fix.ReplaceWithConstantValueFix; import com.intellij.codeInspection.dataFlow.fix.ReplaceWithObjectsEqualsFix; import com.intellij.codeInspection.dataFlow.fix.SimplifyToAssignmentFix; import com.intellij.codeInspection.dataFlow.instructions.*; import com.intellij.codeInspection.dataFlow.value.DfaConstValue; import com.intellij.codeInspection.dataFlow.value.DfaValue; import com.intellij.codeInspection.nullable.NullableStuffInspectionBase; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiTypesUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.ArrayUtilRt; import com.intellij.util.IncorrectOperationException; import com.intellij.util.ThreeState; import com.intellij.util.containers.ContainerUtil; import com.siyeh.ig.psiutils.ComparisonUtils; import com.siyeh.ig.psiutils.ControlFlowUtils; import com.siyeh.ig.psiutils.ExpressionUtils; import com.siyeh.ig.psiutils.TestUtils; import one.util.streamex.StreamEx; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.*; @SuppressWarnings("ConditionalExpressionWithIdenticalBranches") public class DataFlowInspectionBase extends AbstractBaseJavaLocalInspectionTool { static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.DataFlowInspection"); @NonNls private static final String SHORT_NAME = "ConstantConditions"; public boolean SUGGEST_NULLABLE_ANNOTATIONS; public boolean DONT_REPORT_TRUE_ASSERT_STATEMENTS; public boolean TREAT_UNKNOWN_MEMBERS_AS_NULLABLE; public boolean IGNORE_ASSERT_STATEMENTS; public boolean REPORT_CONSTANT_REFERENCE_VALUES = true; public boolean REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER = true; public boolean REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL = true; public boolean REPORT_UNCHECKED_OPTIONALS = true; @Override public JComponent createOptionsPanel() { throw new RuntimeException("no UI in headless mode"); } @Override public void writeSettings(@NotNull Element node) throws WriteExternalException { node.addContent(new Element("option").setAttribute("name", "SUGGEST_NULLABLE_ANNOTATIONS").setAttribute("value", String.valueOf(SUGGEST_NULLABLE_ANNOTATIONS))); node.addContent(new Element("option").setAttribute("name", "DONT_REPORT_TRUE_ASSERT_STATEMENTS").setAttribute("value", String.valueOf(DONT_REPORT_TRUE_ASSERT_STATEMENTS))); if (IGNORE_ASSERT_STATEMENTS) { node.addContent(new Element("option").setAttribute("name", "IGNORE_ASSERT_STATEMENTS").setAttribute("value", "true")); } if (!REPORT_CONSTANT_REFERENCE_VALUES) { node.addContent(new Element("option").setAttribute("name", "REPORT_CONSTANT_REFERENCE_VALUES").setAttribute("value", "false")); } if (TREAT_UNKNOWN_MEMBERS_AS_NULLABLE) { node.addContent(new Element("option").setAttribute("name", "TREAT_UNKNOWN_MEMBERS_AS_NULLABLE").setAttribute("value", "true")); } if (!REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER) { node.addContent(new Element("option").setAttribute("name", "REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER").setAttribute("value", "false")); } if (!REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL) { node.addContent(new Element("option").setAttribute("name", "REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL").setAttribute("value", "false")); } if (!REPORT_UNCHECKED_OPTIONALS) { node.addContent(new Element("option").setAttribute("name", "REPORT_UNCHECKED_OPTIONALS").setAttribute("value", "false")); } } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { return new JavaElementVisitor() { @Override public void visitClass(PsiClass aClass) { if (aClass instanceof PsiTypeParameter) return; analyzeCodeBlock(aClass, holder); } @Override public void visitMethod(PsiMethod method) { analyzeCodeBlock(method.getBody(), holder); analyzeNullLiteralMethodArguments(method, holder); } @Override public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) { super.visitMethodReferenceExpression(expression); final PsiElement resolve = expression.resolve(); if (resolve instanceof PsiMethod) { final PsiType methodReturnType = ((PsiMethod)resolve).getReturnType(); if (TypeConversionUtil.isPrimitiveWrapper(methodReturnType) && NullableNotNullManager.isNullable((PsiMethod)resolve)) { final PsiType returnType = LambdaUtil.getFunctionalInterfaceReturnType(expression); if (TypeConversionUtil.isPrimitiveAndNotNull(returnType)) { holder.registerProblem(expression, InspectionsBundle.message("dataflow.message.unboxing.method.reference")); } } } } @Override public void visitIfStatement(PsiIfStatement statement) { PsiExpression condition = PsiUtil.skipParenthesizedExprDown(statement.getCondition()); if (BranchingInstruction.isBoolConst(condition)) { LocalQuickFix fix = createSimplifyBooleanExpressionFix(condition, condition.textMatches(PsiKeyword.TRUE)); holder.registerProblem(condition, "Condition is always " + condition.getText(), fix); } } @Override public void visitWhileStatement(PsiWhileStatement statement) { checkLoopCondition(statement.getCondition()); } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { checkLoopCondition(statement.getCondition()); } @Override public void visitForStatement(PsiForStatement statement) { checkLoopCondition(statement.getCondition()); } private void checkLoopCondition(PsiExpression condition) { condition = PsiUtil.skipParenthesizedExprDown(condition); if (condition != null && condition.textMatches(PsiKeyword.FALSE)) { holder.registerProblem(condition, "Condition is always false", createSimplifyBooleanExpressionFix(condition, false)); } } }; } protected LocalQuickFix createNavigateToNullParameterUsagesFix(PsiParameter parameter) { return null; } private void analyzeNullLiteralMethodArguments(PsiMethod method, ProblemsHolder holder) { if (REPORT_NULLS_PASSED_TO_NOT_NULL_PARAMETER && holder.isOnTheFly()) { for (PsiParameter parameter : NullParameterConstraintChecker.checkMethodParameters(method)) { PsiIdentifier name = parameter.getNameIdentifier(); if (name != null) { holder.registerProblem(name, InspectionsBundle.message("dataflow.method.fails.with.null.argument"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, createNavigateToNullParameterUsagesFix(parameter)); } } } } private void analyzeCodeBlock(@Nullable final PsiElement scope, ProblemsHolder holder) { if (scope == null) return; PsiClass containingClass = PsiTreeUtil.getNonStrictParentOfType(scope, PsiClass.class); if (containingClass != null && PsiUtil.isLocalOrAnonymousClass(containingClass) && !(containingClass instanceof PsiEnumConstantInitializer)) return; final StandardDataFlowRunner dfaRunner = new StandardDataFlowRunner(TREAT_UNKNOWN_MEMBERS_AS_NULLABLE, !DfaUtil.isInsideConstructorOrInitializer(scope)); analyzeDfaWithNestedClosures(scope, holder, dfaRunner, Collections.singletonList(dfaRunner.createMemoryState())); } private void analyzeDfaWithNestedClosures(PsiElement scope, ProblemsHolder holder, StandardDataFlowRunner dfaRunner, Collection<? extends DfaMemoryState> initialStates) { final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(); final RunnerResult rc = dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates); if (rc == RunnerResult.OK) { createDescription(dfaRunner, holder, visitor, scope); dfaRunner.forNestedClosures((closure, states) -> analyzeDfaWithNestedClosures(closure, holder, dfaRunner, states)); } else if (rc == RunnerResult.TOO_COMPLEX) { PsiIdentifier name = null; String message = null; if(scope.getParent() instanceof PsiMethod) { name = ((PsiMethod)scope.getParent()).getNameIdentifier(); message = InspectionsBundle.message("dataflow.too.complex"); } else if(scope instanceof PsiClass) { name = ((PsiClass)scope).getNameIdentifier(); message = InspectionsBundle.message("dataflow.too.complex.class"); } if (name != null) { // Might be null for synthetic methods like JSP page. holder.registerProblem(name, message, ProblemHighlightType.WEAK_WARNING); } } } @NotNull protected List<LocalQuickFix> createNPEFixes(PsiExpression qualifier, PsiExpression expression, boolean onTheFly) { return Collections.emptyList(); } protected List<LocalQuickFix> createMethodReferenceNPEFixes(PsiMethodReferenceExpression methodRef) { return Collections.emptyList(); } @Nullable protected LocalQuickFix createIntroduceVariableFix(PsiExpression expression) { return null; } protected LocalQuickFix createRemoveAssignmentFix(PsiAssignmentExpression assignment) { return null; } protected LocalQuickFix createReplaceWithTrivialLambdaFix(Object value) { return null; } private void createDescription(StandardDataFlowRunner runner, ProblemsHolder holder, final DataFlowInstructionVisitor visitor, PsiElement scope) { Pair<Set<Instruction>, Set<Instruction>> constConditions = runner.getConstConditionalExpressions(); Set<Instruction> trueSet = constConditions.getFirst(); Set<Instruction> falseSet = constConditions.getSecond(); ArrayList<Instruction> allProblems = new ArrayList<>(); allProblems.addAll(trueSet); allProblems.addAll(falseSet); allProblems.addAll(visitor.getClassCastExceptionInstructions()); allProblems.addAll(ContainerUtil.filter(runner.getInstructions(), instruction1 -> instruction1 instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction)instruction1))); HashSet<PsiElement> reportedAnchors = new HashSet<>(); for (Instruction instruction : allProblems) { if (instruction instanceof TypeCastInstruction && reportedAnchors.add(((TypeCastInstruction)instruction).getCastExpression().getCastType())) { reportCastMayFail(holder, (TypeCastInstruction)instruction); } else if (instruction instanceof BranchingInstruction) { handleBranchingInstruction(holder, visitor, trueSet, falseSet, reportedAnchors, (BranchingInstruction)instruction); } } reportAlwaysFailingCalls(holder, visitor, reportedAnchors); reportConstantPushes(runner, holder, reportedAnchors); reportNullabilityProblems(holder, visitor, reportedAnchors); reportNullableReturns(visitor, holder, reportedAnchors, scope); if (SUGGEST_NULLABLE_ANNOTATIONS) { reportNullableArgumentsPassedToNonAnnotated(visitor, holder, reportedAnchors); } reportOptionalOfNullableImprovements(holder, reportedAnchors, visitor.getOfNullableCalls()); reportUncheckedOptionalGet(holder, visitor.getOptionalCalls(), visitor.getOptionalQualifiers()); visitor.getBooleanCalls().forEach((call, state) -> { if (state != ThreeState.UNSURE && reportedAnchors.add(call)) { reportConstantCondition(holder, call, state.toBoolean()); } }); reportMethodReferenceProblems(holder, visitor); reportArrayAccessProblems(holder, visitor); reportArrayStoreProblems(holder, visitor); if (REPORT_CONSTANT_REFERENCE_VALUES) { reportConstantReferenceValues(holder, visitor, reportedAnchors); } if (REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL && visitor.isAlwaysReturnsNotNull(runner.getInstructions())) { reportAlwaysReturnsNotNull(holder, scope); } reportMutabilityViolations(holder, reportedAnchors, visitor.getMutabilityViolations(true), InspectionsBundle.message("dataflow.message.immutable.modified")); reportMutabilityViolations(holder, reportedAnchors, visitor.getMutabilityViolations(false), InspectionsBundle.message("dataflow.message.immutable.passed")); reportDuplicateAssignments(holder, reportedAnchors, visitor); } private void reportDuplicateAssignments(ProblemsHolder holder, HashSet<PsiElement> reportedAnchors, DataFlowInstructionVisitor visitor) { visitor.sameValueAssignments().forEach(expr -> { if(!reportedAnchors.add(expr)) return; PsiAssignmentExpression assignment = PsiTreeUtil.getParentOfType(expr, PsiAssignmentExpression.class); PsiElement context = PsiTreeUtil.getParentOfType(expr, PsiForStatement.class, PsiClassInitializer.class); if (context instanceof PsiForStatement && PsiTreeUtil.isAncestor(((PsiForStatement)context).getInitialization(), expr, true)) { return; } if (context instanceof PsiClassInitializer && expr instanceof PsiReferenceExpression) { if (assignment != null) { Object constValue = ExpressionUtils.computeConstantExpression(assignment.getRExpression()); if (constValue == PsiTypesUtil.getDefaultValue(expr.getType())) { PsiElement target = ((PsiReferenceExpression)expr).resolve(); if (target instanceof PsiField && ((PsiField)target).getContainingClass() == ((PsiClassInitializer)context).getContainingClass()) { return; } } } } holder.registerProblem(expr, InspectionsBundle.message("dataflow.message.redundant.assignment"), createRemoveAssignmentFix(assignment)); }); } private static void reportMutabilityViolations(ProblemsHolder holder, Set<PsiElement> reportedAnchors, Set<PsiElement> violations, String message) { for (PsiElement violation : violations) { if (reportedAnchors.add(violation)) { holder.registerProblem(violation, message); } } } private void reportNullabilityProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor, HashSet<PsiElement> reportedAnchors) { visitor.problems().forEach(problem -> { if (NullabilityProblemKind.passingNullableArgumentToNonAnnotatedParameter.isMyProblem(problem) || NullabilityProblemKind.nullableReturn.isMyProblem(problem)) { // these two kinds are still reported separately return; } if (!reportedAnchors.add(problem.getAnchor())) return; NullabilityProblemKind.innerClassNPE.ifMyProblem(problem, newExpression -> { List<LocalQuickFix> fixes = createNPEFixes(newExpression.getQualifier(), newExpression, holder.isOnTheFly()); holder.registerProblem(getElementToHighlight(newExpression), problem.getMessage(), fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); }); NullabilityProblemKind.callMethodRefNPE.ifMyProblem(problem, methodRef -> holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.npe.methodref.invocation"), createMethodReferenceNPEFixes(methodRef).toArray(LocalQuickFix.EMPTY_ARRAY))); NullabilityProblemKind.callNPE.ifMyProblem(problem, call -> reportCallMayProduceNpe(holder, call)); NullabilityProblemKind.passingNullableToNotNullParameter.ifMyProblem(problem, expr -> reportNullableArgument(holder, expr)); NullabilityProblemKind.arrayAccessNPE.ifMyProblem(problem, expression -> { LocalQuickFix[] fix = createNPEFixes(expression.getArrayExpression(), expression, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY); holder.registerProblem(expression, problem.getMessage(), fix); }); NullabilityProblemKind.fieldAccessNPE.ifMyProblem(problem, element -> { PsiElement parent = element.getParent(); PsiExpression fieldAccess = parent instanceof PsiReferenceExpression ? (PsiExpression)parent : element; LocalQuickFix[] fix = createNPEFixes(element, fieldAccess, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY); holder.registerProblem(element, problem.getMessage(), fix); }); NullabilityProblemKind.unboxingNullable.ifMyProblem(problem, element -> holder.registerProblem(element, problem.getMessage())); NullabilityProblemKind.nullableFunctionReturn.ifMyProblem(problem, expr -> holder.registerProblem(expr, problem.getMessage())); NullabilityProblemKind.assigningToNotNull.ifMyProblem(problem, expr -> reportNullabilityProblem(holder, problem, expr)); NullabilityProblemKind.storingToNotNullArray.ifMyProblem(problem, expr -> reportNullabilityProblem(holder, problem, expr)); }); } private void reportNullabilityProblem(ProblemsHolder holder, NullabilityProblem<?> problem, PsiExpression expr) { holder.registerProblem(expr, problem.getMessage(), createNPEFixes(expr, expr, holder.isOnTheFly()).toArray(LocalQuickFix.EMPTY_ARRAY)); } private static void reportArrayAccessProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.outOfBoundsArrayAccesses().forEach(access -> { PsiExpression indexExpression = access.getIndexExpression(); if (indexExpression != null) { holder.registerProblem(indexExpression, InspectionsBundle.message("dataflow.message.array.index.out.of.bounds")); } }); } private static void reportArrayStoreProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.getArrayStoreProblems().forEach( (assignment, types) -> holder.registerProblem(assignment.getOperationSign(), InspectionsBundle .message("dataflow.message.arraystore", types.getFirst().getCanonicalText(), types.getSecond().getCanonicalText()))); } private void reportMethodReferenceProblems(ProblemsHolder holder, DataFlowInstructionVisitor visitor) { visitor.getMethodReferenceResults().forEach((methodRef, dfaValue) -> { if (dfaValue instanceof DfaConstValue) { Object value = ((DfaConstValue)dfaValue).getValue(); if(value instanceof Boolean) { holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.constant.method.reference", value), createReplaceWithTrivialLambdaFix(value)); } } }); } private void reportUncheckedOptionalGet(ProblemsHolder holder, Map<PsiMethodCallExpression, ThreeState> calls, List<PsiExpression> qualifiers) { if (!REPORT_UNCHECKED_OPTIONALS) return; for (Map.Entry<PsiMethodCallExpression, ThreeState> entry : calls.entrySet()) { ThreeState state = entry.getValue(); if (state != ThreeState.UNSURE) continue; PsiMethodCallExpression call = entry.getKey(); PsiMethod method = call.resolveMethod(); if (method == null) continue; PsiClass optionalClass = method.getContainingClass(); if (optionalClass == null) continue; PsiExpression qualifier = PsiUtil.skipParenthesizedExprDown(call.getMethodExpression().getQualifierExpression()); if (qualifier instanceof PsiMethodCallExpression && qualifiers.stream().anyMatch(q -> PsiEquivalenceUtil.areElementsEquivalent(q, qualifier))) { // Conservatively do not report methodCall().get() cases if methodCall().isPresent() was found in the same method // without deep correspondence analysis continue; } LocalQuickFix fix = holder.isOnTheFly() ? new SetInspectionOptionFix(this, "REPORT_UNCHECKED_OPTIONALS", InspectionsBundle .message("inspection.data.flow.turn.off.unchecked.optional.get.quickfix"), false) : null; holder.registerProblem(getElementToHighlight(call), InspectionsBundle.message("dataflow.message.optional.get.without.is.present", optionalClass.getName()), fix); } } private void reportAlwaysReturnsNotNull(ProblemsHolder holder, PsiElement scope) { if (!(scope.getParent() instanceof PsiMethod)) return; PsiMethod method = (PsiMethod)scope.getParent(); if (PsiUtil.canBeOverridden(method)) return; PsiAnnotation nullableAnno = NullableNotNullManager.getInstance(scope.getProject()).getNullableAnnotation(method, false); if (nullableAnno == null || !nullableAnno.isPhysical()) return; PsiJavaCodeReferenceElement annoName = nullableAnno.getNameReferenceElement(); assert annoName != null; String msg = "@" + NullableStuffInspectionBase.getPresentableAnnoName(nullableAnno) + " method '" + method.getName() + "' always returns a non-null value"; LocalQuickFix[] fixes = {new AddNotNullAnnotationFix(method)}; if (holder.isOnTheFly()) { fixes = ArrayUtil.append(fixes, new SetInspectionOptionFix(this, "REPORT_NULLABLE_METHODS_RETURNING_NOT_NULL", InspectionsBundle .message( "inspection.data.flow.turn.off.nullable.returning.notnull.quickfix"), false)); } holder.registerProblem(annoName, msg, fixes); } private static void reportAlwaysFailingCalls(ProblemsHolder holder, DataFlowInstructionVisitor visitor, HashSet<PsiElement> reportedAnchors) { visitor.getAlwaysFailingCalls().forEach((call, contracts) -> { if (TestUtils.isExceptionExpected(call)) return; PsiMethod method = call.resolveMethod(); if (method != null && reportedAnchors.add(call)) { holder.registerProblem(getElementToHighlight(call), getContractMessage(contracts)); } }); } @NotNull private static String getContractMessage(List<MethodContract> contracts) { if (contracts.stream().allMatch(mc -> mc.getConditions().stream().allMatch(cv -> cv.isBoundCheckingCondition()))) { return InspectionsBundle.message("dataflow.message.contract.fail.index"); } return InspectionsBundle.message("dataflow.message.contract.fail"); } @NotNull private static PsiElement getElementToHighlight(@NotNull PsiCall call) { PsiJavaCodeReferenceElement ref; if (call instanceof PsiNewExpression) { ref = ((PsiNewExpression)call).getClassReference(); } else if (call instanceof PsiMethodCallExpression) { ref = ((PsiMethodCallExpression)call).getMethodExpression(); } else { return call; } if (ref != null) { PsiElement name = ref.getReferenceNameElement(); return name != null ? name : ref; } return call; } private void reportConstantPushes(StandardDataFlowRunner runner, ProblemsHolder holder, Set<PsiElement> reportedAnchors) { for (Instruction instruction : runner.getInstructions()) { if (instruction instanceof PushInstruction) { PsiExpression place = ((PushInstruction)instruction).getPlace(); DfaValue value = ((PushInstruction)instruction).getValue(); Object constant = value instanceof DfaConstValue ? ((DfaConstValue)value).getValue() : null; if (place instanceof PsiPolyadicExpression && constant instanceof Boolean && !isFlagCheck(place) && reportedAnchors.add(place)) { reportConstantCondition(holder, place, (Boolean)constant); } } } } private static void reportOptionalOfNullableImprovements(ProblemsHolder holder, Set<PsiElement> reportedAnchors, Map<MethodCallInstruction, ThreeState> nullArgs) { nullArgs.forEach((call, nullArg) -> { PsiElement arg = call.getArgumentAnchor(0); if (reportedAnchors.add(arg)) { switch (nullArg) { case YES: holder.registerProblem(arg, "Passing <code>null</code> argument to <code>Optional</code>", DfaOptionalSupport.createReplaceOptionalOfNullableWithEmptyFix(arg)); break; case NO: holder.registerProblem(arg, "Passing a non-null argument to <code>Optional</code>", DfaOptionalSupport.createReplaceOptionalOfNullableWithOfFix(arg)); break; default: } } }); } private void reportConstantReferenceValues(ProblemsHolder holder, DataFlowInstructionVisitor visitor, Set<PsiElement> reportedAnchors) { for (Pair<PsiReferenceExpression, DfaConstValue> pair : visitor.getConstantReferenceValues()) { PsiReferenceExpression ref = pair.first; if (ref.getParent() instanceof PsiReferenceExpression || !reportedAnchors.add(ref)) { continue; } final Object value = pair.second.getValue(); PsiVariable constant = pair.second.getConstant(); final String presentableName = constant != null ? constant.getName() : String.valueOf(value); final String exprText = String.valueOf(value); if (presentableName == null || exprText == null) { continue; } LocalQuickFix[] fixes = {new ReplaceWithConstantValueFix(presentableName, exprText)}; if (holder.isOnTheFly()) { fixes = ArrayUtil.append(fixes, new SetInspectionOptionFix(this, "REPORT_CONSTANT_REFERENCE_VALUES", InspectionsBundle .message("inspection.data.flow.turn.off.constant.references.quickfix"), false)); } holder.registerProblem(ref, "Value <code>#ref</code> #loc is always '" + presentableName + "'", fixes); } } private void reportNullableArgumentsPassedToNonAnnotated(DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) { for (PsiElement expr : visitor.problems() .map(NullabilityProblemKind.passingNullableArgumentToNonAnnotatedParameter::asMyProblem).nonNull() .map(NullabilityProblem::getAnchor)) { if (reportedAnchors.contains(expr)) continue; if (expr.getParent() instanceof PsiMethodReferenceExpression) { holder.registerProblem(expr.getParent(), "Method reference argument might be null but passed to non annotated parameter"); continue; } final String text = isNullLiteralExpression(expr) ? "Passing <code>null</code> argument to non annotated parameter" : "Argument <code>#ref</code> #loc might be null but passed to non annotated parameter"; List<LocalQuickFix> fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly()); final PsiElement parent = expr.getParent(); if (parent instanceof PsiExpressionList) { final int idx = ArrayUtilRt.find(((PsiExpressionList)parent).getExpressions(), expr); if (idx > -1) { final PsiElement gParent = parent.getParent(); if (gParent instanceof PsiCallExpression) { final PsiMethod psiMethod = ((PsiCallExpression)gParent).resolveMethod(); if (psiMethod != null && psiMethod.getManager().isInProject(psiMethod) && AnnotationUtil.isAnnotatingApplicable(psiMethod)) { final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); if (idx < parameters.length) { fixes.add(new AddNullableAnnotationFix(parameters[idx])); holder.registerProblem(expr, text, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); reportedAnchors.add(expr); } } } } } } } private void reportCallMayProduceNpe(ProblemsHolder holder, PsiMethodCallExpression callExpression) { PsiReferenceExpression methodExpression = callExpression.getMethodExpression(); List<LocalQuickFix> fixes = createNPEFixes(methodExpression.getQualifierExpression(), callExpression, holder.isOnTheFly()); ContainerUtil.addIfNotNull(fixes, ReplaceWithObjectsEqualsFix.createFix(callExpression, methodExpression)); PsiElement toHighlight = getElementToHighlight(callExpression); holder.registerProblem(toHighlight, InspectionsBundle.message("dataflow.message.npe.method.invocation"), fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } private static void reportCastMayFail(ProblemsHolder holder, TypeCastInstruction instruction) { PsiTypeCastExpression typeCast = instruction.getCastExpression(); PsiExpression operand = typeCast.getOperand(); PsiTypeElement castType = typeCast.getCastType(); assert castType != null; assert operand != null; holder.registerProblem(castType, InspectionsBundle.message("dataflow.message.cce", operand.getText())); } private void handleBranchingInstruction(ProblemsHolder holder, StandardInstructionVisitor visitor, Set<Instruction> trueSet, Set<Instruction> falseSet, HashSet<PsiElement> reportedAnchors, BranchingInstruction instruction) { PsiElement psiAnchor = instruction.getPsiAnchor(); if (instruction instanceof InstanceofInstruction && visitor.isInstanceofRedundant((InstanceofInstruction)instruction)) { if (visitor.canBeNull((BinopInstruction)instruction)) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.redundant.instanceof"), new RedundantInstanceofFix()); } else { final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true); String message = InspectionsBundle.message(isAtRHSOfBooleanAnd(psiAnchor) ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(true)); holder.registerProblem(psiAnchor, message, localQuickFix); } } else if (psiAnchor instanceof PsiSwitchLabelStatement) { if (falseSet.contains(instruction)) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label")); } } else if (psiAnchor != null && !reportedAnchors.contains(psiAnchor) && !isFlagCheck(psiAnchor)) { boolean evaluatesToTrue = trueSet.contains(instruction); final PsiElement parent = psiAnchor.getParent(); if (parent instanceof PsiAssignmentExpression && ((PsiAssignmentExpression)parent).getLExpression() == psiAnchor) { holder.registerProblem( psiAnchor, InspectionsBundle.message("dataflow.message.pointless.assignment.expression", Boolean.toString(evaluatesToTrue)), createConditionalAssignmentFixes(evaluatesToTrue, (PsiAssignmentExpression)parent, holder.isOnTheFly()) ); } else { reportConstantCondition(holder, psiAnchor, evaluatesToTrue); } reportedAnchors.add(psiAnchor); } } private void reportConstantCondition(ProblemsHolder holder, PsiElement psiAnchor, boolean evaluatesToTrue) { if (psiAnchor.getParent() instanceof PsiForeachStatement) { // highlighted for-each iterated value means evaluatesToTrue == "collection is always empty" if (!evaluatesToTrue) { // loop on always non-empty collection -- nothing to report return; } boolean array = psiAnchor instanceof PsiExpression && ((PsiExpression)psiAnchor).getType() instanceof PsiArrayType; holder.registerProblem(psiAnchor, array ? InspectionsBundle.message("dataflow.message.loop.on.empty.array") : InspectionsBundle.message("dataflow.message.loop.on.empty.collection")); } else if (psiAnchor instanceof PsiMethodReferenceExpression) { holder.registerProblem(psiAnchor, InspectionsBundle.message("dataflow.message.constant.method.reference", evaluatesToTrue), createReplaceWithTrivialLambdaFix(evaluatesToTrue)); } else { boolean isAssertion = isAssertionEffectively(psiAnchor, evaluatesToTrue); if (!DONT_REPORT_TRUE_ASSERT_STATEMENTS || !isAssertion) { List<LocalQuickFix> fixes = new ArrayList<>(); ContainerUtil.addIfNotNull(fixes, createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue)); if (isAssertion && holder.isOnTheFly()) { fixes.add(new SetInspectionOptionFix(this, "DONT_REPORT_TRUE_ASSERT_STATEMENTS", InspectionsBundle.message("inspection.data.flow.turn.off.true.asserts.quickfix"), true)); } String message = InspectionsBundle.message(isAtRHSOfBooleanAnd(psiAnchor) ? "dataflow.message.constant.condition.when.reached" : "dataflow.message.constant.condition", Boolean.toString(evaluatesToTrue)); holder.registerProblem(psiAnchor, message, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } } } protected LocalQuickFix[] createConditionalAssignmentFixes(boolean evaluatesToTrue, PsiAssignmentExpression parent, final boolean onTheFly) { return LocalQuickFix.EMPTY_ARRAY; } private void reportNullableArgument(ProblemsHolder holder, PsiElement expr) { if (expr.getParent() instanceof PsiMethodReferenceExpression) { PsiMethodReferenceExpression methodRef = (PsiMethodReferenceExpression)expr.getParent(); holder.registerProblem(methodRef, InspectionsBundle.message("dataflow.message.passing.nullable.argument.methodref"), createMethodReferenceNPEFixes(methodRef).toArray(LocalQuickFix.EMPTY_ARRAY)); } else { final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.passing.null.argument") : InspectionsBundle.message("dataflow.message.passing.nullable.argument"); List<LocalQuickFix> fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly()); holder.registerProblem(expr, text, fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } } @Nullable private static PsiMethod getScopeMethod(PsiElement block) { PsiElement parent = block.getParent(); if (parent instanceof PsiMethod) return (PsiMethod)parent; if (parent instanceof PsiLambdaExpression) return LambdaUtil.getFunctionalInterfaceMethod(((PsiLambdaExpression)parent).getFunctionalInterfaceType()); return null; } private void reportNullableReturns(DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors, @NotNull PsiElement block) { final PsiMethod method = getScopeMethod(block); if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return; PsiAnnotation notNullAnno = NullableNotNullManager.getInstance(method.getProject()).getNotNullAnnotation(method, true); if (notNullAnno == null && (!SUGGEST_NULLABLE_ANNOTATIONS || block.getParent() instanceof PsiLambdaExpression)) return; PsiType returnType = method.getReturnType(); // no warnings in void lambdas, where the expression is not returned anyway if (block instanceof PsiExpression && block.getParent() instanceof PsiLambdaExpression && PsiType.VOID.equals(returnType)) return; // no warnings for Void methods, where only null can be possibly returned if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return; for (NullabilityProblem<PsiExpression> problem : visitor.problems().map(NullabilityProblemKind.nullableReturn::asMyProblem).nonNull()) { final PsiExpression expr = problem.getAnchor(); if (!reportedAnchors.add(expr)) continue; if (notNullAnno != null) { String presentable = NullableStuffInspectionBase.getPresentableAnnoName(notNullAnno); final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.return.null.from.notnull", presentable) : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull", presentable); holder.registerProblem(expr, text); } else if (AnnotationUtil.isAnnotatingApplicable(expr)) { final NullableNotNullManager manager = NullableNotNullManager.getInstance(expr.getProject()); final String defaultNullable = manager.getDefaultNullable(); final String presentableNullable = StringUtil.getShortName(defaultNullable); final String text = isNullLiteralExpression(expr) ? InspectionsBundle.message("dataflow.message.return.null.from.notnullable", presentableNullable) : InspectionsBundle.message("dataflow.message.return.nullable.from.notnullable", presentableNullable); final LocalQuickFix[] fixes = PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class) instanceof PsiLambdaExpression ? LocalQuickFix.EMPTY_ARRAY : new LocalQuickFix[]{ new AnnotateMethodFix(defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls()))}; holder.registerProblem(expr, text, fixes); } } } private static boolean isAssertionEffectively(PsiElement psiAnchor, boolean evaluatesToTrue) { PsiElement parent = PsiUtil.skipParenthesizedExprUp(psiAnchor.getParent()); if (parent instanceof PsiAssertStatement) { return evaluatesToTrue; } if (parent instanceof PsiIfStatement && psiAnchor == ((PsiIfStatement)parent).getCondition()) { PsiStatement thenBranch = ControlFlowUtils.stripBraces(((PsiIfStatement)parent).getThenBranch()); if (thenBranch instanceof PsiThrowStatement) { return !evaluatesToTrue; } } return false; } private static boolean isAtRHSOfBooleanAnd(PsiElement expr) { PsiElement cur = expr; while (cur != null && !(cur instanceof PsiMember)) { PsiElement parent = cur.getParent(); if (parent instanceof PsiBinaryExpression && cur == ((PsiBinaryExpression)parent).getROperand()) { return true; } cur = parent; } return false; } private static boolean isFlagCheck(PsiElement element) { PsiElement scope = PsiTreeUtil.getParentOfType(element, PsiStatement.class, PsiVariable.class); PsiExpression topExpression = scope instanceof PsiIfStatement ? ((PsiIfStatement)scope).getCondition() : scope instanceof PsiVariable ? ((PsiVariable)scope).getInitializer() : null; if (!PsiTreeUtil.isAncestor(topExpression, element, false)) return false; return StreamEx.<PsiElement>ofTree(topExpression, e -> StreamEx.of(e.getChildren())) .anyMatch(DataFlowInspectionBase::isCompileTimeFlagCheck); } private static boolean isCompileTimeFlagCheck(PsiElement element) { if(element instanceof PsiBinaryExpression) { PsiBinaryExpression binOp = (PsiBinaryExpression)element; if(ComparisonUtils.isComparisonOperation(binOp.getOperationTokenType())) { PsiExpression comparedWith = null; if(ExpressionUtils.isLiteral(binOp.getROperand())) { comparedWith = binOp.getLOperand(); } else if(ExpressionUtils.isLiteral(binOp.getLOperand())) { comparedWith = binOp.getROperand(); } comparedWith = PsiUtil.skipParenthesizedExprDown(comparedWith); if (isConstantOfType(comparedWith, PsiType.INT, PsiType.LONG)) { // like "if(DEBUG_LEVEL > 2)" return true; } if(comparedWith instanceof PsiBinaryExpression) { PsiBinaryExpression subOp = (PsiBinaryExpression)comparedWith; if(subOp.getOperationTokenType().equals(JavaTokenType.AND)) { PsiExpression left = PsiUtil.skipParenthesizedExprDown(subOp.getLOperand()); PsiExpression right = PsiUtil.skipParenthesizedExprDown(subOp.getROperand()); if(isConstantOfType(left, PsiType.INT, PsiType.LONG) || isConstantOfType(right, PsiType.INT, PsiType.LONG)) { // like "if((FLAGS & SOME_FLAG) != 0)" return true; } } } } } // like "if(DEBUG)" return isConstantOfType(element, PsiType.BOOLEAN); } private static boolean isConstantOfType(PsiElement element, PsiPrimitiveType... types) { PsiElement resolved = element instanceof PsiReferenceExpression ? ((PsiReferenceExpression)element).resolve() : null; if (!(resolved instanceof PsiField)) return false; PsiVariable field = (PsiVariable)resolved; return field.hasModifierProperty(PsiModifier.STATIC) && PsiUtil.isCompileTimeConstant(field) && ArrayUtil.contains(field.getType(), types); } private static boolean isNullLiteralExpression(PsiElement expr) { return expr instanceof PsiExpression && ExpressionUtils.isNullLiteral((PsiExpression)expr); } @Nullable private LocalQuickFix createSimplifyBooleanExpressionFix(PsiElement element, final boolean value) { LocalQuickFixOnPsiElement fix = createSimplifyBooleanFix(element, value); if (fix == null) return null; final String text = fix.getText(); return new LocalQuickFix() { @Override @NotNull public String getName() { return text; } @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { final PsiElement psiElement = descriptor.getPsiElement(); if (psiElement == null) return; final LocalQuickFixOnPsiElement fix = createSimplifyBooleanFix(psiElement, value); if (fix == null) return; try { LOG.assertTrue(psiElement.isValid()); fix.applyFix(); } catch (IncorrectOperationException e) { LOG.error(e); } } @Override @NotNull public String getFamilyName() { return InspectionsBundle.message("inspection.data.flow.simplify.boolean.expression.quickfix"); } }; } @NotNull protected static LocalQuickFix createSimplifyToAssignmentFix() { return new SimplifyToAssignmentFix(); } protected LocalQuickFixOnPsiElement createSimplifyBooleanFix(PsiElement element, boolean value) { return null; } @Override @NotNull public String getDisplayName() { return InspectionsBundle.message("inspection.data.flow.display.name"); } @Override @NotNull public String getGroupDisplayName() { return GroupNames.BUGS_GROUP_NAME; } @Override @NotNull public String getShortName() { return SHORT_NAME; } }
DataFlowInspectionBase: qualifier check (Review ID: IDEA-CR-28206)
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
DataFlowInspectionBase: qualifier check (Review ID: IDEA-CR-28206)
Java
apache-2.0
8dc2ada17a9de0237e3fa30003dba588684392e8
0
kiryuxxu/konashi-android-sdk,YUKAI/konashi-android-sdk,YUKAI/konashi-android-sdk,shiitakeo/konashi-android-sdk
package com.uxxu.konashi.sample.piosample; import android.app.Activity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; import com.uxxu.konashi.lib.Konashi; import com.uxxu.konashi.lib.KonashiErrorReason; import com.uxxu.konashi.lib.KonashiManager; import com.uxxu.konashi.lib.listeners.KonashiDigitalListener; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { private static final int[] PIO_PINS = new int[] { Konashi.PIO0, Konashi.PIO1, Konashi.PIO2, Konashi.PIO3, Konashi.PIO4, Konashi.PIO5 }; private static final int[] PIO_MODE_BUTTON_IDS = new int[] { R.id.btn_mode_pio0, R.id.btn_mode_pio1, R.id.btn_mode_pio2, R.id.btn_mode_pio3, R.id.btn_mode_pio4, R.id.btn_mode_pio5 }; private static final int[] PIO_OUTPUT_BUTTON_IDS = new int[] { R.id.btn_output_pio0, R.id.btn_output_pio1, R.id.btn_output_pio2, R.id.btn_output_pio3, R.id.btn_output_pio4, R.id.btn_output_pio5 }; private static final int[] PIO_INPUT_TEXT_IDS = new int[] { R.id.text_input_pio0, R.id.text_input_pio1, R.id.text_input_pio2, R.id.text_input_pio3, R.id.text_input_pio4, R.id.text_input_pio5 }; private static final int[] PIO_PULLUP_CHECKBOX_IDS = new int[] { R.id.checkbox_pullup_pio0, R.id.checkbox_pullup_pio1, R.id.checkbox_pullup_pio2, R.id.checkbox_pullup_pio3, R.id.checkbox_pullup_pio4, R.id.checkbox_pullup_pio5 }; private Callback mCallback; private ViewHolder[] mViewHolders = new ViewHolder[PIO_PINS.length]; public MainActivityFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof Callback) { mCallback = (Callback) activity; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); for (int i = 0; i < PIO_PINS.length; i++) { mViewHolders[i] = new ViewHolder( PIO_PINS[i], mCallback, (ToggleButton) v.findViewById(PIO_MODE_BUTTON_IDS[i]), (ToggleButton) v.findViewById(PIO_OUTPUT_BUTTON_IDS[i]), (TextView) v.findViewById(PIO_INPUT_TEXT_IDS[i]), (CheckBox) v.findViewById(PIO_PULLUP_CHECKBOX_IDS[i]) ); } return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mCallback.getKonashiManager().addListener(mKonashiDigitalListener); } @Override public void onDestroyView() { mCallback.getKonashiManager().removeListener(mKonashiDigitalListener); super.onDestroyView(); } private final KonashiDigitalListener mKonashiDigitalListener = new KonashiDigitalListener() { @Override public void onUpdatePioSetting(int modes) {} @Override public void onUpdatePioPullup(int pullups) {} @Override public void onUpdatePioInput(byte value) { mViewHolders[0].setInputValue(value); } @Override public void onUpdatePioOutput(byte value) { } @Override public void onError(KonashiErrorReason errorReason, String message) {} }; public interface Callback { KonashiManager getKonashiManager(); } private static final class ViewHolder implements CompoundButton.OnCheckedChangeListener { private final int mPin; private final Callback mCallback; private final ToggleButton mPioModeButton; private final ToggleButton mPioOutputButton; private final TextView mPioInputText; private final CheckBox mPioPullupCheckbox; public ViewHolder(int pin, Callback callback, ToggleButton pioModeButton, ToggleButton pioOutputButton, TextView pioInputText, CheckBox pioPullupCheckbox) { mPin = pin; mCallback = callback; mPioModeButton = pioModeButton; mPioOutputButton = pioOutputButton; mPioInputText = pioInputText; mPioPullupCheckbox = pioPullupCheckbox; mPioModeButton.setOnCheckedChangeListener(this); mPioOutputButton.setOnCheckedChangeListener(this); mPioPullupCheckbox.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.equals(mPioModeButton)) { mCallback.getKonashiManager().pinMode(mPin, isChecked ? Konashi.OUTPUT : Konashi.INPUT); mPioOutputButton.setEnabled(isChecked); mPioInputText.setEnabled(!isChecked); } if (buttonView.equals(mPioOutputButton)) { mCallback.getKonashiManager().digitalWrite(mPin, isChecked ? Konashi.HIGH : Konashi.LOW); } if (buttonView.equals(mPioPullupCheckbox)) { mCallback.getKonashiManager().pinPullup(mPin, isChecked ? Konashi.PULLUP : Konashi.NO_PULLS); } } public void setInputValue(byte value) { mPioInputText.setText(value == Konashi.HIGH ? "HIGH" : "LOW"); } } }
samples/pio-sample/src/main/java/com/uxxu/konashi/sample/piosample/MainActivityFragment.java
package com.uxxu.konashi.sample.piosample; import android.app.Activity; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.ToggleButton; import com.uxxu.konashi.lib.Konashi; import com.uxxu.konashi.lib.KonashiErrorReason; import com.uxxu.konashi.lib.KonashiManager; import com.uxxu.konashi.lib.listeners.KonashiDigitalListener; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { private static final int[] PIO_PINS = new int[] { Konashi.PIO0, Konashi.PIO1, Konashi.PIO2, Konashi.PIO3, Konashi.PIO4, Konashi.PIO5 }; private static final int[] PIO_MODE_BUTTON_IDS = new int[] { R.id.btn_mode_pio0, R.id.btn_mode_pio1, R.id.btn_mode_pio2, R.id.btn_mode_pio3, R.id.btn_mode_pio4, R.id.btn_mode_pio5 }; private static final int[] PIO_OUTPUT_BUTTON_IDS = new int[] { R.id.btn_output_pio0, R.id.btn_output_pio1, R.id.btn_output_pio2, R.id.btn_output_pio3, R.id.btn_output_pio4, R.id.btn_output_pio5 }; private static final int[] PIO_INPUT_TEXT_IDS = new int[] { R.id.text_input_pio0, R.id.text_input_pio1, R.id.text_input_pio2, R.id.text_input_pio3, R.id.text_input_pio4, R.id.text_input_pio5 }; private static final int[] PIO_PULLUP_CHECKBOX_IDS = new int[] { R.id.checkbox_pullup_pio0, R.id.checkbox_pullup_pio1, R.id.checkbox_pullup_pio2, R.id.checkbox_pullup_pio3, R.id.checkbox_pullup_pio4, R.id.checkbox_pullup_pio5 }; private Callback mCallback; private ViewHolder[] mViewHolders = new ViewHolder[PIO_PINS.length]; public MainActivityFragment() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof Callback) { mCallback = (Callback) activity; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); for (int i = 0; i < PIO_PINS.length; i++) { mViewHolders[i] = new ViewHolder( PIO_PINS[i], mCallback, (ToggleButton) v.findViewById(PIO_MODE_BUTTON_IDS[i]), (ToggleButton) v.findViewById(PIO_OUTPUT_BUTTON_IDS[i]), (TextView) v.findViewById(PIO_INPUT_TEXT_IDS[i]), (CheckBox) v.findViewById(PIO_PULLUP_CHECKBOX_IDS[i]) ); } return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mCallback.getKonashiManager().addListener(mKonashiDigitalListener); } @Override public void onDestroyView() { mCallback.getKonashiManager().removeListener(mKonashiDigitalListener); super.onDestroyView(); } private final KonashiDigitalListener mKonashiDigitalListener = new KonashiDigitalListener() { @Override public void onUpdatePioSetting(int modes) {} @Override public void onUpdatePioPullup(int pullups) {} @Override public void onUpdatePioInput(byte value) { mViewHolders[0].setInputValue(value); } @Override public void onError(KonashiErrorReason errorReason, String message) {} }; public interface Callback { KonashiManager getKonashiManager(); } private static final class ViewHolder implements CompoundButton.OnCheckedChangeListener { private final int mPin; private final Callback mCallback; private final ToggleButton mPioModeButton; private final ToggleButton mPioOutputButton; private final TextView mPioInputText; private final CheckBox mPioPullupCheckbox; public ViewHolder(int pin, Callback callback, ToggleButton pioModeButton, ToggleButton pioOutputButton, TextView pioInputText, CheckBox pioPullupCheckbox) { mPin = pin; mCallback = callback; mPioModeButton = pioModeButton; mPioOutputButton = pioOutputButton; mPioInputText = pioInputText; mPioPullupCheckbox = pioPullupCheckbox; mPioModeButton.setOnCheckedChangeListener(this); mPioOutputButton.setOnCheckedChangeListener(this); mPioPullupCheckbox.setOnCheckedChangeListener(this); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView.equals(mPioModeButton)) { mCallback.getKonashiManager().pinMode(mPin, isChecked ? Konashi.OUTPUT : Konashi.INPUT); mPioOutputButton.setEnabled(isChecked); mPioInputText.setEnabled(!isChecked); } if (buttonView.equals(mPioOutputButton)) { mCallback.getKonashiManager().digitalWrite(mPin, isChecked ? Konashi.HIGH : Konashi.LOW); } if (buttonView.equals(mPioPullupCheckbox)) { mCallback.getKonashiManager().pinPullup(mPin, isChecked ? Konashi.PULLUP : Konashi.NO_PULLS); } } public void setInputValue(byte value) { mPioInputText.setText(value == Konashi.HIGH ? "HIGH" : "LOW"); } } }
Fix PIO sample
samples/pio-sample/src/main/java/com/uxxu/konashi/sample/piosample/MainActivityFragment.java
Fix PIO sample
Java
apache-2.0
b9f9ce3463ba0dcf38f3c3af1482f3c2c7356bda
0
Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet,Ooppa/iot-industrial-internet
/* * IoT - Industrial Internet Framework * Apache License Version 2.0, January 2004 * Released as a part of Helsinki University * Software Engineering Lab in summer 2015 */ package fi.iot.iiframework.restapi; import fi.iot.iiframework.application.ApplicationSettings; import fi.iot.iiframework.restapi.exceptions.InvalidObjectException; import fi.iot.iiframework.restapi.exceptions.InvalidParametersException; import fi.iot.iiframework.restapi.exceptions.ResourceNotFoundException; import fi.iot.iiframework.source.InformationSourceConfiguration; import fi.iot.iiframework.source.InformationSourceManager; import fi.iot.iiframework.source.service.InformationSourceConfigurationService; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("1.0/configurations") public class ConfigurationController { @Autowired private RestAPIHelper helper; @Autowired private ApplicationSettings settings; @Autowired private InformationSourceManager informationSourceManager; @Autowired private InformationSourceConfigurationService informationSourceConfigurationService; @RequestMapping(value = "/informationsources/{configid}/view", produces = "application/json") @ResponseBody public InformationSourceConfiguration getInformationSource( @PathVariable String configid, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException { return (InformationSourceConfiguration) helper.returnOrException(informationSourceConfigurationService.get(configid)); } @RequestMapping( value = "/informationsources/add", method = RequestMethod.POST, produces = "application/json", consumes = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> addInformationSource( @RequestBody InformationSourceConfiguration configuration, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException { helper.checkIfObjectIsValid(configuration); informationSourceManager.updateSource(configuration.getId(), configuration); return new ResponseEntity<>(configuration, HttpStatus.CREATED); } @RequestMapping( value = "/informationsources/edit", method = RequestMethod.POST, produces = "application/json", consumes = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> editInformationSource( @RequestBody InformationSourceConfiguration configuration, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException { helper.checkIfObjectIsValid(configuration); informationSourceManager.updateSource(configuration.getId(), configuration); return new ResponseEntity<>(configuration, HttpStatus.CREATED); } @RequestMapping( value = "/informationsources/{configid}/delete", method = RequestMethod.DELETE, produces = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> deleteInformationSource( @PathVariable String configid, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException { InformationSourceConfiguration configuration = (InformationSourceConfiguration) helper.returnOrException(informationSourceConfigurationService.get(configid)); informationSourceConfigurationService.delete(configuration); return new ResponseEntity<>(configuration, HttpStatus.OK); } @RequestMapping(value = "/informationsources/list", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesList( @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { return informationSourceConfigurationService.get(0, settings.getDefaultInformationSourcesRetrievedFromDatabase()); } @RequestMapping(value = "/informationsources/list/{amount}", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesListAmount( @PathVariable int amount, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { helper.exceptionIfWrongLimits(0, amount); return informationSourceConfigurationService.get(0, amount); } @RequestMapping(value = "/informationsources/list/{to}/{from}", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesListFromTo( @PathVariable int from, @PathVariable int to, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { helper.exceptionIfWrongLimits(to, from); return informationSourceConfigurationService.get(to, from); } }
iot-industrial-internet/src/main/java/fi/iot/iiframework/restapi/ConfigurationController.java
/* * IoT - Industrial Internet Framework * Apache License Version 2.0, January 2004 * Released as a part of Helsinki University * Software Engineering Lab in summer 2015 */ package fi.iot.iiframework.restapi; import fi.iot.iiframework.application.ApplicationSettings; import fi.iot.iiframework.restapi.exceptions.InvalidObjectException; import fi.iot.iiframework.restapi.exceptions.InvalidParametersException; import fi.iot.iiframework.restapi.exceptions.ResourceNotFoundException; import fi.iot.iiframework.source.InformationSourceConfiguration; import fi.iot.iiframework.source.InformationSourceManager; import fi.iot.iiframework.source.service.InformationSourceConfigurationService; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("1.0/configurations") public class ConfigurationController { @Autowired private RestAPIHelper helper; @Autowired private ApplicationSettings settings; @Autowired private InformationSourceManager informationSourceManager; @Autowired private InformationSourceConfigurationService informationSourceConfigurationService; @RequestMapping(value = "/informationsources/{configid}/view", produces = "application/json") @ResponseBody public InformationSourceConfiguration getInformationSource( @PathVariable String configid, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException { return (InformationSourceConfiguration) helper.returnOrException(informationSourceConfigurationService.get(configid)); } @RequestMapping( value = "/informationsources/add", method = RequestMethod.POST, produces = "application/json", consumes = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> addInformationSource( @RequestBody InformationSourceConfiguration configuration, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException { helper.checkIfObjectIsValid(configuration); informationSourceConfigurationService.save(configuration); return new ResponseEntity<>(configuration, HttpStatus.CREATED); } @RequestMapping( value = "/informationsources/edit", method = RequestMethod.POST, produces = "application/json", consumes = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> editInformationSource( @RequestBody InformationSourceConfiguration configuration, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException, InvalidObjectException { helper.checkIfObjectIsValid(configuration); informationSourceManager.updateSource(configuration.getId(), configuration); return new ResponseEntity<>(configuration, HttpStatus.CREATED); } @RequestMapping( value = "/informationsources/{configid}/delete", method = RequestMethod.DELETE, produces = "application/json" ) @ResponseBody public ResponseEntity<InformationSourceConfiguration> deleteInformationSource( @PathVariable String configid, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException, ResourceNotFoundException { InformationSourceConfiguration configuration = (InformationSourceConfiguration) helper.returnOrException(informationSourceConfigurationService.get(configid)); informationSourceConfigurationService.delete(configuration); return new ResponseEntity<>(configuration, HttpStatus.OK); } @RequestMapping(value = "/informationsources/list", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesList( @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { return informationSourceConfigurationService.get(0, settings.getDefaultInformationSourcesRetrievedFromDatabase()); } @RequestMapping(value = "/informationsources/list/{amount}", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesListAmount( @PathVariable int amount, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { helper.exceptionIfWrongLimits(0, amount); return informationSourceConfigurationService.get(0, amount); } @RequestMapping(value = "/informationsources/list/{to}/{from}", produces = "application/json") @ResponseBody public List<InformationSourceConfiguration> listInformationSourcesListFromTo( @PathVariable int from, @PathVariable int to, @RequestParam(required = false) Map<String, String> params ) throws InvalidParametersException { helper.exceptionIfWrongLimits(to, from); return informationSourceConfigurationService.get(to, from); } }
Changed addInformationSource
iot-industrial-internet/src/main/java/fi/iot/iiframework/restapi/ConfigurationController.java
Changed addInformationSource
Java
apache-2.0
16c357f470e888dd99c2ba12d3c84374a78f5821
0
jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim,jaamsim/jaamsim
/* * JaamSim Discrete Event Simulation * Copyright (C) 2016-2018 JaamSim Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import com.jaamsim.Commands.DefineCommand; import com.jaamsim.Commands.CoordinateCommand; import com.jaamsim.Commands.DeleteCommand; import com.jaamsim.Commands.KeywordCommand; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.Simulation; import com.jaamsim.controllers.RenderManager; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.math.Vec3d; public class ContextMenu { private static final ArrayList<ContextMenuItem> menuItems = new ArrayList<>(); private ContextMenu() {} public static final void addCustomMenuHandler(ContextMenuItem i) { synchronized (menuItems) { menuItems.add(i); } } private static class UIMenuItem extends JMenuItem implements ActionListener { final ContextMenuItem i; final Entity ent; final int x; final int y; UIMenuItem(ContextMenuItem i, Entity ent, int x, int y) { super(i.getMenuText()); this.i = i; this.ent = ent; this.x = x; this.y = y; this.addActionListener(this); } @Override public void actionPerformed(ActionEvent event) { i.performAction(ent, x, y); } } /** * Adds menu items to the right click (context) menu for the specified entity. * @param ent - entity whose context menu is to be generated * @param menu - context menu to be populated with menu items * @param x - screen coordinate for the menu * @param y - screen coordinate for the menu */ public static void populateMenu(JPopupMenu menu, final Entity ent, final int nodeIndex, final int x, final int y) { // 1) Input Editor JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowInputEditor", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( inputEditorMenuItem ); // 2) Output Viewer JMenuItem outputViewerMenuItem = new JMenuItem( "Output Viewer" ); outputViewerMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowOutputViewer", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( outputViewerMenuItem ); // 3) Property Viewer JMenuItem propertyViewerMenuItem = new JMenuItem( "Property Viewer" ); propertyViewerMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowPropertyViewer", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( propertyViewerMenuItem ); // 4) Duplicate JMenuItem duplicateMenuItem = new JMenuItem( "Duplicate" ); duplicateMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String name = InputAgent.getUniqueName(ent.getName(), "_Copy"); InputAgent.storeAndExecute(new DefineCommand(ent.getClass(), name)); Entity copiedEntity = Entity.getNamedEntity(name); // Match all the inputs copiedEntity.copyInputs(ent); // Position the duplicated entity next to the original if (copiedEntity instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity)copiedEntity; Vec3d pos = dEnt.getPosition(); pos.x += 0.5d * dEnt.getSize().x; pos.y -= 0.5d * dEnt.getSize().y; try { dEnt.dragged(pos); } catch (InputErrorException e) {} } // Show the duplicated entity in the editors and viewers FrameBox.setSelectedEntity(copiedEntity, false); } } ); if (ent.testFlag(Entity.FLAG_GENERATED)) { duplicateMenuItem.setEnabled(false); } menu.add( duplicateMenuItem ); // 5) Delete JMenuItem deleteMenuItem = new JMenuItem( "Delete" ); deleteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.storeAndExecute(new DeleteCommand(ent)); FrameBox.setSelectedEntity(null, false); } } ); menu.add( deleteMenuItem ); // DisplayEntity menu items if (ent instanceof DisplayEntity) { ContextMenu.populateDisplayEntityMenu(menu, (DisplayEntity)ent, nodeIndex, x, y); } synchronized (menuItems) { for (ContextMenuItem each : menuItems) { if (each.supportsEntity(ent)) menu.add(new UIMenuItem(each, ent, x, y)); } } } public static void populateDisplayEntityMenu(JPopupMenu menu, final DisplayEntity ent, final int nodeIndex, final int x, final int y) { if (!RenderManager.isGood()) return; // 1) Change Graphics JMenuItem changeGraphicsMenuItem = new JMenuItem( "Change Graphics" ); changeGraphicsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GraphicBox graphicBox = GraphicBox.getInstance(ent, x, y); graphicBox.setVisible( true ); } } ); if (ent.getDisplayModelList() == null) { changeGraphicsMenuItem.setEnabled(false); } menu.add( changeGraphicsMenuItem ); // 2) Show Label final EntityLabel label = EntityLabel.getLabel(ent); boolean bool = label != null && label.getShow(); final JMenuItem showLabelMenuItem = new JCheckBoxMenuItem( "Show Label", bool ); showLabelMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (showLabelMenuItem.isSelected()) { // If required, create the EntityLabel object if (label == null) { String name = InputAgent.getUniqueName(ent.getName(), "_Label"); InputAgent.storeAndExecute(new DefineCommand(EntityLabel.class, name)); EntityLabel newLabel = (EntityLabel)Entity.getNamedEntity(name); // Assign inputs that link the label to its target entity InputAgent.applyArgs(newLabel, "TargetEntity", ent.getName()); InputAgent.applyArgs(newLabel, "RelativeEntity", ent.getName()); if (ent.getCurrentRegion() != null) InputAgent.applyArgs(newLabel, "Region", ent.getCurrentRegion().getName()); // Set the label's position double ypos = -0.15 - 0.5*ent.getSize().y; InputAgent.apply(newLabel, InputAgent.formatPointInputs("Position", new Vec3d(0.0, ypos, 0.0), "m")); // Set the label's size newLabel.resizeForText(); return; } // Show the label InputAgent.applyArgs(label, "Show", "TRUE"); } else { // Hide the label if it already exists if (label != null) InputAgent.applyArgs(label, "Show", "FALSE"); } } } ); if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { showLabelMenuItem.setEnabled(false); } menu.add( showLabelMenuItem ); // 3) Set RelativeEntity ScrollableMenu setRelativeEntityMenu = new ScrollableMenu( "Set RelativeEntity" ); ArrayList<String> entNameList = new ArrayList<>(); entNameList.add("<None>"); entNameList.addAll(ent.getRelativeEntityOptions()); String presentEntName = "<None>"; if (ent.getRelativeEntity() != null) { presentEntName = ent.getRelativeEntity().getName(); } for (final String entName : entNameList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(entName); if (entName.equals(presentEntName)) { item.setSelected(true); } item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw; if (entName.equals("<None>")) { kw = InputAgent.formatArgs("RelativeEntity"); } else { kw = InputAgent.formatArgs("RelativeEntity", entName); } InputAgent.storeAndExecute(new CoordinateCommand(ent, kw)); } } ); setRelativeEntityMenu.add(item); } if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { setRelativeEntityMenu.setEnabled(false); } menu.add( setRelativeEntityMenu ); // 4) Set Region ScrollableMenu setRegionMenu = new ScrollableMenu( "Set Region" ); ArrayList<String> regionNameList = new ArrayList<>(); regionNameList.add("<None>"); regionNameList.addAll(ent.getRegionOptions()); String presentRegionName = "<None>"; if (ent.getCurrentRegion() != null) { presentRegionName = ent.getCurrentRegion().getName(); } for (final String regionName : regionNameList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(regionName); if (regionName.equals(presentRegionName)) { item.setSelected(true); } item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw; if (regionName.equals("<None>")) { kw = InputAgent.formatArgs("Region"); } else { kw = InputAgent.formatArgs("Region", regionName); } InputAgent.storeAndExecute(new CoordinateCommand(ent, kw)); } } ); setRegionMenu.add(item); } if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { setRegionMenu.setEnabled(false); } menu.add( setRegionMenu ); // 5) Centre in View JMenuItem centerInViewMenuItem = new JMenuItem( "Center in View" ); final View v = RenderManager.inst().getActiveView(); centerInViewMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Move the camera position so that the entity is in the centre of the screen Vec3d viewPos = new Vec3d(v.getGlobalPosition()); viewPos.sub3(v.getGlobalCenter()); viewPos.add3(ent.getPosition()); KeywordIndex posKw = InputAgent.formatPointInputs("ViewPosition", viewPos, "m"); KeywordIndex ctrKw = InputAgent.formatPointInputs("ViewCenter", ent.getPosition(), "m"); InputAgent.storeAndExecute(new KeywordCommand(v, posKw, ctrKw)); } } ); if (v == null) { centerInViewMenuItem.setEnabled(false); } menu.add( centerInViewMenuItem ); // 6) Split JMenuItem spitMenuItem = new JMenuItem( "Split" ); spitMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String name = InputAgent.getUniqueName(ent.getName(), "_Split"); InputAgent.storeAndExecute(new DefineCommand(ent.getClass(), name)); DisplayEntity splitEnt = (DisplayEntity) Entity.getNamedEntity(name); // Match all the inputs splitEnt.copyInputs(ent); // Original entity is left with the first portion of the nodes ArrayList<Vec3d> pts = ent.getPoints(); ArrayList<Vec3d> pts0 = new ArrayList<>(nodeIndex + 1); for (int i = 0; i <= nodeIndex; i++) { pts0.add(pts.get(i)); } KeywordIndex ptsKw0 = InputAgent.formatPointsInputs("Points", pts0, new Vec3d()); InputAgent.storeAndExecute(new KeywordCommand(ent, nodeIndex, ptsKw0)); // New entity receives the remaining portion of the nodes ArrayList<Vec3d> pts1 = new ArrayList<>(pts.size() - nodeIndex); for (int i = nodeIndex; i < pts.size(); i++) { pts1.add(pts.get(i)); } KeywordIndex ptsKw1 = InputAgent.formatPointsInputs("Points", pts1, new Vec3d()); InputAgent.processKeyword(splitEnt, ptsKw1); // Change any other object specific inputs for the split ent.setInputsForSplit(splitEnt); // Show the split entity in the editors and viewers FrameBox.setSelectedEntity(splitEnt, false); } } ); if (ent.testFlag(Entity.FLAG_GENERATED) || nodeIndex <= 0 || nodeIndex == ent.getPoints().size() - 1) { spitMenuItem.setEnabled(false); } menu.add( spitMenuItem ); // 7) Delete Node JMenuItem deleteNodeItem = new JMenuItem( "Delete Node" ); deleteNodeItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<Vec3d> pts = ent.getPoints(); pts.remove(nodeIndex); KeywordIndex ptsKw = InputAgent.formatPointsInputs("Points", pts, new Vec3d()); InputAgent.storeAndExecute(new KeywordCommand(ent, nodeIndex, ptsKw)); } } ); if (ent.testFlag(Entity.FLAG_GENERATED) || nodeIndex == -1 || ent.getPoints().size() <= 2) { deleteNodeItem.setEnabled(false); } menu.add( deleteNodeItem ); } }
src/main/java/com/jaamsim/ui/ContextMenu.java
/* * JaamSim Discrete Event Simulation * Copyright (C) 2016-2018 JaamSim Software Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jaamsim.ui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import com.jaamsim.Commands.DefineCommand; import com.jaamsim.Commands.CoordinateCommand; import com.jaamsim.Commands.DeleteCommand; import com.jaamsim.Commands.KeywordCommand; import com.jaamsim.Graphics.DisplayEntity; import com.jaamsim.Graphics.EntityLabel; import com.jaamsim.basicsim.Entity; import com.jaamsim.basicsim.Simulation; import com.jaamsim.controllers.RenderManager; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.KeywordIndex; import com.jaamsim.math.Vec3d; public class ContextMenu { private static final ArrayList<ContextMenuItem> menuItems = new ArrayList<>(); private ContextMenu() {} public static final void addCustomMenuHandler(ContextMenuItem i) { synchronized (menuItems) { menuItems.add(i); } } private static class UIMenuItem extends JMenuItem implements ActionListener { final ContextMenuItem i; final Entity ent; final int x; final int y; UIMenuItem(ContextMenuItem i, Entity ent, int x, int y) { super(i.getMenuText()); this.i = i; this.ent = ent; this.x = x; this.y = y; this.addActionListener(this); } @Override public void actionPerformed(ActionEvent event) { i.performAction(ent, x, y); } } /** * Adds menu items to the right click (context) menu for the specified entity. * @param ent - entity whose context menu is to be generated * @param menu - context menu to be populated with menu items * @param x - screen coordinate for the menu * @param y - screen coordinate for the menu */ public static void populateMenu(JPopupMenu menu, final Entity ent, final int nodeIndex, final int x, final int y) { // 1) Input Editor JMenuItem inputEditorMenuItem = new JMenuItem( "Input Editor" ); inputEditorMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowInputEditor", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( inputEditorMenuItem ); // 2) Output Viewer JMenuItem outputViewerMenuItem = new JMenuItem( "Output Viewer" ); outputViewerMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowOutputViewer", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( outputViewerMenuItem ); // 3) Property Viewer JMenuItem propertyViewerMenuItem = new JMenuItem( "Property Viewer" ); propertyViewerMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.applyArgs(Simulation.getInstance(), "ShowPropertyViewer", "TRUE"); FrameBox.setSelectedEntity(ent, false); } } ); menu.add( propertyViewerMenuItem ); // 4) Duplicate JMenuItem duplicateMenuItem = new JMenuItem( "Duplicate" ); duplicateMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String name = InputAgent.getUniqueName(ent.getName(), "_Copy"); InputAgent.storeAndExecute(new DefineCommand(ent.getClass(), name)); Entity copiedEntity = Entity.getNamedEntity(name); // Match all the inputs copiedEntity.copyInputs(ent); // Position the duplicated entity next to the original if (copiedEntity instanceof DisplayEntity) { DisplayEntity dEnt = (DisplayEntity)copiedEntity; Vec3d pos = dEnt.getPosition(); pos.x += 0.5d * dEnt.getSize().x; pos.y -= 0.5d * dEnt.getSize().y; try { dEnt.dragged(pos); } catch (InputErrorException e) {} } // Show the duplicated entity in the editors and viewers FrameBox.setSelectedEntity(copiedEntity, false); } } ); if (ent.testFlag(Entity.FLAG_GENERATED)) { duplicateMenuItem.setEnabled(false); } menu.add( duplicateMenuItem ); // 5) Delete JMenuItem deleteMenuItem = new JMenuItem( "Delete" ); deleteMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { InputAgent.storeAndExecute(new DeleteCommand(ent)); FrameBox.setSelectedEntity(null, false); } } ); menu.add( deleteMenuItem ); // DisplayEntity menu items if (ent instanceof DisplayEntity) { ContextMenu.populateDisplayEntityMenu(menu, (DisplayEntity)ent, nodeIndex, x, y); } synchronized (menuItems) { for (ContextMenuItem each : menuItems) { if (each.supportsEntity(ent)) menu.add(new UIMenuItem(each, ent, x, y)); } } } public static void populateDisplayEntityMenu(JPopupMenu menu, final DisplayEntity ent, final int nodeIndex, final int x, final int y) { if (!RenderManager.isGood()) return; // 1) Change Graphics JMenuItem changeGraphicsMenuItem = new JMenuItem( "Change Graphics" ); changeGraphicsMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { GraphicBox graphicBox = GraphicBox.getInstance(ent, x, y); graphicBox.setVisible( true ); } } ); if (ent.getDisplayModelList() == null) { changeGraphicsMenuItem.setEnabled(false); } menu.add( changeGraphicsMenuItem ); // 2) Show Label final EntityLabel label = EntityLabel.getLabel(ent); boolean bool = label != null && label.getShow(); final JMenuItem showLabelMenuItem = new JCheckBoxMenuItem( "Show Label", bool ); showLabelMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { if (showLabelMenuItem.isSelected()) { // If required, create the EntityLabel object if (label == null) { String name = InputAgent.getUniqueName(ent.getName(), "_Label"); InputAgent.storeAndExecute(new DefineCommand(EntityLabel.class, name)); EntityLabel newLabel = (EntityLabel)Entity.getNamedEntity(name); // Assign inputs that link the label to its target entity InputAgent.applyArgs(newLabel, "TargetEntity", ent.getName()); InputAgent.applyArgs(newLabel, "RelativeEntity", ent.getName()); if (ent.getCurrentRegion() != null) InputAgent.applyArgs(newLabel, "Region", ent.getCurrentRegion().getName()); // Set the label's position double ypos = -0.15 - 0.5*ent.getSize().y; InputAgent.apply(newLabel, InputAgent.formatPointInputs("Position", new Vec3d(0.0, ypos, 0.0), "m")); // Set the label's size newLabel.resizeForText(); return; } // Show the label InputAgent.applyArgs(label, "Show", "TRUE"); } else { // Hide the label if it already exists if (label != null) InputAgent.applyArgs(label, "Show", "FALSE"); } } } ); if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { showLabelMenuItem.setEnabled(false); } menu.add( showLabelMenuItem ); // 3) Set RelativeEntity JMenu setRelativeEntityMenu = new JMenu( "Set RelativeEntity" ); ArrayList<String> entNameList = new ArrayList<>(); entNameList.add("<None>"); entNameList.addAll(ent.getRelativeEntityOptions()); String presentEntName = "<None>"; if (ent.getRelativeEntity() != null) { presentEntName = ent.getRelativeEntity().getName(); } for (final String entName : entNameList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(entName); if (entName.equals(presentEntName)) { item.setSelected(true); } item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw; if (entName.equals("<None>")) { kw = InputAgent.formatArgs("RelativeEntity"); } else { kw = InputAgent.formatArgs("RelativeEntity", entName); } InputAgent.storeAndExecute(new CoordinateCommand(ent, kw)); } } ); setRelativeEntityMenu.add(item); } if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { setRelativeEntityMenu.setEnabled(false); } menu.add( setRelativeEntityMenu ); // 4) Set Region JMenu setRegionMenu = new JMenu( "Set Region" ); ArrayList<String> regionNameList = new ArrayList<>(); regionNameList.add("<None>"); regionNameList.addAll(ent.getRegionOptions()); String presentRegionName = "<None>"; if (ent.getCurrentRegion() != null) { presentRegionName = ent.getCurrentRegion().getName(); } for (final String regionName : regionNameList) { JRadioButtonMenuItem item = new JRadioButtonMenuItem(regionName); if (regionName.equals(presentRegionName)) { item.setSelected(true); } item.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { KeywordIndex kw; if (regionName.equals("<None>")) { kw = InputAgent.formatArgs("Region"); } else { kw = InputAgent.formatArgs("Region", regionName); } InputAgent.storeAndExecute(new CoordinateCommand(ent, kw)); } } ); setRegionMenu.add(item); } if (ent instanceof EntityLabel || ent.testFlag(Entity.FLAG_GENERATED)) { setRegionMenu.setEnabled(false); } menu.add( setRegionMenu ); // 5) Centre in View JMenuItem centerInViewMenuItem = new JMenuItem( "Center in View" ); final View v = RenderManager.inst().getActiveView(); centerInViewMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { // Move the camera position so that the entity is in the centre of the screen Vec3d viewPos = new Vec3d(v.getGlobalPosition()); viewPos.sub3(v.getGlobalCenter()); viewPos.add3(ent.getPosition()); KeywordIndex posKw = InputAgent.formatPointInputs("ViewPosition", viewPos, "m"); KeywordIndex ctrKw = InputAgent.formatPointInputs("ViewCenter", ent.getPosition(), "m"); InputAgent.storeAndExecute(new KeywordCommand(v, posKw, ctrKw)); } } ); if (v == null) { centerInViewMenuItem.setEnabled(false); } menu.add( centerInViewMenuItem ); // 6) Split JMenuItem spitMenuItem = new JMenuItem( "Split" ); spitMenuItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { String name = InputAgent.getUniqueName(ent.getName(), "_Split"); InputAgent.storeAndExecute(new DefineCommand(ent.getClass(), name)); DisplayEntity splitEnt = (DisplayEntity) Entity.getNamedEntity(name); // Match all the inputs splitEnt.copyInputs(ent); // Original entity is left with the first portion of the nodes ArrayList<Vec3d> pts = ent.getPoints(); ArrayList<Vec3d> pts0 = new ArrayList<>(nodeIndex + 1); for (int i = 0; i <= nodeIndex; i++) { pts0.add(pts.get(i)); } KeywordIndex ptsKw0 = InputAgent.formatPointsInputs("Points", pts0, new Vec3d()); InputAgent.storeAndExecute(new KeywordCommand(ent, nodeIndex, ptsKw0)); // New entity receives the remaining portion of the nodes ArrayList<Vec3d> pts1 = new ArrayList<>(pts.size() - nodeIndex); for (int i = nodeIndex; i < pts.size(); i++) { pts1.add(pts.get(i)); } KeywordIndex ptsKw1 = InputAgent.formatPointsInputs("Points", pts1, new Vec3d()); InputAgent.processKeyword(splitEnt, ptsKw1); // Change any other object specific inputs for the split ent.setInputsForSplit(splitEnt); // Show the split entity in the editors and viewers FrameBox.setSelectedEntity(splitEnt, false); } } ); if (ent.testFlag(Entity.FLAG_GENERATED) || nodeIndex <= 0 || nodeIndex == ent.getPoints().size() - 1) { spitMenuItem.setEnabled(false); } menu.add( spitMenuItem ); // 7) Delete Node JMenuItem deleteNodeItem = new JMenuItem( "Delete Node" ); deleteNodeItem.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent event ) { ArrayList<Vec3d> pts = ent.getPoints(); pts.remove(nodeIndex); KeywordIndex ptsKw = InputAgent.formatPointsInputs("Points", pts, new Vec3d()); InputAgent.storeAndExecute(new KeywordCommand(ent, nodeIndex, ptsKw)); } } ); if (ent.testFlag(Entity.FLAG_GENERATED) || nodeIndex == -1 || ent.getPoints().size() <= 2) { deleteNodeItem.setEnabled(false); } menu.add( deleteNodeItem ); } }
JS: use ScrollableMenu to set RelativeEntity and Region in ContextMenu Signed-off-by: Harry King <[email protected]>
src/main/java/com/jaamsim/ui/ContextMenu.java
JS: use ScrollableMenu to set RelativeEntity and Region in ContextMenu
Java
apache-2.0
b6204a3aabea1ade6a7636d1823a268c91058113
0
trask/glowroot-example-collector
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.example; import java.io.File; import java.util.List; import org.glowroot.agent.shaded.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.Environment; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.GaugeValue; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.LogEvent; import org.glowroot.agent.shaded.glowroot.wire.api.model.TraceOuterClass.Trace; public class GlowrootCollector implements org.glowroot.agent.collector.Collector { @Override public void init(File glowrootDir, Environment environment, AgentConfig agentConfig, AgentConfigUpdater agentConfigUpdater) throws Exception { System.out.println("collectInit"); } @Override public void collectAggregates(long captureTime, Aggregates aggregates) throws Exception { System.out.println("collectAggregates"); } @Override public void collectGaugeValues(List<GaugeValue> gaugeValues) throws Exception { System.out.println("collectGaugeValues: " + gaugeValues.size()); } @Override public void collectTrace(Trace trace) throws Exception { System.out.println("collectAggregates"); } @Override public void log(LogEvent logEvent) throws Exception { System.out.println("log"); } }
src/main/java/org/example/GlowrootCollector.java
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.example; import java.io.File; import java.util.List; import org.glowroot.agent.shaded.glowroot.wire.api.model.AgentConfigOuterClass.AgentConfig; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.Environment; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.GaugeValue; import org.glowroot.agent.shaded.glowroot.wire.api.model.CollectorServiceOuterClass.LogEvent; import org.glowroot.agent.shaded.glowroot.wire.api.model.TraceOuterClass.Trace; public class GlowrootCollector implements org.glowroot.agent.collector.Collector { @Override public void init(File glowrootBaseDir, Environment environment, AgentConfig agentConfig, AgentConfigUpdater agentConfigUpdater) throws Exception { System.out.println("collectInit"); } @Override public void collectAggregates(long captureTime, Aggregates aggregates) throws Exception { System.out.println("collectAggregates"); } @Override public void collectGaugeValues(List<GaugeValue> gaugeValues) throws Exception { System.out.println("collectGaugeValues: " + gaugeValues.size()); } @Override public void collectTrace(Trace trace) throws Exception { System.out.println("collectAggregates"); } @Override public void log(LogEvent logEvent) throws Exception { System.out.println("log"); } }
Update to latest version
src/main/java/org/example/GlowrootCollector.java
Update to latest version
Java
apache-2.0
de5e4c708b3b7567f2da5ce6f9c1760857aa9380
0
gavanx/pdflearn,gavanx/pdflearn
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.debugger.ui; import java.awt.Component; import java.util.Arrays; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JRadioButtonMenuItem; /** * @author Khyrul Bashar * * A singleton class that provides zoom menu which can be used to show zoom menu in the menubar. To * act upon the menu item selection user of the class must add ActionListener which will check for * the action command and act accordingly. */ public final class ZoomMenu extends MenuBase { private static class ZoomMenuItem extends JRadioButtonMenuItem { private final int zoom; ZoomMenuItem(String text, int zoom) { super(text); this.zoom = zoom; } } private float pageZoomScale = 1; private float imageZoomScale = 1; private static final int[] ZOOMS = new int[] { 25, 50, 100, 200, 400, 1000 }; private static ZoomMenu instance; private final JMenu menu; /** * Constructor. */ private ZoomMenu() { menu = new JMenu("Zoom"); ButtonGroup bg = new ButtonGroup(); for (int zoom : ZOOMS) { ZoomMenuItem zoomItem = new ZoomMenuItem(zoom + "%", zoom); bg.add(zoomItem); menu.add(zoomItem); } setMenu(menu); } /** * Provides the ZoomMenu instance. * * @return ZoomMenu instance. */ public static ZoomMenu getInstance() { if (instance == null) { instance = new ZoomMenu(); } return instance; } /** * Set the zoom selection. * * @param zoomValue, e.g. 1, 0.25, 4. * @throws IllegalArgumentException if the parameter doesn't belong to a zoom menu item. */ public void changeZoomSelection(float zoomValue) { String selection = (int)(zoomValue*100) +"%"; for (Component comp : menu.getMenuComponents()) { JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) comp; if (menuItem.getText().equals(selection)) { menuItem.setSelected(true); return; } } throw new IllegalArgumentException("no zoom menu item found for: " + selection); } /** * Tell whether the command belongs to the zoom menu. * * @param actionCommand a menu command string. * @return true if the command is a zoom menu command, e.g. "100%", false if not. */ public static boolean isZoomMenu(String actionCommand) { if (!actionCommand.matches("^\\d+%$")) { return false; } int zoom = Integer.parseInt(actionCommand.substring(0, actionCommand.length() - 1)); return Arrays.binarySearch(ZOOMS, zoom) >= 0; } /** * Tell the current zoom scale. * * @return the current zoom scale. * @throws IllegalStateException if no zoom menu item is selected. */ public static float getZoomScale() { for (Component comp : instance.menu.getMenuComponents()) { ZoomMenuItem menuItem = (ZoomMenuItem) comp; if (menuItem.isSelected()) { return menuItem.zoom / 100f; } } throw new IllegalStateException("no zoom menu item is selected"); } public float getPageZoomScale() { return pageZoomScale; } public void setPageZoomScale(float pageZoomValue) { pageZoomScale = pageZoomValue; } public float getImageZoomScale() { return imageZoomScale; } public void setImageZoomScale(float imageZoomValue) { imageZoomScale = imageZoomValue; } /** * When a new file is loaded zoom values should be reset. * */ public void resetZoom() { setPageZoomScale(1); setImageZoomScale(1); changeZoomSelection(1); } }
debugger/src/main/java/org/apache/pdfbox/debugger/ui/ZoomMenu.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pdfbox.debugger.ui; import java.awt.Component; import java.util.Arrays; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JRadioButtonMenuItem; /** * @author Khyrul Bashar * * A singleton class that provides zoom menu which can be used to show zoom menu in the menubar. To * act upon the menu item selection user of the class must add ActionListener which will check for * the action command and act accordingly. */ public final class ZoomMenu extends MenuBase { private static class ZoomMenuItem extends JRadioButtonMenuItem { private final int zoom; ZoomMenuItem(String text, int zoom) { super(text); this.zoom = zoom; } } private float pageZoomScale = 1; private float imageZoomScale = 1; private static final int[] ZOOMS = new int[] { 25, 50, 100, 200, 400 }; private static ZoomMenu instance; private final JMenu menu; /** * Constructor. */ private ZoomMenu() { menu = new JMenu("Zoom"); ButtonGroup bg = new ButtonGroup(); for (int zoom : ZOOMS) { ZoomMenuItem zoomItem = new ZoomMenuItem(zoom + "%", zoom); bg.add(zoomItem); menu.add(zoomItem); } setMenu(menu); } /** * Provides the ZoomMenu instance. * * @return ZoomMenu instance. */ public static ZoomMenu getInstance() { if (instance == null) { instance = new ZoomMenu(); } return instance; } /** * Set the zoom selection. * * @param zoomValue, e.g. 1, 0.25, 4. * @throws IllegalArgumentException if the parameter doesn't belong to a zoom menu item. */ public void changeZoomSelection(float zoomValue) { String selection = (int)(zoomValue*100) +"%"; for (Component comp : menu.getMenuComponents()) { JRadioButtonMenuItem menuItem = (JRadioButtonMenuItem) comp; if (menuItem.getText().equals(selection)) { menuItem.setSelected(true); return; } } throw new IllegalArgumentException("no zoom menu item found for: " + selection); } /** * Tell whether the command belongs to the zoom menu. * * @param actionCommand a menu command string. * @return true if the command is a zoom menu command, e.g. "100%", false if not. */ public static boolean isZoomMenu(String actionCommand) { if (!actionCommand.matches("^\\d+%$")) { return false; } int zoom = Integer.parseInt(actionCommand.substring(0, actionCommand.length() - 1)); return Arrays.binarySearch(ZOOMS, zoom) >= 0; } /** * Tell the current zoom scale. * * @return the current zoom scale. * @throws IllegalStateException if no zoom menu item is selected. */ public static float getZoomScale() { for (Component comp : instance.menu.getMenuComponents()) { ZoomMenuItem menuItem = (ZoomMenuItem) comp; if (menuItem.isSelected()) { return menuItem.zoom / 100f; } } throw new IllegalStateException("no zoom menu item is selected"); } public float getPageZoomScale() { return pageZoomScale; } public void setPageZoomScale(float pageZoomValue) { pageZoomScale = pageZoomValue; } public float getImageZoomScale() { return imageZoomScale; } public void setImageZoomScale(float imageZoomValue) { imageZoomScale = imageZoomValue; } /** * When a new file is loaded zoom values should be reset. * */ public void resetZoom() { setPageZoomScale(1); setImageZoomScale(1); changeZoomSelection(1); } }
PDFBOX-2941: add zoom 1000 git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1773903 13f79535-47bb-0310-9956-ffa450edef68
debugger/src/main/java/org/apache/pdfbox/debugger/ui/ZoomMenu.java
PDFBOX-2941: add zoom 1000
Java
apache-2.0
ba8c7a19f08d9264542fef9e8f404220d3058b2e
0
Kurento/kurento-java,EugenioFidel/kurento-java,EugenioFidel/kurento-java,Kurento/kurento-java,Kurento/kurento-java,Kurento/kurento-java,EugenioFidel/kurento-java,EugenioFidel/kurento-java
package org.kurento.commons; import java.lang.reflect.Type; import org.kurento.commons.exception.KurentoException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; public class PropertiesManager { public static interface PropertyHolder { public String getProperty(String property); } private static Gson gson; private static PropertyHolder propertyHolder = new PropertyHolder() { @Override public String getProperty(String property) { return System.getProperty(property); } }; public static void setPropertyHolder(PropertyHolder propertyHolder) { PropertiesManager.propertyHolder = propertyHolder; } public static String getProperty(String property) { return propertyHolder.getProperty(property); } public static String getPropertyOrException(String property, String exceptionMessage) { String value = getProperty(property); if (value == null) { throw new KurentoException(exceptionMessage); } return value; } public static Address getProperty(String property, Address defaultValue) { String systemValue = propertyHolder.getProperty(property); if (systemValue == null) { return defaultValue; } else { String[] parts = systemValue.split(":"); if (parts.length == 0) { return defaultValue; } else if (parts.length == 1) { return new Address(parts[0], defaultValue.getPort()); } else { String host = parts[0]; int port; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { port = defaultValue.getPort(); } return new Address(host, port); } } } public static int getProperty(String property, int defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Integer.parseInt(systemValue) : defaultValue; } public static double getProperty(String property, double defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Double.parseDouble(systemValue) : defaultValue; } public static long getProperty(String property, long defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Integer.parseInt(systemValue) : defaultValue; } public static String getProperty(String property, String defaultValue) { String value = propertyHolder.getProperty(property); if (value != null) { return value; } else { return defaultValue; } } @SuppressWarnings("unchecked") public static <E extends Enum<E>> E getProperty(String property, E defaultValue) { String value = propertyHolder.getProperty(property); if (value != null) { return Enum.valueOf((Class<E>) defaultValue.getClass(), value.toUpperCase()); } else { return defaultValue; } } public static <T extends JsonElement> T getPropertyJson(String property, String defaultValue, Class<T> clazz) { String value = getProperty(property, defaultValue); initGson(); return gson.fromJson(value, clazz); } public static <T> T getPropertyJson(String property, String defaultValue, Type classOfT) { String value = getProperty(property, defaultValue); initGson(); return gson.fromJson(value, classOfT); } private static void initGson() { if (gson == null) { synchronized (PropertiesManager.class) { if (gson == null) { gson = new GsonBuilder().create(); } } } } public static boolean getProperty(String property, boolean defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Boolean.parseBoolean(systemValue) : defaultValue; } private static String createWithPrefix(String prefix, String property) { if (prefix == null) { return property; } else { return prefix + "." + property; } } public static int getProperty(String prefix, String property, int defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } public static String getProperty(String prefix, String property, String defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } public static Address getProperty(String prefix, String property, Address defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } }
kurento-commons/src/main/java/org/kurento/commons/PropertiesManager.java
package org.kurento.commons; import java.lang.reflect.Type; import org.kurento.commons.exception.KurentoException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; public class PropertiesManager { public static interface PropertyHolder { public String getProperty(String property); } private static Gson gson; private static PropertyHolder propertyHolder = new PropertyHolder() { @Override public String getProperty(String property) { return System.getProperty(property); } }; public static void setPropertyHolder(PropertyHolder propertyHolder) { PropertiesManager.propertyHolder = propertyHolder; } public static String getProperty(String property) { return propertyHolder.getProperty(property); } public static String getPropertyOrException(String property, String exceptionMessage) { String value = getProperty(property); if (value == null) { throw new KurentoException(exceptionMessage); } return value; } public static Address getProperty(String property, Address defaultValue) { String systemValue = propertyHolder.getProperty(property); if (systemValue == null) { return defaultValue; } else { String[] parts = systemValue.split(":"); if (parts.length == 0) { return defaultValue; } else if (parts.length == 1) { return new Address(parts[0], defaultValue.getPort()); } else { String host = parts[0]; int port; try { port = Integer.parseInt(parts[1]); } catch (NumberFormatException e) { port = defaultValue.getPort(); } return new Address(host, port); } } } public static int getProperty(String property, int defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Integer.parseInt(systemValue) : defaultValue; } public static double getProperty(String property, double defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Double.parseDouble(systemValue) : defaultValue; } public static long getProperty(String property, long defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Integer.parseInt(systemValue) : defaultValue; } public static String getProperty(String property, String defaultValue) { String value = propertyHolder.getProperty(property); if (value != null) { return value; } else { return defaultValue; } } public static <T extends JsonElement> T getPropertyJson(String property, String defaultValue, Class<T> clazz) { String value = getProperty(property, defaultValue); initGson(); return gson.fromJson(value, clazz); } public static <T> T getPropertyJson(String property, String defaultValue, Type classOfT) { String value = getProperty(property, defaultValue); initGson(); return gson.fromJson(value, classOfT); } private static void initGson() { if (gson == null) { synchronized (PropertiesManager.class) { if (gson == null) { gson = new GsonBuilder().create(); } } } } public static boolean getProperty(String property, boolean defaultValue) { String systemValue = propertyHolder.getProperty(property); return systemValue != null ? Boolean.parseBoolean(systemValue) : defaultValue; } private static String createWithPrefix(String prefix, String property) { if (prefix == null) { return property; } else { return prefix + "." + property; } } public static int getProperty(String prefix, String property, int defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } public static String getProperty(String prefix, String property, String defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } public static Address getProperty(String prefix, String property, Address defaultValue) { return getProperty(createWithPrefix(prefix, property), defaultValue); } }
Add Enums to PropertiesManager Change-Id: Id16693f4adfc282eeee35e63abc9154f78b6426c
kurento-commons/src/main/java/org/kurento/commons/PropertiesManager.java
Add Enums to PropertiesManager
Java
apache-2.0
4b1964014f311c4b80ecfdf13205ed76a17f6935
0
allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community
package org.jetbrains.plugins.textmate.language.syntax.lexer; import com.google.common.base.Joiner; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.UncheckedExecutionException; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.textmate.Constants; import org.jetbrains.plugins.textmate.language.syntax.InjectionNodeDescriptor; import org.jetbrains.plugins.textmate.language.syntax.SyntaxNodeDescriptor; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorCachingWeigher; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorWeigher; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorWeigherImpl; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateWeigh; import org.jetbrains.plugins.textmate.plist.PListValue; import org.jetbrains.plugins.textmate.plist.Plist; import org.jetbrains.plugins.textmate.regex.MatchData; import org.jetbrains.plugins.textmate.regex.RegexFacade; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.jetbrains.plugins.textmate.regex.RegexFacade.regex; public final class SyntaxMatchUtils { private static final Pattern DIGIT_GROUP_REGEX = Pattern.compile("\\\\([0-9]+)"); private static final LoadingCache<MatchKey, TextMateLexerState> CACHE = CacheBuilder.newBuilder().maximumSize(32768) .build(CacheLoader.from( key -> matchFirstUncached(Objects.requireNonNull(key).descriptor, key.line, key.position, key.priority, key.currentScope))); private final static Joiner MY_OPEN_TAGS_JOINER = Joiner.on(" ").skipNulls(); private static final TextMateSelectorWeigher mySelectorWeigher = new TextMateSelectorCachingWeigher(new TextMateSelectorWeigherImpl()); @NotNull public static TextMateLexerState matchFirst(SyntaxNodeDescriptor syntaxNodeDescriptor, String line, int position, TextMateWeigh.Priority priority, String currentScope) { try { return CACHE.get(new MatchKey(syntaxNodeDescriptor, line, position, priority, currentScope)); } catch (ExecutionException | UncheckedExecutionException e) { Throwable cause = e.getCause(); while (cause != null) { if (cause instanceof ProcessCanceledException) { throw (ProcessCanceledException)cause; } cause = cause.getCause(); } throw new RuntimeException(e); } } @NotNull private static TextMateLexerState matchFirstUncached(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull TextMateWeigh.Priority priority, @NotNull String currentScope) { TextMateLexerState resultState = TextMateLexerState.notMatched(syntaxNodeDescriptor); List<SyntaxNodeDescriptor> children = syntaxNodeDescriptor.getChildren(); for (SyntaxNodeDescriptor child : children) { resultState = moreImportantState(resultState, matchFirstChild(child, line, position, priority, currentScope)); if (resultState.matchData.matched() && resultState.matchData.offset().getStartOffset() == position) { // optimization. There cannot be anything more `important` than current state matched from the very beginning break; } } return moreImportantState(resultState, matchInjections(syntaxNodeDescriptor, line, position, currentScope)); } @NotNull private static TextMateLexerState matchInjections(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull String currentScope) { TextMateLexerState resultState = TextMateLexerState.notMatched(syntaxNodeDescriptor); List<InjectionNodeDescriptor> injections = syntaxNodeDescriptor.getInjections(); for (InjectionNodeDescriptor injection : injections) { TextMateWeigh selectorWeigh = mySelectorWeigher.weigh(injection.getSelector(), currentScope); if (selectorWeigh.weigh <= 0) { continue; } TextMateLexerState injectionState = matchFirst(injection.getSyntaxNodeDescriptor(), line, position, selectorWeigh.priority, currentScope); resultState = moreImportantState(resultState, injectionState); } return resultState; } @NotNull private static TextMateLexerState moreImportantState(@NotNull TextMateLexerState oldState, @NotNull TextMateLexerState newState) { if (!newState.matchData.matched()) { return oldState; } else if (!oldState.matchData.matched()) { return newState; } int newScore = newState.matchData.offset().getStartOffset(); int oldScore = oldState.matchData.offset().getStartOffset(); if (newScore < oldScore || newScore == oldScore && newState.priorityMatch.compareTo(oldState.priorityMatch) > 0) { if (!newState.matchData.offset().isEmpty() || oldState.matchData.offset().isEmpty() || hasBeginKey(newState)) { return newState; } } return oldState; } private static boolean hasBeginKey(@NotNull TextMateLexerState lexerState) { return lexerState.syntaxRule.getRegexAttribute(Constants.BEGIN_KEY) != null; } private static TextMateLexerState matchFirstChild(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull TextMateWeigh.Priority priority, @NotNull String currentScope) { RegexFacade matchRegex = syntaxNodeDescriptor.getRegexAttribute(Constants.MATCH_KEY); if (matchRegex != null) { return new TextMateLexerState(syntaxNodeDescriptor, matchRegex.match(line, position), priority); } RegexFacade beginRegex = syntaxNodeDescriptor.getRegexAttribute(Constants.BEGIN_KEY); if (beginRegex != null) { return new TextMateLexerState(syntaxNodeDescriptor, beginRegex.match(line, position), priority); } if (syntaxNodeDescriptor.getStringAttribute(Constants.END_KEY) != null) { return TextMateLexerState.notMatched(syntaxNodeDescriptor); } return matchFirst(syntaxNodeDescriptor, line, position, priority, currentScope); } public static List<CaptureMatchData> matchCaptures(@NotNull Plist captures, @NotNull MatchData matchData) { List<CaptureMatchData> result = new ArrayList<>(); for (Map.Entry<String, PListValue> capture : captures.entries()) { try { int index = Integer.parseInt(capture.getKey()); Plist captureDict = capture.getValue().getPlist(); String captureName = captureDict.getPlistValue(Constants.NAME_KEY, "").getString(); final TextRange offset = index < matchData.count() ? matchData.offset(index) : TextRange.EMPTY_RANGE; if (!captureName.isEmpty() && offset.getLength() > 0) { result.add(new CaptureMatchData(offset, index, captureName)); } } catch (NumberFormatException ignore) { } } return result; } public static MatchData matchStringRegex(String keyName, String line, TextMateLexerState lexerState, int linePosition) { String stringRegex = lexerState.syntaxRule.getStringAttribute(keyName); return stringRegex != null ? regex(replaceGroupsWithMatchData(stringRegex, lexerState.matchData)).match(line, linePosition) : MatchData.NOT_MATCHED; } /** * Replaces parts like \1 or \20 in patternString parameter with group captures from matchData. * <p/> * E.g. given patternString "\1-\2" and matchData consists of two groups: "first" and "second", * then patternString "first-second" will be returned. * * @param patternString source pattern * @param matchData matched data with captured groups for replacement * @return patternString with replaced group-references */ public static String replaceGroupsWithMatchData(String patternString, MatchData matchData) { Matcher matcher = DIGIT_GROUP_REGEX.matcher(patternString); StringBuilder result = new StringBuilder(); int lastPosition = 0; while (matcher.find()) { int groupIndex = StringUtil.parseInt(matcher.group(1), -1); if (groupIndex >= 0 && matchData.count() > groupIndex) { result.append(patternString, lastPosition, matcher.start()); StringUtil.escapeToRegexp(matchData.capture(groupIndex), result); lastPosition = matcher.end(); } } if (lastPosition < patternString.length()) { result.append(patternString.substring(lastPosition)); } return result.toString(); } @NotNull public static String selectorsToScope(@NotNull List<String> selectors) { return MY_OPEN_TAGS_JOINER.join(selectors); } private static class MatchKey { final SyntaxNodeDescriptor descriptor; final String line; final int position; private final TextMateWeigh.Priority priority; final String currentScope; private MatchKey(SyntaxNodeDescriptor descriptor, String line, int position, TextMateWeigh.Priority priority, String currentScope) { this.descriptor = descriptor; this.line = line; this.position = position; this.priority = priority; this.currentScope = currentScope; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchKey key = (MatchKey)o; return position == key.position && descriptor.equals(key.descriptor) && line.equals(key.line) && priority == key.priority && currentScope.equals(key.currentScope); } @Override public int hashCode() { return Objects.hash(descriptor, line, position, priority, currentScope); } } }
plugins/textmate/src/org/jetbrains/plugins/textmate/language/syntax/lexer/SyntaxMatchUtils.java
package org.jetbrains.plugins.textmate.language.syntax.lexer; import com.google.common.base.Joiner; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.util.concurrent.UncheckedExecutionException; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.textmate.Constants; import org.jetbrains.plugins.textmate.language.syntax.InjectionNodeDescriptor; import org.jetbrains.plugins.textmate.language.syntax.SyntaxNodeDescriptor; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorCachingWeigher; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorWeigher; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateSelectorWeigherImpl; import org.jetbrains.plugins.textmate.language.syntax.selector.TextMateWeigh; import org.jetbrains.plugins.textmate.plist.PListValue; import org.jetbrains.plugins.textmate.plist.Plist; import org.jetbrains.plugins.textmate.regex.MatchData; import org.jetbrains.plugins.textmate.regex.RegexFacade; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutionException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.jetbrains.plugins.textmate.regex.RegexFacade.regex; public final class SyntaxMatchUtils { private static final Pattern DIGIT_GROUP_REGEX = Pattern.compile("\\\\([0-9]+)"); private static final LoadingCache<MatchKey, TextMateLexerState> CACHE = CacheBuilder.newBuilder().maximumSize(32768) .build(CacheLoader.from( key -> matchFirstUncached(Objects.requireNonNull(key).descriptor, key.line, key.position, key.priority, key.currentScope))); private final static Joiner MY_OPEN_TAGS_JOINER = Joiner.on(" ").skipNulls(); private static final TextMateSelectorWeigher mySelectorWeigher = new TextMateSelectorCachingWeigher(new TextMateSelectorWeigherImpl()); @NotNull public static TextMateLexerState matchFirst(SyntaxNodeDescriptor syntaxNodeDescriptor, String line, int position, TextMateWeigh.Priority priority, String currentScope) { try { return CACHE.get(new MatchKey(syntaxNodeDescriptor, line, position, priority, currentScope)); } catch (ExecutionException | UncheckedExecutionException e) { Throwable cause = e.getCause(); while (cause != null) { if (cause instanceof ProcessCanceledException) { throw (ProcessCanceledException)cause; } cause = cause.getCause(); } throw new RuntimeException(e); } } @NotNull private static TextMateLexerState matchFirstUncached(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull TextMateWeigh.Priority priority, @NotNull String currentScope) { TextMateLexerState resultState = TextMateLexerState.notMatched(syntaxNodeDescriptor); List<SyntaxNodeDescriptor> children = syntaxNodeDescriptor.getChildren(); for (SyntaxNodeDescriptor child : children) { resultState = moreImportantState(resultState, matchFirstChild(child, line, position, priority, currentScope)); } return moreImportantState(resultState, matchInjections(syntaxNodeDescriptor, line, position, currentScope)); } @NotNull private static TextMateLexerState matchInjections(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull String currentScope) { TextMateLexerState resultState = TextMateLexerState.notMatched(syntaxNodeDescriptor); List<InjectionNodeDescriptor> injections = syntaxNodeDescriptor.getInjections(); for (InjectionNodeDescriptor injection : injections) { TextMateWeigh selectorWeigh = mySelectorWeigher.weigh(injection.getSelector(), currentScope); if (selectorWeigh.weigh <= 0) { continue; } TextMateLexerState injectionState = matchFirst(injection.getSyntaxNodeDescriptor(), line, position, selectorWeigh.priority, currentScope); resultState = moreImportantState(resultState, injectionState); } return resultState; } @NotNull private static TextMateLexerState moreImportantState(@NotNull TextMateLexerState oldState, @NotNull TextMateLexerState newState) { if (!newState.matchData.matched()) { return oldState; } else if (!oldState.matchData.matched()) { return newState; } int newScore = newState.matchData.offset().getStartOffset(); int oldScore = oldState.matchData.offset().getStartOffset(); if (newScore < oldScore || newScore == oldScore && newState.priorityMatch.compareTo(oldState.priorityMatch) > 0) { if (!newState.matchData.offset().isEmpty() || oldState.matchData.offset().isEmpty() || hasBeginKey(newState)) { return newState; } } return oldState; } private static boolean hasBeginKey(@NotNull TextMateLexerState lexerState) { return lexerState.syntaxRule.getRegexAttribute(Constants.BEGIN_KEY) != null; } private static TextMateLexerState matchFirstChild(@NotNull SyntaxNodeDescriptor syntaxNodeDescriptor, @NotNull String line, int position, @NotNull TextMateWeigh.Priority priority, @NotNull String currentScope) { RegexFacade matchRegex = syntaxNodeDescriptor.getRegexAttribute(Constants.MATCH_KEY); if (matchRegex != null) { return new TextMateLexerState(syntaxNodeDescriptor, matchRegex.match(line, position), priority); } RegexFacade beginRegex = syntaxNodeDescriptor.getRegexAttribute(Constants.BEGIN_KEY); if (beginRegex != null) { return new TextMateLexerState(syntaxNodeDescriptor, beginRegex.match(line, position), priority); } if (syntaxNodeDescriptor.getStringAttribute(Constants.END_KEY) != null) { return TextMateLexerState.notMatched(syntaxNodeDescriptor); } return matchFirst(syntaxNodeDescriptor, line, position, priority, currentScope); } public static List<CaptureMatchData> matchCaptures(@NotNull Plist captures, @NotNull MatchData matchData) { List<CaptureMatchData> result = new ArrayList<>(); for (Map.Entry<String, PListValue> capture : captures.entries()) { try { int index = Integer.parseInt(capture.getKey()); Plist captureDict = capture.getValue().getPlist(); String captureName = captureDict.getPlistValue(Constants.NAME_KEY, "").getString(); final TextRange offset = index < matchData.count() ? matchData.offset(index) : TextRange.EMPTY_RANGE; if (!captureName.isEmpty() && offset.getLength() > 0) { result.add(new CaptureMatchData(offset, index, captureName)); } } catch (NumberFormatException ignore) { } } return result; } public static MatchData matchStringRegex(String keyName, String line, TextMateLexerState lexerState, int linePosition) { String stringRegex = lexerState.syntaxRule.getStringAttribute(keyName); return stringRegex != null ? regex(replaceGroupsWithMatchData(stringRegex, lexerState.matchData)).match(line, linePosition) : MatchData.NOT_MATCHED; } /** * Replaces parts like \1 or \20 in patternString parameter with group captures from matchData. * <p/> * E.g. given patternString "\1-\2" and matchData consists of two groups: "first" and "second", * then patternString "first-second" will be returned. * * @param patternString source pattern * @param matchData matched data with captured groups for replacement * @return patternString with replaced group-references */ public static String replaceGroupsWithMatchData(String patternString, MatchData matchData) { Matcher matcher = DIGIT_GROUP_REGEX.matcher(patternString); StringBuilder result = new StringBuilder(); int lastPosition = 0; while (matcher.find()) { int groupIndex = StringUtil.parseInt(matcher.group(1), -1); if (groupIndex >= 0 && matchData.count() > groupIndex) { result.append(patternString, lastPosition, matcher.start()); StringUtil.escapeToRegexp(matchData.capture(groupIndex), result); lastPosition = matcher.end(); } } if (lastPosition < patternString.length()) { result.append(patternString.substring(lastPosition)); } return result.toString(); } @NotNull public static String selectorsToScope(@NotNull List<String> selectors) { return MY_OPEN_TAGS_JOINER.join(selectors); } private static class MatchKey { final SyntaxNodeDescriptor descriptor; final String line; final int position; private final TextMateWeigh.Priority priority; final String currentScope; private MatchKey(SyntaxNodeDescriptor descriptor, String line, int position, TextMateWeigh.Priority priority, String currentScope) { this.descriptor = descriptor; this.line = line; this.position = position; this.priority = priority; this.currentScope = currentScope; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MatchKey key = (MatchKey)o; return position == key.position && descriptor.equals(key.descriptor) && line.equals(key.line) && priority == key.priority && currentScope.equals(key.currentScope); } @Override public int hashCode() { return Objects.hash(descriptor, line, position, priority, currentScope); } } }
TextMate: optimization GitOrigin-RevId: 06ca75ff0412647cb3278b66b2516e01b79f41f3
plugins/textmate/src/org/jetbrains/plugins/textmate/language/syntax/lexer/SyntaxMatchUtils.java
TextMate: optimization
Java
apache-2.0
075d8d29f7617e2f298f6380f1d62c03b1e1b674
0
Sivaramvt/Slice
/*- * #%L * Slice - Mapper * %% * Copyright (C) 2012 Cognifide Limited * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.cognifide.slice.mapper; import com.cognifide.slice.mapper.api.Mapper; import com.cognifide.slice.mapper.api.processor.FieldPostProcessor; import com.cognifide.slice.mapper.api.processor.FieldProcessor; import com.cognifide.slice.mapper.impl.postprocessor.EscapeValuePostProcessor; import com.cognifide.slice.mapper.impl.processor.BooleanFieldProcessor; import com.cognifide.slice.mapper.impl.processor.ChildrenFieldProcessor; import com.cognifide.slice.mapper.impl.processor.DefaultFieldProcessor; import com.cognifide.slice.mapper.impl.processor.EnumFieldProcessor; import com.cognifide.slice.mapper.impl.processor.ListFieldProcessor; import com.cognifide.slice.mapper.impl.processor.SliceReferenceFieldProcessor; import com.cognifide.slice.mapper.impl.processor.SliceResourceFieldProcessor; import com.google.inject.Inject; import java.util.Deque; import java.util.LinkedList; /** * MapperBuilder replaced previous MapperFactory. It allows to set Field Processors and Post Processors and * then build instance of {@link Mapper} * * @author maciej.matuszewski */ public final class MapperBuilder { private final Deque<FieldProcessor> processors = new LinkedList<FieldProcessor>(); private final Deque<FieldPostProcessor> postProcessors = new LinkedList<FieldPostProcessor>(); @Inject private SliceResourceFieldProcessor sliceResourceFieldProcessor; @Inject private SliceReferenceFieldProcessor sliceReferenceFieldProcessor; @Inject private ChildrenFieldProcessor childrenFieldProcessor; /** * This method creates new instance of {@link GenericSlingMapper}. Field processors should be added before * this method. * * @return */ public Mapper build() { return new GenericSlingMapper(this); } /** * Adds {@link FieldProcessor} at the beginning of processors list. * * @param fieldProcessor * @return */ public MapperBuilder addFieldProcessor(FieldProcessor fieldProcessor) { processors.addFirst(fieldProcessor); return this; } /** * Adds {@link FieldPostProcessor} at the beginning of postProcessors list. * * @param fieldPostProcessor * @return */ public MapperBuilder addFieldPostProcessor(FieldPostProcessor fieldPostProcessor) { postProcessors.addFirst(fieldPostProcessor); return this; } /** * Adds default processors and post processors * * @return */ public MapperBuilder addDefaultSliceProcessors() { addSliceProcessors(); addSlicePostProcessors(); return this; } /** * Adds default processors * * @return */ public MapperBuilder addSliceProcessors() { processors.add(sliceReferenceFieldProcessor); // @SliceReference processors.add(sliceResourceFieldProcessor); // @SliceResource processors.add(childrenFieldProcessor); // child models @Children processors.add(new ListFieldProcessor()); // Subclasses of Collection<?> and arrays processors.add(new BooleanFieldProcessor()); // booleans processors.add(new EnumFieldProcessor()); // enums processors.add(new DefaultFieldProcessor()); // any other fields return this; } /** * Adds default post-processors * * @return */ public MapperBuilder addSlicePostProcessors() { postProcessors.add(new EscapeValuePostProcessor()); return this; } Deque<FieldProcessor> getProcessors() { return processors; } Deque<FieldPostProcessor> getPostProcessors() { return postProcessors; } }
slice-mapper/src/main/java/com/cognifide/slice/mapper/MapperBuilder.java
/*- * #%L * Slice - Mapper * %% * Copyright (C) 2012 Cognifide Limited * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.cognifide.slice.mapper; import com.cognifide.slice.mapper.api.Mapper; import com.cognifide.slice.mapper.api.processor.FieldPostProcessor; import com.cognifide.slice.mapper.api.processor.FieldProcessor; import com.cognifide.slice.mapper.impl.postprocessor.EscapeValuePostProcessor; import com.cognifide.slice.mapper.impl.processor.BooleanFieldProcessor; import com.cognifide.slice.mapper.impl.processor.ChildrenFieldProcessor; import com.cognifide.slice.mapper.impl.processor.DefaultFieldProcessor; import com.cognifide.slice.mapper.impl.processor.EnumFieldProcessor; import com.cognifide.slice.mapper.impl.processor.ListFieldProcessor; import com.cognifide.slice.mapper.impl.processor.SliceReferenceFieldProcessor; import com.cognifide.slice.mapper.impl.processor.SliceResourceFieldProcessor; import com.google.inject.Inject; import java.util.Deque; import java.util.LinkedList; /** * MapperBuilder replaced previous MapperFactory. It allows to set Field Processors and Post Processors and * then build instance of {@link Mapper} * * @author maciej.matuszewski */ public final class MapperBuilder { private final Deque<FieldProcessor> processors = new LinkedList<FieldProcessor>(); private final Deque<FieldPostProcessor> postProcessors = new LinkedList<FieldPostProcessor>(); @Inject private SliceResourceFieldProcessor sliceResourceFieldProcessor; @Inject private SliceReferenceFieldProcessor sliceReferenceFieldProcessor; @Inject private ChildrenFieldProcessor childrenFieldProcessor; /** * This method creates new instance of {@link GenericSlingMapper}. Field processors should be added before * this method. * * @return */ public Mapper build() { return new GenericSlingMapper(this); } /** * Adds {@link FieldProcessor} at the beginning of processors list. * * @param fieldProcessor * @return */ public MapperBuilder addFieldProcessor(FieldProcessor fieldProcessor) { processors.addFirst(fieldProcessor); return this; } /** * Adds {@link FieldPostProcessor} at the beginning of postProcessors list. * * @param fieldPostProcessor * @return */ public MapperBuilder addFieldPostProcessor(FieldPostProcessor fieldPostProcessor) { postProcessors.addFirst(fieldPostProcessor); return this; } /** * Adds default processors and post processors - the same that was added in SlingMapperFactory * * @return */ public MapperBuilder addDefaultSliceProcessors() { processors.add(sliceReferenceFieldProcessor); // @SliceReference processors.add(sliceResourceFieldProcessor); // @SliceResource processors.add(childrenFieldProcessor); // child models @Children processors.add(new ListFieldProcessor()); // Subclasses of Collection<?> and arrays processors.add(new BooleanFieldProcessor()); // booleans processors.add(new EnumFieldProcessor()); // enums processors.add(new DefaultFieldProcessor()); // any other fields postProcessors.add(new EscapeValuePostProcessor()); return this; } Deque<FieldProcessor> getProcessors() { return processors; } Deque<FieldPostProcessor> getPostProcessors() { return postProcessors; } }
Split MapperBuilder#addDefaultSliceProcessors
slice-mapper/src/main/java/com/cognifide/slice/mapper/MapperBuilder.java
Split MapperBuilder#addDefaultSliceProcessors
Java
apache-2.0
8bff5611d8840c3dca2b5661169e5ddc3936b564
0
tdiesler/camel,tadayosi/camel,CodeSmell/camel,nicolaferraro/camel,alvinkwekel/camel,ullgren/camel,CodeSmell/camel,nikhilvibhav/camel,cunningt/camel,tdiesler/camel,christophd/camel,apache/camel,mcollovati/camel,nicolaferraro/camel,tdiesler/camel,gnodet/camel,adessaigne/camel,apache/camel,pax95/camel,ullgren/camel,alvinkwekel/camel,gnodet/camel,DariusX/camel,tdiesler/camel,CodeSmell/camel,DariusX/camel,cunningt/camel,cunningt/camel,christophd/camel,DariusX/camel,adessaigne/camel,pax95/camel,tadayosi/camel,alvinkwekel/camel,mcollovati/camel,apache/camel,ullgren/camel,christophd/camel,adessaigne/camel,cunningt/camel,nicolaferraro/camel,pmoerenhout/camel,tadayosi/camel,apache/camel,cunningt/camel,pmoerenhout/camel,apache/camel,christophd/camel,nicolaferraro/camel,zregvart/camel,adessaigne/camel,gnodet/camel,DariusX/camel,pmoerenhout/camel,tdiesler/camel,adessaigne/camel,pax95/camel,nikhilvibhav/camel,pax95/camel,zregvart/camel,cunningt/camel,tadayosi/camel,alvinkwekel/camel,tadayosi/camel,pax95/camel,apache/camel,zregvart/camel,pmoerenhout/camel,christophd/camel,nikhilvibhav/camel,gnodet/camel,nikhilvibhav/camel,pax95/camel,zregvart/camel,mcollovati/camel,ullgren/camel,mcollovati/camel,tdiesler/camel,gnodet/camel,tadayosi/camel,pmoerenhout/camel,adessaigne/camel,CodeSmell/camel,pmoerenhout/camel,christophd/camel
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf; import org.w3c.dom.Node; import org.apache.camel.Exchange; import org.apache.camel.ExtendedExchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.converter.stream.CachedOutputStream; import org.apache.camel.spi.Synchronization; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; //Modified from https://issues.apache.org/jira/secure/attachment/12730161/0001-CAMEL-8419-Camel-StreamCache-does-not-work-with-CXF-.patch public class CxfConsumerStreamCacheTest extends CamelTestSupport { protected static final String REQUEST_MESSAGE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"test/service\">" + "<soapenv:Header/><soapenv:Body><ser:ping/></soapenv:Body></soapenv:Envelope>"; protected static final String RESPONSE_MESSAGE_BEGINE = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><pong xmlns=\"test/service\""; protected static final String RESPONSE_MESSAGE_END = "/></soap:Body></soap:Envelope>"; protected static final String RESPONSE = "<pong xmlns=\"test/service\"/>"; protected final String simpleEndpointAddress = "http://localhost:" + CXFTestSupport.getPort1() + "/" + getClass().getSimpleName() + "/test"; protected final String simpleEndpointURI = "cxf://" + simpleEndpointAddress + "?synchronous=" + isSynchronous() + "&serviceClass=org.apache.camel.component.cxf.ServiceProvider&dataFormat=PAYLOAD"; @Override public boolean isCreateCamelContextPerClass() { return true; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { getContext().setStreamCaching(true); getContext().getStreamCachingStrategy().setSpoolThreshold(1L); errorHandler(noErrorHandler()); from(getFromEndpointUri()).process(new Processor() { public void process(final Exchange exchange) throws Exception { Message in = exchange.getIn(); Node node = in.getBody(Node.class); assertNotNull(node); CachedOutputStream cos = new CachedOutputStream(exchange); cos.write(RESPONSE.getBytes("UTF-8")); cos.close(); exchange.getOut().setBody(cos.newStreamCache()); exchange.adapt(ExtendedExchange.class).addOnCompletion(new Synchronization() { @Override public void onComplete(Exchange exchange) { template.sendBody("mock:onComplete", ""); } @Override public void onFailure(Exchange exchange) { } }); } }); } }; } @Test public void testInvokingServiceFromHttpCompnent() throws Exception { MockEndpoint mock = getMockEndpoint("mock:onComplete"); mock.expectedMessageCount(2); // call the service with right post message String response = template.requestBody(simpleEndpointAddress, REQUEST_MESSAGE, String.class); assertTrue("Get a wrong response ", response.startsWith(RESPONSE_MESSAGE_BEGINE)); assertTrue("Get a wrong response ", response.endsWith(RESPONSE_MESSAGE_END)); try { template.requestBody(simpleEndpointAddress, null, String.class); fail("Excpetion to get exception here"); } catch (Exception ex) { // do nothing here } response = template.requestBody(simpleEndpointAddress, REQUEST_MESSAGE, String.class); assertTrue("Get a wrong response ", response.startsWith(RESPONSE_MESSAGE_BEGINE)); assertTrue("Get a wrong response ", response.endsWith(RESPONSE_MESSAGE_END)); mock.assertIsSatisfied(); } protected String getFromEndpointUri() { return simpleEndpointURI; } protected boolean isSynchronous() { return false; } }
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerStreamCacheTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.cxf; import org.apache.camel.ExtendedExchange; import org.w3c.dom.Node; import org.apache.camel.Exchange; import org.apache.camel.Message; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.converter.stream.CachedOutputStream; import org.apache.camel.spi.Synchronization; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; //Modified from https://issues.apache.org/jira/secure/attachment/12730161/0001-CAMEL-8419-Camel-StreamCache-does-not-work-with-CXF-.patch public class CxfConsumerStreamCacheTest extends CamelTestSupport { protected static final String REQUEST_MESSAGE = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"test/service\">" + "<soapenv:Header/><soapenv:Body><ser:ping/></soapenv:Body></soapenv:Envelope>"; protected static final String RESPONSE_MESSAGE_BEGINE = "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body><pong xmlns=\"test/service\""; protected static final String RESPONSE_MESSAGE_END = "/></soap:Body></soap:Envelope>"; protected static final String RESPONSE = "<pong xmlns=\"test/service\"/>"; protected final String simpleEndpointAddress = "http://localhost:" + CXFTestSupport.getPort1() + "/" + getClass().getSimpleName() + "/test"; protected final String simpleEndpointURI = "cxf://" + simpleEndpointAddress + "?synchronous=" + isSynchronous() + "&serviceClass=org.apache.camel.component.cxf.ServiceProvider&dataFormat=PAYLOAD"; @Override public boolean isCreateCamelContextPerClass() { return true; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { getContext().setStreamCaching(true); getContext().getStreamCachingStrategy().setSpoolThreshold(1L); errorHandler(noErrorHandler()); from(getFromEndpointUri()).process(new Processor() { public void process(final Exchange exchange) throws Exception { Message in = exchange.getIn(); Node node = in.getBody(Node.class); assertNotNull(node); CachedOutputStream cos = new CachedOutputStream(exchange); cos.write(RESPONSE.getBytes("UTF-8")); cos.close(); exchange.getOut().setBody(cos.newStreamCache()); exchange.adapt(ExtendedExchange.class).addOnCompletion(new Synchronization() { @Override public void onComplete(Exchange exchange) { template.sendBody("mock:onComplete", ""); } @Override public void onFailure(Exchange exchange) { } }); } }); } }; } @Test public void testInvokingServiceFromHttpCompnent() throws Exception { MockEndpoint mock = getMockEndpoint("mock:onComplete"); mock.expectedMessageCount(2); // call the service with right post message String response = template.requestBody(simpleEndpointAddress, REQUEST_MESSAGE, String.class); assertTrue("Get a wrong response ", response.startsWith(RESPONSE_MESSAGE_BEGINE)); assertTrue("Get a wrong response ", response.endsWith(RESPONSE_MESSAGE_END)); try { template.requestBody(simpleEndpointAddress, null, String.class); fail("Excpetion to get exception here"); } catch (Exception ex) { // do nothing here } response = template.requestBody(simpleEndpointAddress, REQUEST_MESSAGE, String.class); assertTrue("Get a wrong response ", response.startsWith(RESPONSE_MESSAGE_BEGINE)); assertTrue("Get a wrong response ", response.endsWith(RESPONSE_MESSAGE_END)); mock.assertIsSatisfied(); } protected String getFromEndpointUri() { return simpleEndpointURI; } protected boolean isSynchronous() { return false; } }
Camel-CXF: Fixed CS
components/camel-cxf/src/test/java/org/apache/camel/component/cxf/CxfConsumerStreamCacheTest.java
Camel-CXF: Fixed CS
Java
apache-2.0
71952848c6fac8d9105e5cf08db7fb76fb77cf5c
0
Carbonado/CarbonadoTestSuite
/* * Copyright 2008 Amazon Technologies, Inc. or its affiliates. * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks * of Amazon Technologies, Inc. or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.amazon.carbonado.spi; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import junit.framework.TestCase; import junit.framework.TestSuite; import com.amazon.carbonado.IsolationLevel; import com.amazon.carbonado.Transaction; /** * * * @author Brian S O'Neill */ public class TestTransactionManager extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTransactionManager.class); } TM mTxnMgr; public TestTransactionManager(String name) { super(name); } protected void setUp() { mTxnMgr = new TM(); } public void testAttachDetach() throws Exception { Transaction txn = mTxnMgr.localScope().enter(null); // This batch of tests just ensures no IllegalStateExceptions are thrown. { // Should do nothing. txn.attach(); // Should detach. txn.detach(); // Should do nothing. txn.detach(); // Should attach. txn.attach(); } // Set up for multi-threaded tests. ExecutorService es = Executors.newSingleThreadExecutor(); final Transaction txn2 = es.submit(new Callable<Transaction>() { public Transaction call() { return mTxnMgr.localScope().enter(null); } }).get(); try { txn2.attach(); fail(); } catch (IllegalStateException e) { } try { txn2.detach(); fail(); } catch (IllegalStateException e) { } txn.detach(); try { txn2.attach(); fail(); } catch (IllegalStateException e) { } es.submit(new Runnable() { public void run() { txn2.detach(); } }).get(); txn2.attach(); txn2.detach(); txn2.attach(); try { txn.attach(); fail(); } catch (IllegalStateException e) { } txn.detach(); txn2.exit(); try { txn.attach(); fail(); } catch (IllegalStateException e) { } txn.detach(); txn2.detach(); txn.detach(); txn.attach(); txn.detach(); es.shutdown(); } private static class Txn { } private static class TM extends TransactionManager<Txn> { protected IsolationLevel selectIsolationLevel(Transaction parent, IsolationLevel level) { return IsolationLevel.READ_UNCOMMITTED; } protected boolean supportsForUpdate() { return true; } protected Txn createTxn(Txn parent, IsolationLevel level) { return new Txn(); } protected boolean commitTxn(Txn txn) { return false; } protected void abortTxn(Txn txn) { } } }
src/test/java/com/amazon/carbonado/spi/TestTransactionManager.java
/* * Copyright 2008 Amazon Technologies, Inc. or its affiliates. * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks * of Amazon Technologies, Inc. or its affiliates. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.amazon.carbonado.spi; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import junit.framework.TestCase; import junit.framework.TestSuite; import com.amazon.carbonado.IsolationLevel; import com.amazon.carbonado.Transaction; /** * * * @author Brian S O'Neill */ public class TestTransactionManager extends TestCase { public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static TestSuite suite() { return new TestSuite(TestTransactionManager.class); } TM mTxnMgr; public TestTransactionManager(String name) { super(name); } protected void setUp() { mTxnMgr = new TM(); } public void testAttachDetach() throws Exception { Transaction txn = mTxnMgr.localScope().enter(null); // This batch of tests just ensures no IllegalStateExceptions are thrown. { // Should do nothing. txn.attach(); // Should detach. txn.detach(); // Should do nothing. txn.detach(); // Should attach. txn.attach(); } // Set up for multi-threaded tests. ExecutorService es = Executors.newSingleThreadExecutor(); Transaction txn2 = es.submit(new Callable<Transaction>() { public Transaction call() { return mTxnMgr.localScope().enter(null); } }).get(); try { txn2.attach(); fail(); } catch (IllegalStateException e) { } try { txn2.detach(); fail(); } catch (IllegalStateException e) { } txn.detach(); txn2.attach(); txn2.detach(); txn2.attach(); try { txn.attach(); fail(); } catch (IllegalStateException e) { } try { txn.detach(); fail(); } catch (IllegalStateException e) { } txn2.exit(); try { txn.attach(); fail(); } catch (IllegalStateException e) { } try { txn.detach(); fail(); } catch (IllegalStateException e) { } txn2.detach(); txn.detach(); txn.attach(); txn.detach(); es.shutdown(); } private static class Txn { } private static class TM extends TransactionManager<Txn> { protected IsolationLevel selectIsolationLevel(Transaction parent, IsolationLevel level) { return IsolationLevel.READ_UNCOMMITTED; } protected boolean supportsForUpdate() { return true; } protected Txn createTxn(Txn parent, IsolationLevel level) { return new Txn(); } protected boolean commitTxn(Txn txn) { return false; } protected void abortTxn(Txn txn) { } } }
More fixes for bug that allowed a transaction to be attached to multiple threads.
src/test/java/com/amazon/carbonado/spi/TestTransactionManager.java
More fixes for bug that allowed a transaction to be attached to multiple threads.
Java
apache-2.0
442b4853f32bf74dcc88bb45c5f76fdbc08990ac
0
remcomokveld/CastNotifications
package nl.rmokveld.castnotifications; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import com.google.android.gms.cast.MediaInfo; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class CastNotification implements Parcelable { public static final int STATE_NORMAL = 0; public static final int STATE_CONNECTING = 1; public static final String TABLE_NAME = "Notifications"; static final String COL_ID = "id"; private static final String COL_TITLE = "title"; private static final String COL_TEXT = "text"; private static final String COL_MEDIA_INFO = "media_info"; static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COL_ID + " INTEGER PRIMARY KEY," + COL_TITLE + " TEXT," + COL_TEXT + " TEXT," + COL_MEDIA_INFO + " TEXT);"; private final int mId; private final String mTitle, mContentText; private final MediaInfo mMediaInfo; @State private int mState = STATE_NORMAL; private String mDeviceName; public CastNotification(int id, String title, String contentText, @NonNull MediaInfo mediaInfo) { mId = id; mTitle = title; mContentText = contentText; mMediaInfo = mediaInfo; } public CastNotification(Cursor cursor) { mId = cursor.getInt(cursor.getColumnIndexOrThrow(COL_ID)); mTitle = cursor.getString(cursor.getColumnIndexOrThrow(COL_TITLE)); mContentText = cursor.getString(cursor.getColumnIndexOrThrow(COL_TEXT)); mMediaInfo = CastNotificationManager.getInstance().getMediaInfoSerializer().toMediaInfo(cursor.getString(cursor.getColumnIndexOrThrow(COL_MEDIA_INFO))); } protected CastNotification(Parcel in) { mId = in.readInt(); mTitle = in.readString(); mContentText = in.readString(); //noinspection ResourceType mState = in.readInt(); mDeviceName = in.readString(); mMediaInfo = CastNotificationManager.getInstance().getMediaInfoSerializer().toMediaInfo(in.readString()); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mId); dest.writeString(mTitle); dest.writeString(mContentText); dest.writeInt(mState); dest.writeString(mDeviceName); dest.writeString(CastNotificationManager.getInstance().getMediaInfoSerializer().toJson(mMediaInfo)); } @Override public int describeContents() { return 0; } public static final Creator<CastNotification> CREATOR = new Creator<CastNotification>() { @Override public CastNotification createFromParcel(Parcel in) { return new CastNotification(in); } @Override public CastNotification[] newArray(int size) { return new CastNotification[size]; } }; public String getTitle() { return mTitle; } public String getContentText() { return mContentText; } public MediaInfo getMediaInfo() { return mMediaInfo; } public int getId() { return mId; } public void setState(@State int state, String deviceName) { mState = state; mDeviceName = deviceName; } @State public int getState() { return mState; } public String getDeviceName() { return mDeviceName; } public ContentValues toContentValues() { ContentValues contentValues = new ContentValues(); contentValues.put(COL_ID, mId); contentValues.put(COL_TITLE, mTitle); contentValues.put(COL_TEXT, mContentText); contentValues.put(COL_MEDIA_INFO, CastNotificationManager.getInstance().getMediaInfoSerializer().toJson(mMediaInfo)); return contentValues; } @IntDef({STATE_NORMAL, STATE_CONNECTING}) @Retention(RetentionPolicy.SOURCE) @interface State { } }
library/src/main/java/nl/rmokveld/castnotifications/CastNotification.java
package nl.rmokveld.castnotifications; import android.content.ContentValues; import android.database.Cursor; import android.support.annotation.IntDef; import android.support.annotation.NonNull; import com.google.android.gms.cast.MediaInfo; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class CastNotification { public static final int STATE_NORMAL = 0; public static final int STATE_CONNECTING = 1; public static final String TABLE_NAME = "Notifications"; static final String COL_ID = "id"; private static final String COL_TITLE = "title"; private static final String COL_TEXT = "text"; private static final String COL_MEDIA_INFO = "media_info"; static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + COL_ID + " INTEGER PRIMARY KEY," + COL_TITLE + " TEXT," + COL_TEXT + " TEXT," + COL_MEDIA_INFO + " TEXT);"; private final int mId; private final String mTitle, mContentText; private final MediaInfo mMediaInfo; @State private int mState = STATE_NORMAL; private String mDeviceName; public CastNotification(int id, String title, String contentText, @NonNull MediaInfo mediaInfo) { mId = id; mTitle = title; mContentText = contentText; mMediaInfo = mediaInfo; } public CastNotification(Cursor cursor) { mId = cursor.getInt(cursor.getColumnIndexOrThrow(COL_ID)); mTitle = cursor.getString(cursor.getColumnIndexOrThrow(COL_TITLE)); mContentText = cursor.getString(cursor.getColumnIndexOrThrow(COL_TEXT)); mMediaInfo = CastNotificationManager.getInstance().getMediaInfoSerializer().toMediaInfo(cursor.getString(cursor.getColumnIndexOrThrow(COL_MEDIA_INFO))); } public String getTitle() { return mTitle; } public String getContentText() { return mContentText; } public MediaInfo getMediaInfo() { return mMediaInfo; } public int getId() { return mId; } public void setState(@State int state, String deviceName) { mState = state; mDeviceName = deviceName; } @State public int getState() { return mState; } public String getDeviceName() { return mDeviceName; } public ContentValues toContentValues() { ContentValues contentValues = new ContentValues(); contentValues.put(COL_ID, mId); contentValues.put(COL_TITLE, mTitle); contentValues.put(COL_TEXT, mContentText); contentValues.put(COL_MEDIA_INFO, CastNotificationManager.getInstance().getMediaInfoSerializer().toJson(mMediaInfo)); return contentValues; } @IntDef({STATE_NORMAL, STATE_CONNECTING}) @Retention(RetentionPolicy.SOURCE) @interface State { } }
make CastNotification Parcelable
library/src/main/java/nl/rmokveld/castnotifications/CastNotification.java
make CastNotification Parcelable
Java
bsd-2-clause
41c28ffb42513bd43b759642e6e36ee87ce08238
0
magneticbear/scala1_android
package com.magneticbear.scala1; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; public class Splash extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Timer splashtimer = new Timer(); splashtimer.schedule(new TimerTask() { @Override public void run() { Intent intent = new Intent(getBaseContext(), Home.class); startActivity(intent); finish(); } }, 2000); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_splash, menu); return true; } }
src/com/magneticbear/scala1/Splash.java
package com.magneticbear.scala1; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class Splash extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_splash, menu); return true; } }
hold splash for 2sec then go to home
src/com/magneticbear/scala1/Splash.java
hold splash for 2sec then go to home
Java
bsd-3-clause
dcc506ff697b8360c766a317785d3d05f515e409
0
Clunker5/tregmine-2.0,EmilHernvall/tregmine,EmilHernvall/tregmine,EmilHernvall/tregmine,Clunker5/tregmine-2.0
package info.tregmine.listeners; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.api.Zone; import info.tregmine.api.lore.Created; import info.tregmine.currency.Wallet; import info.tregmine.database.ConnectionPool; import info.tregmine.quadtree.Point; import info.tregmine.zones.Lot; import info.tregmine.zones.ZoneWorld; import info.tregmine.zones.ZonesPlugin; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; public class ZoneBlockListener implements Listener { private final ZonesPlugin plugin; private final Tregmine tregmine; public ZoneBlockListener(ZonesPlugin instance) { this.plugin = instance; this.tregmine = instance.tregmine; } public void mineForTreg(BlockBreakEvent event) { if(event.isCancelled()) { return; } TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (event.getBlock().getType().equals(Material.SPONGE)) { if(!event.getPlayer().isOp()) { event.setCancelled(true); return; } } if (event.getPlayer().getItemInHand().equals(Material.PAPER)) { ItemStack paper = player.getItemInHand(); ItemMeta papermeta = paper.getItemMeta(); if (papermeta.hasDisplayName()) { player.sendMessage("NAME: " + papermeta.getDisplayName()); } // if (Created.valueOf(item).equals(Created.PURCHASED)) { // player.sendMessage("KOPT"); // } // List<String> lore = new ArrayList<String>(); // lore.add(Created.PURCHASED.toColorString()); // TregminePlayer p = this.getPlayer(player); // lore.add(ChatColor.WHITE + "by: " + p.getName() ); // lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" ); // meta.setLore(lore); // meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon"); event.setCancelled(true); return; } if (player.getGameMode().equals(GameMode.CREATIVE)) { return; } if (player.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH)) { return; } if (player.getItemInHand().containsEnchantment(Enchantment.LOOT_BONUS_BLOCKS)) { return; } for (ItemStack item : event.getBlock().getDrops() ) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); String sql = "SELECT value FROM items_destroyvalue WHERE itemid = ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, event.getBlock().getTypeId()); stmt.execute(); rs = stmt.getResultSet(); if (rs.first() ) { event.setCancelled(true); event.getBlock().setType(Material.AIR); ItemStack drop = new ItemStack(item.getType(), item.getAmount(), item.getData().getData()); ItemMeta meta = drop.getItemMeta(); item.setType(Material.AIR); if (this.tregmine.blockStats.isPlaced(event.getBlock())) { } else { Wallet wallet = new Wallet (player.getName()); wallet.add(rs.getInt("value")); } List<String> lore = new ArrayList<String>(); lore.add(info.tregmine.api.lore.Created.MINED.toColorString()); lore.add(ChatColor.WHITE + "by: " + player.getChatName()); lore.add(ChatColor.WHITE + "Value: "+ rs.getInt("value") + " Treg" ); lore.add(ChatColor.WHITE + "World: "+ event.getBlock().getWorld().getName()); meta.setLore(lore); drop.setItemMeta(meta); event.getBlock().getWorld().dropItem(event.getBlock().getLocation(), drop); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } } @EventHandler public void onBlockBreak (BlockBreakEvent event) { TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (player.isAdmin()) { mineForTreg(event); return; } ZoneWorld world = plugin.getWorld(player.getWorld()); Block block = event.getBlock(); Location location = block.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.getCurrentZone(); if (currentZone == null || !currentZone.contains(pos)) { currentZone = world.findZone(pos); player.setCurrentZone(currentZone); } if (currentZone != null) { Zone.Permission perm = currentZone.getUser(player.getName()); Lot lot = world.findLot(pos); if (lot != null) { if (perm != Zone.Permission.Owner && !lot.isOwner(player.getName())) { player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in lot " + lot.getName() + "."); event.setCancelled(true); return; } mineForTreg(event); return; } // if everyone is allowed to build in this zone... if (currentZone.getDestroyDefault()) { // ...the only people that can't build are those that are banned if (perm != null && perm == Zone.Permission.Banned) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are banned from " + currentZone.getName() + "."); } } // if this zone has limited building privileges... else { // ...we only allow builders and owners to make changes. if (perm == null || (perm != Zone.Permission.Maker && perm != Zone.Permission.Owner)) { player.setFireTicks(50); event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in " + currentZone.getName() + "."); } } } mineForTreg(event); } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (player.isAdmin()) { return; } ZoneWorld world = plugin.getWorld(player.getWorld()); Block block = event.getBlock(); Location location = block.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.getCurrentZone(); if (currentZone == null || !currentZone.contains(pos)) { currentZone = world.findZone(pos); player.setCurrentZone(currentZone); } if (currentZone != null) { Zone.Permission perm = currentZone.getUser(player.getName()); Lot lot = world.findLot(pos); if (lot != null) { if (perm != Zone.Permission.Owner && !lot.isOwner(player.getName())) { player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in lot " + lot.getName() + "."); event.setCancelled(true); return; } // we should only get here if the event is allowed, in which case we don't need // any more checks. return; } // if everyone is allowed to build in this zone... if (currentZone.getPlaceDefault()) { // ...the only people that can't build are those that are banned if (perm != null && perm == Zone.Permission.Banned) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are banned from " + currentZone.getName() + "."); } } // if this zone has limited building privileges... else { // ...we only allow builders and owners to make changes. if (perm == null || (perm != Zone.Permission.Maker && perm != Zone.Permission.Owner)) { player.setFireTicks(50); event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to place blocks in " + currentZone.getName() + "."); } } } } }
Zones/src/info/tregmine/listeners/ZoneBlockListener.java
package info.tregmine.listeners; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import info.tregmine.Tregmine; import info.tregmine.api.TregminePlayer; import info.tregmine.api.Zone; import info.tregmine.api.lore.Created; import info.tregmine.currency.Wallet; import info.tregmine.database.ConnectionPool; import info.tregmine.quadtree.Point; import info.tregmine.zones.Lot; import info.tregmine.zones.ZoneWorld; import info.tregmine.zones.ZonesPlugin; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; public class ZoneBlockListener implements Listener { private final ZonesPlugin plugin; private final Tregmine tregmine; public ZoneBlockListener(ZonesPlugin instance) { this.plugin = instance; this.tregmine = instance.tregmine; } public void mineForTreg(BlockBreakEvent event) { if(event.isCancelled()) { return; } TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (event.getBlock().getType().equals(Material.SPONGE)) { if(!event.getPlayer().isOp()) { event.setCancelled(true); return; } } if (event.getPlayer().getItemInHand().equals(Material.PAPER)) { ItemStack paper = player.getItemInHand(); ItemMeta papermeta = paper.getItemMeta(); player.sendMessage("NAME: " + papermeta.getDisplayName()); // if (Created.valueOf(item).equals(Created.PURCHASED)) { // player.sendMessage("KOPT"); // } // List<String> lore = new ArrayList<String>(); // lore.add(Created.PURCHASED.toColorString()); // TregminePlayer p = this.getPlayer(player); // lore.add(ChatColor.WHITE + "by: " + p.getName() ); // lore.add(ChatColor.WHITE + "Value: 25.000" + ChatColor.WHITE + " Tregs" ); // meta.setLore(lore); // meta.setDisplayName(ChatColor.GREEN + "DIRT -> SPONG Coupon"); event.setCancelled(true); return; } if (player.getGameMode().equals(GameMode.CREATIVE)) { return; } if (player.getItemInHand().containsEnchantment(Enchantment.SILK_TOUCH)) { return; } if (player.getItemInHand().containsEnchantment(Enchantment.LOOT_BONUS_BLOCKS)) { return; } for (ItemStack item : event.getBlock().getDrops() ) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = ConnectionPool.getConnection(); String sql = "SELECT value FROM items_destroyvalue WHERE itemid = ?"; stmt = conn.prepareStatement(sql); stmt.setLong(1, event.getBlock().getTypeId()); stmt.execute(); rs = stmt.getResultSet(); if (rs.first() ) { event.setCancelled(true); event.getBlock().setType(Material.AIR); ItemStack drop = new ItemStack(item.getType(), item.getAmount(), item.getData().getData()); ItemMeta meta = drop.getItemMeta(); item.setType(Material.AIR); if (this.tregmine.blockStats.isPlaced(event.getBlock())) { } else { Wallet wallet = new Wallet (player.getName()); wallet.add(rs.getInt("value")); } List<String> lore = new ArrayList<String>(); lore.add(info.tregmine.api.lore.Created.MINED.toColorString()); lore.add(ChatColor.WHITE + "by: " + player.getChatName()); lore.add(ChatColor.WHITE + "Value: "+ rs.getInt("value") + " Treg" ); lore.add(ChatColor.WHITE + "World: "+ event.getBlock().getWorld().getName()); meta.setLore(lore); drop.setItemMeta(meta); event.getBlock().getWorld().dropItem(event.getBlock().getLocation(), drop); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) {} } if (stmt != null) { try { stmt.close(); } catch (SQLException e) {} } if (conn != null) { try { conn.close(); } catch (SQLException e) {} } } } } @EventHandler public void onBlockBreak (BlockBreakEvent event) { TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (player.isAdmin()) { mineForTreg(event); return; } ZoneWorld world = plugin.getWorld(player.getWorld()); Block block = event.getBlock(); Location location = block.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.getCurrentZone(); if (currentZone == null || !currentZone.contains(pos)) { currentZone = world.findZone(pos); player.setCurrentZone(currentZone); } if (currentZone != null) { Zone.Permission perm = currentZone.getUser(player.getName()); Lot lot = world.findLot(pos); if (lot != null) { if (perm != Zone.Permission.Owner && !lot.isOwner(player.getName())) { player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in lot " + lot.getName() + "."); event.setCancelled(true); return; } mineForTreg(event); return; } // if everyone is allowed to build in this zone... if (currentZone.getDestroyDefault()) { // ...the only people that can't build are those that are banned if (perm != null && perm == Zone.Permission.Banned) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are banned from " + currentZone.getName() + "."); } } // if this zone has limited building privileges... else { // ...we only allow builders and owners to make changes. if (perm == null || (perm != Zone.Permission.Maker && perm != Zone.Permission.Owner)) { player.setFireTicks(50); event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in " + currentZone.getName() + "."); } } } mineForTreg(event); } @EventHandler public void onBlockPlace(BlockPlaceEvent event) { TregminePlayer player = tregmine.getPlayer(event.getPlayer()); if (player.isAdmin()) { return; } ZoneWorld world = plugin.getWorld(player.getWorld()); Block block = event.getBlock(); Location location = block.getLocation(); Point pos = new Point(location.getBlockX(), location.getBlockZ()); Zone currentZone = player.getCurrentZone(); if (currentZone == null || !currentZone.contains(pos)) { currentZone = world.findZone(pos); player.setCurrentZone(currentZone); } if (currentZone != null) { Zone.Permission perm = currentZone.getUser(player.getName()); Lot lot = world.findLot(pos); if (lot != null) { if (perm != Zone.Permission.Owner && !lot.isOwner(player.getName())) { player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to break blocks in lot " + lot.getName() + "."); event.setCancelled(true); return; } // we should only get here if the event is allowed, in which case we don't need // any more checks. return; } // if everyone is allowed to build in this zone... if (currentZone.getPlaceDefault()) { // ...the only people that can't build are those that are banned if (perm != null && perm == Zone.Permission.Banned) { event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are banned from " + currentZone.getName() + "."); } } // if this zone has limited building privileges... else { // ...we only allow builders and owners to make changes. if (perm == null || (perm != Zone.Permission.Maker && perm != Zone.Permission.Owner)) { player.setFireTicks(50); event.setCancelled(true); player.sendMessage(ChatColor.RED + "[" + currentZone.getName() + "] " + "You are not allowed to place blocks in " + currentZone.getName() + "."); } } } } }
added check for if it has meta
Zones/src/info/tregmine/listeners/ZoneBlockListener.java
added check for if it has meta
Java
bsd-3-clause
9d5d91f9306c1431dce92107ef11e4b82d9adb16
0
rahulmutt/ghcvm,rahulmutt/ghcvm,rahulmutt/ghcvm,rahulmutt/ghcvm,rahulmutt/ghcvm
package eta.runtime.io; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Queue; import java.util.NavigableMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.nio.ByteBuffer; import eta.runtime.stg.WeakPtr; import static eta.runtime.RuntimeLogging.barf; import static eta.runtime.RuntimeLogging.debugMemoryManager; public class MemoryManager { /** Allocating Off-Heap Memory **/ /* TODO: Optimize this to make a specialized data structure that stores primitive ints & longs. */ /* Map block sizes to addresses of free blocks */ public static final NavigableMap<Integer, Queue<Long>> freeDirectBlocks = new ConcurrentSkipListMap<Integer, Queue<Long>>(); public static final NavigableMap<Integer, Queue<Long>> freeHeapBlocks = new ConcurrentSkipListMap<Integer, Queue<Long>>(); /* Locks on each size */ public static Map<Integer, SizeLock> directSizeLocks = new ConcurrentHashMap<Integer, SizeLock>(); public static AtomicBoolean directSizeLocksLock = new AtomicBoolean(); public static Map<Integer, SizeLock> heapSizeLocks = new ConcurrentHashMap<Integer, SizeLock>(); public static AtomicBoolean heapSizeLocksLock = new AtomicBoolean(); public static SizeLock getSizeLock (Map<Integer, SizeLock> sizeLocks, AtomicBoolean sizeLocksLock, Integer key) { SizeLock sizeLock; for (;;) { sizeLock = sizeLocks.get(key); if (sizeLock == null) { if (sizeLocksLock.compareAndSet(false, true)) { try { sizeLock = new SizeLock(); sizeLocks.put(key, sizeLock); } finally { sizeLocksLock.set(false); } } else continue; } return sizeLock; } } /* Map addresses to size of free blocks */ public static final NavigableMap<Long, Integer> freeDirectAddresses = new ConcurrentSkipListMap<Long, Integer>(); public static final NavigableMap<Long, Integer> freeHeapAddresses = new ConcurrentSkipListMap<Long, Integer>(); /* Map addresses to size of allocated blocks */ public static final NavigableMap<Long, Integer> allocatedDirectBlocks = new ConcurrentSkipListMap<Long, Integer>(); public static final NavigableMap<Long, Integer> allocatedHeapBlocks = new ConcurrentSkipListMap<Long, Integer>(); /* Actual storage of blocks */ public static List[] blockArrays = { new ArrayList() , new ArrayList() , new ArrayList() , new ArrayList() }; /* Locks for each blockArray */ public static AtomicBoolean[] blockLocks = { new AtomicBoolean() , new AtomicBoolean() , new AtomicBoolean() , new AtomicBoolean() }; /* Buffer Allocation This logic is rather complicated but it is done for efficiency purposes. Each free block size has a lock associated with it which is taken whenever a modification is done for that size. That way, two concurrent threads that are trying to allocate two different sizes can do so without waiting. */ public static long allocateBuffer(int n, boolean direct) { assert n <= ONE_GB; int newRegionSize; long newAddress; boolean attemptedGC = false; NavigableMap<Integer, Queue<Long>> freeBlocks; NavigableMap<Long, Integer> freeAddresses; NavigableMap<Long, Integer> allocatedBlocks; Map<Integer, SizeLock> sizeLocks; AtomicBoolean sizeLocksLock; if (direct) { allocatedBlocks = allocatedDirectBlocks; freeAddresses = freeDirectAddresses; freeBlocks = freeDirectBlocks; sizeLocks = directSizeLocks; sizeLocksLock = directSizeLocksLock; } else { allocatedBlocks = allocatedHeapBlocks; freeAddresses = freeHeapAddresses; freeBlocks = freeHeapBlocks; sizeLocks = heapSizeLocks; sizeLocksLock = heapSizeLocksLock; } main: for (;;) { Map.Entry<Integer, Queue<Long>> freeEntry = freeBlocks.ceilingEntry(n); if (freeEntry != null) { int regionSize = freeEntry.getKey(); SizeLock sizeLock = getSizeLock(sizeLocks, sizeLocksLock, regionSize); Queue<Long> freeQueue = freeEntry.getValue(); Long address; /* We attempt to acquire a permit (exists if there is a queue element) and upon failure, continue the loop in case changes were made to freeBlocks. */ if (sizeLock.tryAcquire()) { assert freeQueue != null; address = freeQueue.poll(); /* INVARIANT: sizeLocks.peekPermits() == freeQueue.size() Currently does not hold. Needs to be investigated. */ assert address != null; freeAddresses.remove(address); } else { if (freeQueue.isEmpty() && sizeLock.tryStartTransaction()) { try { freeBlocks.remove(regionSize); } finally { sizeLock.endTransaction(); } } continue; } newRegionSize = regionSize - n; newAddress = address + n; allocatedBlocks.put(address, n); debugMemoryManager("Allocate Block @ " + address + " " + renderSize(n) + "."); if (newRegionSize > 0) { insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newRegionSize, newAddress); } return address; } else { int blockType = getBlockType(n); do { AtomicBoolean blockLock = blockLocks[blockType]; @SuppressWarnings("unchecked") List<ByteBuffer> blocks = blockArrays[blockType]; if (blocks.size() == MAX_BLOCK_INDEX) { if (blockType == ONE_GB_BLOCK) { if (!attemptedGC) { /* Attempt to free native memory by first GC'ing any garbage ByteArrays so that some native memory can be freed. */ System.gc(); /* Give some time for the GC to work so that the reference queues get populated. */ try { Thread.sleep(1); } catch (InterruptedException e) {} maybeFreeNativeMemory(); /* Restart the top-level loop to see if any free blocks have been allocated. */ attemptedGC = true; debugMemoryManager("MemoryManager Space Full." + " GC and Retry."); continue main; } else { throw new OutOfMemoryError("The Eta MemoryManager is unable to allocate more off-heap memory."); } } /* INVARIANT: Each increment of blockType yields the next higher blockSize. */ blockType += 1; continue; } if (blockLock.compareAndSet(false, true)) { long address; try { long blockIndex = blocks.size(); int blockSize = getBlockSize(blockType); address = (blockType << BLOCK_TYPE_BITS) | (blockIndex << indexBits(blockType)); /* Avoid allocating something on the null pointer address. */ if (address == 0) address = 1; freeAddresses.remove(address); newRegionSize = blockSize - n; newAddress = address + n; blocks.add(allocateAnonymousBuffer(blockSize, direct)); debugMemoryManager("Create " + renderIsDirect(direct) + " Block " + renderSize(blockSize) + "."); allocatedBlocks.put(address, n); debugMemoryManager("Allocated Block @ " + address + " " + renderSize(n) + "."); insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newRegionSize, newAddress); } finally { blockLock.set(false); } return address; } else { /* If unable to lock, continue the loop to see if free blocks became available in the mean time. */ continue; } } while (true); } } } /* TODO: We can make inserting free blocks asynchronous to speed up allocation a tiny bit, since we don't need to insert them to get the allocated address. This can be done with message passing and adding a bit of work to a Capability's idleLoop that reads from the message queue and inserts free blocks accordingly. The tradeoff with this approach is that new blocks may get allocated more if these free blocks don't get inserted in time. */ public static void insertFreeBlock (NavigableMap<Integer, Queue<Long>> freeBlocks, NavigableMap<Long, Integer> freeAddresses, Map<Integer, SizeLock> sizeLocks, AtomicBoolean sizeLocksLock, int newRegionSize, long newAddress) { assert newRegionSize > 0; /* TODO: Implement block destroying to release memory when it's no longer needed. Currently, if your application suddenly allocates a lot of native memory, it will stay allocated for the lifetime of the application. */ debugMemoryManager("Free Block @ " + newAddress + " " + renderSize(newRegionSize) + "."); /* TODO: Do we need to ensure atomicity of this entire function? */ SizeLock newSizeLock = getSizeLock(sizeLocks, sizeLocksLock, newRegionSize); while (!newSizeLock.tryStartTransaction()) {} try { Queue<Long> freeQueue = freeBlocks.get(newRegionSize); if (freeQueue != null) { freeQueue.offer(newAddress); newSizeLock.enlarge(); } else { freeQueue = new ConcurrentLinkedQueue<Long>(); freeQueue.offer(newAddress); freeBlocks.put(newRegionSize, freeQueue); /* FIXME: If reset() is not called, the INVARIANT [see above] breaks. */ newSizeLock.reset(); } } finally { newSizeLock.endTransaction(); } freeAddresses.put(newAddress, newRegionSize); } public static ByteBuffer allocateAnonymousBuffer(int n, boolean direct) { return (direct? /* Off-Heap Memory */ ByteBuffer.allocateDirect(n): /* Heap Memory */ ByteBuffer.allocate(n)); } /** Freeing Off-Heap Memory **/ public static void maybeFreeNativeMemory() { /* Free memory blocks associated with ByteArrays if the ByteArray itself has been garbage collected. */ IO.checkForGCByteArrays(); /* Check for any WeakPtr keys that have been GC'd and run both the Eta finalizers and Java finalizers. */ WeakPtr.checkForGCWeakPtrs(); } public static void free(long address) { NavigableMap<Integer, Queue<Long>> freeBlocks; NavigableMap<Long, Integer> allocatedBlocks; NavigableMap<Long, Integer> freeAddresses; Map<Integer, SizeLock> sizeLocks; AtomicBoolean sizeLocksLock; Integer sizeInt = allocatedDirectBlocks.get(address); boolean direct; if (sizeInt == null) { sizeInt = allocatedHeapBlocks.get(address); if (sizeInt == null) { /* This means that `address` was already freed. */ return; } else { allocatedBlocks = allocatedHeapBlocks; /* Check if `address` was already freed. */ if (allocatedBlocks.remove(address) == null) { debugMemoryManager("Freed @ " + address + " " + renderSize(sizeInt) + "."); return; } direct = false; } } else { allocatedBlocks = allocatedDirectBlocks; /* Check if `address` was already freed. */ if (allocatedBlocks.remove(address) == null) { debugMemoryManager("Freed @ " + address + " " + renderSize(sizeInt) + "."); return; } direct = true; } debugMemoryManager("Free @ " + address + " " + renderSize(sizeInt) + "."); int size = sizeInt.intValue(); if (direct) { freeAddresses = freeDirectAddresses; freeBlocks = freeDirectBlocks; sizeLocks = directSizeLocks; sizeLocksLock = directSizeLocksLock; } else { freeAddresses = freeHeapAddresses; freeBlocks = freeHeapBlocks; sizeLocks = heapSizeLocks; sizeLocksLock = heapSizeLocksLock; } long lowerAddress = 0L; int lowerSize = 0; long higherAddress = 0L; int higherSize = 0; Map.Entry<Long, Integer> lowerEntry = freeAddresses.lowerEntry(address); Map.Entry<Long, Integer> higherEntry = freeAddresses.higherEntry(address); if (lowerEntry != null) { lowerAddress = lowerEntry.getKey(); lowerSize = lowerEntry.getValue(); } if (higherEntry != null) { higherAddress = higherEntry.getKey(); higherSize = higherEntry.getValue(); } long newAddress = address; int newSize = size; SizeLock lowerRegionLock = null; SizeLock higherRegionLock = null; /* After these two checks, lowerAddress will be the starting point of the new freeBlock and size will be the size of the new block. */ try { if ((lowerAddress + lowerSize) == address && sameBlock(lowerAddress, address)) { lowerRegionLock = getSizeLock(sizeLocks, sizeLocksLock, lowerSize); while (!lowerRegionLock.tryStartTransaction()) {} newAddress = lowerAddress; newSize += lowerSize; } if ((address + size) == higherAddress && sameBlock(address, higherAddress)) { if (lowerRegionLock != null && lowerSize == higherSize) { higherRegionLock = lowerRegionLock; } else { higherRegionLock = getSizeLock(sizeLocks, sizeLocksLock, higherSize); while (!higherRegionLock.tryStartTransaction()) {} } newSize += higherSize; } Queue<Long> freeQueue; if (lowerRegionLock != null) { freeQueue = freeBlocks.get(lowerSize); /* If the free block was taken by the time we got the lock. */ if (freeQueue == null) { newAddress = address; newSize -= lowerSize; } else { /* If the free block was taken by the time we got the lock. */ if (!freeQueue.remove(lowerAddress)) { newAddress = address; newSize -= lowerSize; } else { /* Success, remove a permit */ lowerRegionLock.unconditionalAcquire(); } } } if (higherRegionLock != null) { freeQueue = freeBlocks.get(higherSize); /* If the free block was taken by the time we got the lock. */ if (freeQueue == null) { newSize -= higherSize; } else { /* If the free block was taken by the time we got the lock. */ if (!freeQueue.remove(lowerAddress)) { newSize -= higherSize; } else { /* Success, remove a permit */ higherRegionLock.unconditionalAcquire(); } } } } finally { if (lowerRegionLock != null) lowerRegionLock.endTransaction(); if (higherRegionLock != null && higherRegionLock != lowerRegionLock) higherRegionLock.endTransaction(); } insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newSize, newAddress); } /* FIXME: For some reason, cleanup() causes bugs in the future invocations of the Eta RTS from the same JVM. */ /* This is dangerous if done at any time other than shutdown. It will wipe out all information and free any remaining data. */ public static void cleanup() { freeDirectBlocks.clear(); freeHeapBlocks.clear(); for (List l: blockArrays) { l.clear(); } allocatedDirectBlocks.clear(); allocatedHeapBlocks.clear(); freeDirectAddresses.clear(); freeHeapAddresses.clear(); directSizeLocks.clear(); heapSizeLocks.clear(); } /** Addresses The first two bits of the address determine the block type. The blocks come in four variants: * 1 MB block - 11 free bits, 31 block bits, 20 index bits * 16 MB block - 7 free bits, 31 block bits, 24 index bits * 128 MB block - 4 free bits, 31 block bits, 27 index bits * 1 GB block - 1 free bits, 31 block bits, 30 index bits Hence, the maximum you can allocate a single block for is 1GB. We may want to implement a custom ByteBuffer that can handle block borders. */ public static final long BLOCK_TYPE_MASK = 0xC000000000000000L; public static final int BLOCK_TYPE_BITS = 62; public static final int MAX_BLOCK_INDEX = 0x7FFFFFFF; public static final int ONE_MB_INDEX_BITS = 20; public static final int ONE_SIX_MB_INDEX_BITS = 24; public static final int ONE_TWO_EIGHT_MB_INDEX_BITS = 27; public static final int ONE_GB_INDEX_BITS = 30; public static final int ONE_MB = 1 << ONE_MB_INDEX_BITS; public static final int ONE_SIX_MB = 1 << ONE_SIX_MB_INDEX_BITS; public static final int ONE_TWO_EIGHT_MB = 1 << ONE_TWO_EIGHT_MB_INDEX_BITS; public static final int ONE_GB = 1 << ONE_GB_INDEX_BITS; public static final int ONE_MB_BLOCK = 0; public static final int ONE_SIX_MB_BLOCK = 1; public static final int ONE_TWO_EIGHT_MB_BLOCK = 2; public static final int ONE_GB_BLOCK = 3; public static int getBlockType(int n) { assert n <= ONE_GB; if (n <= ONE_MB) return ONE_MB_BLOCK; else if (n <= ONE_SIX_MB) return ONE_SIX_MB_BLOCK; else if (n <= ONE_TWO_EIGHT_MB) return ONE_TWO_EIGHT_MB_BLOCK; else if (n <= ONE_GB) return ONE_GB_BLOCK; else throw new IllegalArgumentException("Cannot allocate a block size greater than 1GB!"); } public static int getBlockSize(int blockType) { switch (blockType) { case 0: return ONE_MB; case 1: return ONE_SIX_MB; case 2: return ONE_TWO_EIGHT_MB; case 3: return ONE_GB; default: barf("Bad index Mask"); return -1; } } public static boolean sameBlock(long address1, long address2) { int blockType1 = blockType(address1); int blockType2 = blockType(address2); if (blockType1 != blockType2) return false; return blockIndex(address1, indexBits(blockType1)) == blockIndex(address2, indexBits(blockType2)); } public static int blockType(long address) { return (int)((address & BLOCK_TYPE_MASK) >>> BLOCK_TYPE_BITS); } public static int indexBits(int blockType) { switch (blockType) { case 0: return ONE_MB_INDEX_BITS; case 1: return ONE_SIX_MB_INDEX_BITS; case 2: return ONE_TWO_EIGHT_MB_INDEX_BITS; case 3: return ONE_GB_INDEX_BITS; default: barf("Bad index Mask"); return -1; } } public static int blockIndex(long address, int indexBits) { return (int)((address & ~BLOCK_TYPE_MASK) >>> indexBits); } public static int positionIndex(long address) { return (int)(address & ((1 << indexBits(blockType(address))) - 1)); } public static int positionIndex(long address, int indexBits) { return (int)(address & ((1 << indexBits) - 1)); } /** Byte Buffer API to MemoryManager **/ /* This caches the last lookup for reducing the constant factor when you're doing a lot of writes/reads on a single buffer (the common case). */ private static class ThreadLocalLong extends ThreadLocal<Long> { protected Long initialValue() { return new Long(0L); } } /* Start of previous received block. */ public static ThreadLocal<Long> cachedLowerAddress = new ThreadLocalLong(); /* Start of the adjacent block. NOTE: This is the start of the NEXT block so you must do a strict comparison. */ public static ThreadLocal<Long> cachedHigherAddress = new ThreadLocalLong(); /* The cached buffer */ public static ThreadLocal<ByteBuffer> cachedBuffer = new ThreadLocal<ByteBuffer>(); /* The shared empty buffer */ public final static ByteBuffer emptyBuffer = ByteBuffer.allocate(0); public static ByteBuffer getBuffer(long address) { if (address == 0) return emptyBuffer; if (address >= cachedLowerAddress.get() && address < cachedHigherAddress.get()) { ByteBuffer cached = cachedBuffer.get(); if (cached != null) { return cached; } } int blockType = blockType(address); int indexBits = indexBits(blockType); int blockIndex = blockIndex(address, indexBits); long lower = (blockType << BLOCK_TYPE_BITS) | (blockIndex << indexBits); AtomicBoolean blockLock = blockLocks[blockType]; ByteBuffer buf = null; if (blockLock.compareAndSet(false, true)) { try { buf = (ByteBuffer) blockArrays[blockType].get(blockIndex); } finally { blockLock.set(false); } } cachedLowerAddress.set(lower); cachedHigherAddress.set(lower + (1 << indexBits)); cachedBuffer.set(buf); return buf; } /* Helper function that will find an allocated block below the one given. */ private static Map.Entry<Long, Integer> findLowerAllocatedAddress(NavigableMap<Long, Integer> allocatedBlocks ,long address) { Map.Entry<Long, Integer> lowerEntry = allocatedBlocks.floorEntry(Long.valueOf(address)); if (lowerEntry != null && (address <= (lowerEntry.getKey() + lowerEntry.getValue()))) { return lowerEntry; } return null; } public static Map.Entry<Long, Integer> findAllocatedAddress(long address) { Map.Entry<Long, Integer> lowerEntry = findLowerAllocatedAddress(allocatedDirectBlocks, address); if (lowerEntry == null) { lowerEntry = findLowerAllocatedAddress(allocatedHeapBlocks, address); } return lowerEntry; } /* When doing bulk operations, this can be useful. It returns a ByteBuffer positioned at the place referred to by the address. It's duplicated so the user is free to change the position as necessary. Throws an exception if the block that corresponds to the address has been freed. */ public static ByteBuffer getBoundedBuffer(long address) { if (address == 0) return emptyBuffer; Map.Entry<Long, Integer> lowerEntry = findAllocatedAddress(address); if (lowerEntry == null) { throw new IllegalStateException("The block that corresponds to the address "+ address+" is not allocated in memory"); } long lowerAddress = lowerEntry.getKey(); int lowerSize = lowerEntry.getValue(); int blockType = blockType(address); int indexBits = indexBits(blockType); int blockIndex = blockIndex(address, indexBits); int positionIndex = positionIndex(address, indexBits); int size = (int)(lowerAddress + lowerSize - address); ByteBuffer buf = null; AtomicBoolean blockLock = blockLocks[blockType]; if (blockLock.compareAndSet(false, true)) { try { buf = ((ByteBuffer) blockArrays[blockType].get(blockIndex)).duplicate(); } finally { blockLock.set(false); } } buf.position(positionIndex); buf.limit(positionIndex + size); return buf; } /* This returns -1 if `address` has already been freed. */ public static int allocatedSize(long address) { Integer sizeInt = allocatedDirectBlocks.get(address); if (sizeInt == null) { sizeInt = allocatedHeapBlocks.get(address); if (sizeInt == null) { return -1; } } return sizeInt.intValue(); } /** Read APIs **/ public static byte get(long address) { return getBuffer(address).get(positionIndex(address)); } public static short getShort(long address) { return getBuffer(address).getShort(positionIndex(address)); } public static char getChar(long address) { return getBuffer(address).getChar(positionIndex(address)); } public static int getInt(long address) { return getBuffer(address).getInt(positionIndex(address)); } public static long getLong(long address) { return getBuffer(address).getLong(positionIndex(address)); } public static float getFloat(long address) { return getBuffer(address).getFloat(positionIndex(address)); } public static double getDouble(long address) { return getBuffer(address).getDouble(positionIndex(address)); } /** Write APIs **/ public static void put(long address, byte val) { getBuffer(address).put(positionIndex(address), val); } public static void putShort(long address, short val) { getBuffer(address).putShort(positionIndex(address), val); } public static void putChar(long address, char val) { getBuffer(address).putChar(positionIndex(address), val); } public static void putInt(long address, int val) { getBuffer(address).putInt(positionIndex(address), val); } public static void putLong(long address, long val) { getBuffer(address).putLong(positionIndex(address), val); } public static void putFloat(long address, float val) { getBuffer(address).putFloat(positionIndex(address), val); } public static void putDouble(long address, double val) { getBuffer(address).putDouble(positionIndex(address), val); } /** Monitoring **/ private static void printHeading(String heading) { System.out.print("***"); System.out.print(heading); System.out.println("***"); } private static void printAddressMap(String heading, Map<Long, Integer> addresses) { printHeading(heading); if (addresses.size() > 0) { for (Map.Entry<Long, Integer> entry: addresses.entrySet()) { Long address = entry.getKey(); Integer size = entry.getValue(); Long end = entry.getKey() + entry.getValue() - 1; System.out.println(address + "-" + end + " [" + size + " bytes]"); } } else { System.out.println("None"); } } private static void printBlocksMap(String heading, Map<Integer,Queue<Long>> blocks) { printHeading(heading); if (blocks.size() > 0) { for (Map.Entry<Integer, Queue<Long>> entry: blocks.entrySet()) { System.out.println("Region Size: " + entry.getKey() + " bytes"); Queue<Long> freeAddresses = entry.getValue(); if (freeAddresses.size() > 0) { for (Long address: freeAddresses) { System.out.println(" " + address); } } else { System.out.println(" None"); } } } else { System.out.println("None"); } } public static void dumpMemoryManager() { System.out.println("***Eta-Managed Off-Heap Memory***"); printAddressMap("Allocated Direct Blocks", allocatedDirectBlocks); printAddressMap("Allocated Heap Blocks", allocatedHeapBlocks); printAddressMap("Free Direct Addresses", freeDirectAddresses); printAddressMap("Free Heap Addresses", freeHeapAddresses); printBlocksMap("Free Direct Blocks", freeDirectBlocks); printBlocksMap("Free Heap Blocks", freeHeapBlocks); } /** Misc. Utilities **/ private static String renderSize(int size) { return "["+ size + " bytes]"; } private static String renderIsDirect(boolean direct) { return direct? "Direct" : "Heap"; } }
rts/src/eta/runtime/io/MemoryManager.java
package eta.runtime.io; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Queue; import java.util.NavigableMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicBoolean; import java.nio.ByteBuffer; import eta.runtime.stg.WeakPtr; import static eta.runtime.RuntimeLogging.barf; import static eta.runtime.RuntimeLogging.debugMemoryManager; public class MemoryManager { /** Allocating Off-Heap Memory **/ /* TODO: Optimize this to make a specialized data structure that stores primitive ints & longs. */ /* Map block sizes to addresses of free blocks */ public static final NavigableMap<Integer, Queue<Long>> freeDirectBlocks = new ConcurrentSkipListMap<Integer, Queue<Long>>(); public static final NavigableMap<Integer, Queue<Long>> freeHeapBlocks = new ConcurrentSkipListMap<Integer, Queue<Long>>(); /* Locks on each size */ public static Map<Integer, SizeLock> directSizeLocks = new ConcurrentHashMap<Integer, SizeLock>(); public static AtomicBoolean directSizeLocksLock = new AtomicBoolean(); public static Map<Integer, SizeLock> heapSizeLocks = new ConcurrentHashMap<Integer, SizeLock>(); public static AtomicBoolean heapSizeLocksLock = new AtomicBoolean(); public static SizeLock getSizeLock (Map<Integer, SizeLock> sizeLocks, AtomicBoolean sizeLocksLock, Integer key) { SizeLock sizeLock; for (;;) { sizeLock = sizeLocks.get(key); if (sizeLock == null) { if (sizeLocksLock.compareAndSet(false, true)) { try { sizeLock = new SizeLock(); sizeLocks.put(key, sizeLock); } finally { sizeLocksLock.set(false); } } else continue; } return sizeLock; } } /* Map addresses to size of free blocks */ public static final NavigableMap<Long, Integer> freeDirectAddresses = new ConcurrentSkipListMap<Long, Integer>(); public static final NavigableMap<Long, Integer> freeHeapAddresses = new ConcurrentSkipListMap<Long, Integer>(); /* Map addresses to size of allocated blocks */ public static final NavigableMap<Long, Integer> allocatedDirectBlocks = new ConcurrentSkipListMap<Long, Integer>(); public static final NavigableMap<Long, Integer> allocatedHeapBlocks = new ConcurrentSkipListMap<Long, Integer>(); /* Actual storage of blocks */ public static List[] blockArrays = { new ArrayList() , new ArrayList() , new ArrayList() , new ArrayList() }; /* Locks for each blockArray */ public static AtomicBoolean[] blockLocks = { new AtomicBoolean() , new AtomicBoolean() , new AtomicBoolean() , new AtomicBoolean() }; /* Buffer Allocation This logic is rather complicated but it is done for efficiency purposes. Each free block size has a lock associated with it which is taken whenever a modification is done for that size. That way, two concurrent threads that are trying to allocate two different sizes can do so without waiting. */ public static long allocateBuffer(int n, boolean direct) { assert n <= ONE_GB; int newRegionSize; long newAddress; boolean attemptedGC = false; NavigableMap<Integer, Queue<Long>> freeBlocks; NavigableMap<Long, Integer> freeAddresses; NavigableMap<Long, Integer> allocatedBlocks; Map<Integer, SizeLock> sizeLocks; AtomicBoolean sizeLocksLock; if (direct) { allocatedBlocks = allocatedDirectBlocks; freeAddresses = freeDirectAddresses; freeBlocks = freeDirectBlocks; sizeLocks = directSizeLocks; sizeLocksLock = directSizeLocksLock; } else { allocatedBlocks = allocatedHeapBlocks; freeAddresses = freeHeapAddresses; freeBlocks = freeHeapBlocks; sizeLocks = heapSizeLocks; sizeLocksLock = heapSizeLocksLock; } main: for (;;) { Map.Entry<Integer, Queue<Long>> freeEntry = freeBlocks.ceilingEntry(n); if (freeEntry != null) { int regionSize = freeEntry.getKey(); SizeLock sizeLock = getSizeLock(sizeLocks, sizeLocksLock, regionSize); Queue<Long> freeQueue = freeEntry.getValue(); Long address; /* We attempt to acquire a permit (exists if there is a queue element) and upon failure, continue the loop in case changes were made to freeBlocks. */ if (sizeLock.tryAcquire()) { assert freeQueue != null; address = freeQueue.poll(); /* INVARIANT: sizeLocks.peekPermits() == freeQueue.size() Currently does not hold. Needs to be investigated. */ assert address != null; freeAddresses.remove(address); } else { if (freeQueue.isEmpty() && sizeLock.tryStartTransaction()) { try { freeBlocks.remove(regionSize); } finally { sizeLock.endTransaction(); } } continue; } newRegionSize = regionSize - n; newAddress = address + n; allocatedBlocks.put(address, n); debugMemoryManager("Allocate Block @ " + address + " " + renderSize(n) + "."); if (newRegionSize > 0) { insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newRegionSize, newAddress); } return address; } else { int blockType = getBlockType(n); do { AtomicBoolean blockLock = blockLocks[blockType]; @SuppressWarnings("unchecked") List<ByteBuffer> blocks = blockArrays[blockType]; if (blocks.size() == MAX_BLOCK_INDEX) { if (blockType == ONE_GB_BLOCK) { if (!attemptedGC) { /* Attempt to free native memory by first GC'ing any garbage ByteArrays so that some native memory can be freed. */ System.gc(); /* Give some time for the GC to work so that the reference queues get populated. */ try { Thread.sleep(1); } catch (InterruptedException e) {} maybeFreeNativeMemory(); /* Restart the top-level loop to see if any free blocks have been allocated. */ attemptedGC = true; debugMemoryManager("MemoryManager Space Full." + " GC and Retry."); continue main; } else { throw new OutOfMemoryError("The Eta MemoryManager is unable to allocate more off-heap memory."); } } /* INVARIANT: Each increment of blockType yields the next higher blockSize. */ blockType += 1; continue; } if (blockLock.compareAndSet(false, true)) { long address; try { long blockIndex = blocks.size(); int blockSize = getBlockSize(blockType); address = (blockType << BLOCK_TYPE_BITS) | (blockIndex << indexBits(blockType)); /* Avoid allocating something on the null pointer address. */ if (address == 0) address = 1; freeAddresses.remove(address); newRegionSize = blockSize - n; newAddress = address + n; blocks.add(allocateAnonymousBuffer(blockSize, direct)); debugMemoryManager("Create " + renderIsDirect(direct) + " Block " + renderSize(blockSize) + "."); allocatedBlocks.put(address, n); debugMemoryManager("Allocated Block @ " + address + " " + renderSize(n) + "."); insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newRegionSize, newAddress); } finally { blockLock.set(false); } return address; } else { /* If unable to lock, continue the loop to see if free blocks became available in the mean time. */ continue; } } while (true); } } } /* TODO: We can make inserting free blocks asynchronous to speed up allocation a tiny bit, since we don't need to insert them to get the allocated address. This can be done with message passing and adding a bit of work to a Capability's idleLoop that reads from the message queue and inserts free blocks accordingly. The tradeoff with this approach is that new blocks may get allocated more if these free blocks don't get inserted in time. */ public static void insertFreeBlock (NavigableMap<Integer, Queue<Long>> freeBlocks, NavigableMap<Long, Integer> freeAddresses, Map<Integer, SizeLock> sizeLocks, AtomicBoolean sizeLocksLock, int newRegionSize, long newAddress) { assert newRegionSize > 0; /* TODO: Implement block destroying to release memory when it's no longer needed. Currently, if your application suddenly allocates a lot of native memory, it will stay allocated for the lifetime of the application. */ debugMemoryManager("Free Block @ " + newAddress + " " + renderSize(newRegionSize) + "."); /* TODO: Do we need to ensure atomicity of this entire function? */ SizeLock newSizeLock = getSizeLock(sizeLocks, sizeLocksLock, newRegionSize); while (!newSizeLock.tryStartTransaction()) {} try { Queue<Long> freeQueue = freeBlocks.get(newRegionSize); if (freeQueue != null) { freeQueue.offer(newAddress); newSizeLock.enlarge(); } else { freeQueue = new ConcurrentLinkedQueue<Long>(); freeQueue.offer(newAddress); freeBlocks.put(newRegionSize, freeQueue); /* FIXME: If reset() is not called, the INVARIANT [see above] breaks. */ newSizeLock.reset(); } } finally { newSizeLock.endTransaction(); } freeAddresses.put(newAddress, newRegionSize); } public static ByteBuffer allocateAnonymousBuffer(int n, boolean direct) { return (direct? /* Off-Heap Memory */ ByteBuffer.allocateDirect(n): /* Heap Memory */ ByteBuffer.allocate(n)); } /** Freeing Off-Heap Memory **/ public static void maybeFreeNativeMemory() { /* Free memory blocks associated with ByteArrays if the ByteArray itself has been garbage collected. */ IO.checkForGCByteArrays(); /* Check for any WeakPtr keys that have been GC'd and run both the Eta finalizers and Java finalizers. */ WeakPtr.checkForGCWeakPtrs(); } public static void free(long address) { NavigableMap<Integer, Queue<Long>> freeBlocks; NavigableMap<Long, Integer> allocatedBlocks; NavigableMap<Long, Integer> freeAddresses; Map<Integer, SizeLock> sizeLocks; AtomicBoolean sizeLocksLock; Integer sizeInt = allocatedDirectBlocks.get(address); boolean direct; if (sizeInt == null) { sizeInt = allocatedHeapBlocks.get(address); if (sizeInt == null) { /* This means that `address` was already freed. */ return; } else { allocatedBlocks = allocatedHeapBlocks; /* Check if `address` was already freed. */ if (allocatedBlocks.remove(address) == null) { debugMemoryManager("Freed @ " + address + " " + renderSize(sizeInt) + "."); return; } direct = false; } } else { allocatedBlocks = allocatedDirectBlocks; /* Check if `address` was already freed. */ if (allocatedBlocks.remove(address) == null) { debugMemoryManager("Freed @ " + address + " " + renderSize(sizeInt) + "."); return; } direct = true; } debugMemoryManager("Free @ " + address + " " + renderSize(sizeInt) + "."); int size = sizeInt.intValue(); if (direct) { freeAddresses = freeDirectAddresses; freeBlocks = freeDirectBlocks; sizeLocks = directSizeLocks; sizeLocksLock = directSizeLocksLock; } else { freeAddresses = freeHeapAddresses; freeBlocks = freeHeapBlocks; sizeLocks = heapSizeLocks; sizeLocksLock = heapSizeLocksLock; } long lowerAddress = 0L; int lowerSize = 0; long higherAddress = 0L; int higherSize = 0; Map.Entry<Long, Integer> lowerEntry = freeAddresses.lowerEntry(address); Map.Entry<Long, Integer> higherEntry = freeAddresses.higherEntry(address); if (lowerEntry != null) { lowerAddress = lowerEntry.getKey(); lowerSize = lowerEntry.getValue(); } if (higherEntry != null) { higherAddress = higherEntry.getKey(); higherSize = higherEntry.getValue(); } long newAddress = address; int newSize = size; SizeLock lowerRegionLock = null; SizeLock higherRegionLock = null; /* After these two checks, lowerAddress will be the starting point of the new freeBlock and size will be the size of the new block. */ try { if ((lowerAddress + lowerSize) == address && sameBlock(lowerAddress, address)) { lowerRegionLock = getSizeLock(sizeLocks, sizeLocksLock, lowerSize); while (!lowerRegionLock.tryStartTransaction()) {} newAddress = lowerAddress; newSize += lowerSize; } if ((address + size) == higherAddress && sameBlock(address, higherAddress)) { if (lowerRegionLock != null && lowerSize == higherSize) { higherRegionLock = lowerRegionLock; } else { higherRegionLock = getSizeLock(sizeLocks, sizeLocksLock, higherSize); while (!higherRegionLock.tryStartTransaction()) {} } newSize += higherSize; } Queue<Long> freeQueue; if (lowerRegionLock != null) { freeQueue = freeBlocks.get(lowerSize); /* If the free block was taken by the time we got the lock. */ if (freeQueue == null) { newAddress = address; newSize -= lowerSize; } else { /* If the free block was taken by the time we got the lock. */ if (!freeQueue.remove(lowerAddress)) { newAddress = address; newSize -= lowerSize; } else { /* Success, remove a permit */ lowerRegionLock.unconditionalAcquire(); } } } if (higherRegionLock != null) { freeQueue = freeBlocks.get(higherSize); /* If the free block was taken by the time we got the lock. */ if (freeQueue == null) { newSize -= higherSize; } else { /* If the free block was taken by the time we got the lock. */ if (!freeQueue.remove(lowerAddress)) { newSize -= higherSize; } else { /* Success, remove a permit */ higherRegionLock.unconditionalAcquire(); } } } } finally { if (lowerRegionLock != null) lowerRegionLock.endTransaction(); if (higherRegionLock != null && higherRegionLock != lowerRegionLock) higherRegionLock.endTransaction(); } insertFreeBlock(freeBlocks, freeAddresses, sizeLocks, sizeLocksLock, newSize, newAddress); } /* FIXME: For some reason, cleanup() causes bugs in the future invocations of the Eta RTS from the same JVM. */ /* This is dangerous if done at any time other than shutdown. It will wipe out all information and free any remaining data. */ public static void cleanup() { freeDirectBlocks.clear(); freeHeapBlocks.clear(); for (List l: blockArrays) { l.clear(); } allocatedDirectBlocks.clear(); allocatedHeapBlocks.clear(); freeDirectAddresses.clear(); freeHeapAddresses.clear(); directSizeLocks.clear(); heapSizeLocks.clear(); } /** Addresses The first two bits of the address determine the block type. The blocks come in four variants: * 1 MB block - 11 free bits, 31 block bits, 20 index bits * 16 MB block - 7 free bits, 31 block bits, 24 index bits * 128 MB block - 4 free bits, 31 block bits, 27 index bits * 1 GB block - 1 free bits, 31 block bits, 30 index bits Hence, the maximum you can allocate a single block for is 1GB. We may want to implement a custom ByteBuffer that can handle block borders. */ public static final long BLOCK_TYPE_MASK = 0xC000000000000000L; public static final int BLOCK_TYPE_BITS = 62; public static final int MAX_BLOCK_INDEX = 0x7FFFFFFF; public static final int ONE_MB_INDEX_BITS = 20; public static final int ONE_SIX_MB_INDEX_BITS = 24; public static final int ONE_TWO_EIGHT_MB_INDEX_BITS = 27; public static final int ONE_GB_INDEX_BITS = 30; public static final int ONE_MB = 1 << ONE_MB_INDEX_BITS; public static final int ONE_SIX_MB = 1 << ONE_SIX_MB_INDEX_BITS; public static final int ONE_TWO_EIGHT_MB = 1 << ONE_TWO_EIGHT_MB_INDEX_BITS; public static final int ONE_GB = 1 << ONE_GB_INDEX_BITS; public static final int ONE_MB_BLOCK = 0; public static final int ONE_SIX_MB_BLOCK = 1; public static final int ONE_TWO_EIGHT_MB_BLOCK = 2; public static final int ONE_GB_BLOCK = 3; public static int getBlockType(int n) { assert n <= ONE_GB; if (n <= ONE_MB) return ONE_MB_BLOCK; else if (n <= ONE_SIX_MB) return ONE_SIX_MB_BLOCK; else if (n <= ONE_TWO_EIGHT_MB) return ONE_TWO_EIGHT_MB_BLOCK; else if (n <= ONE_GB) return ONE_GB_BLOCK; else throw new IllegalArgumentException("Cannot allocate a block size greater than 1GB!"); } public static int getBlockSize(int blockType) { switch (blockType) { case 0: return ONE_MB; case 1: return ONE_SIX_MB; case 2: return ONE_TWO_EIGHT_MB; case 3: return ONE_GB; default: barf("Bad index Mask"); return -1; } } public static boolean sameBlock(long address1, long address2) { int blockType1 = blockType(address1); int blockType2 = blockType(address2); if (blockType1 != blockType2) return false; return blockIndex(address1, indexBits(blockType1)) == blockIndex(address2, indexBits(blockType2)); } public static int blockType(long address) { return (int)((address & BLOCK_TYPE_MASK) >>> BLOCK_TYPE_BITS); } public static int indexBits(int blockType) { switch (blockType) { case 0: return ONE_MB_INDEX_BITS; case 1: return ONE_SIX_MB_INDEX_BITS; case 2: return ONE_TWO_EIGHT_MB_INDEX_BITS; case 3: return ONE_GB_INDEX_BITS; default: barf("Bad index Mask"); return -1; } } public static int blockIndex(long address, int indexBits) { return (int)((address & ~BLOCK_TYPE_MASK) >>> indexBits); } public static int positionIndex(long address) { return (int)(address & ((1 << indexBits(blockType(address))) - 1)); } public static int positionIndex(long address, int indexBits) { return (int)(address & ((1 << indexBits) - 1)); } /** Byte Buffer API to MemoryManager **/ /* This caches the last lookup for reducing the constant factor when you're doing a lot of writes/reads on a single buffer (the common case). */ private static class ThreadLocalLong extends ThreadLocal<Long> { protected Long initialValue() { return new Long(0L); } } /* Start of previous received block. */ public static ThreadLocal<Long> cachedLowerAddress = new ThreadLocalLong(); /* Start of the adjacent block. NOTE: This is the start of the NEXT block so you must do a strict comparison. */ public static ThreadLocal<Long> cachedHigherAddress = new ThreadLocalLong(); /* The cached buffer */ public static ThreadLocal<ByteBuffer> cachedBuffer = new ThreadLocal<ByteBuffer>(); /* The shared empty buffer */ public final static ByteBuffer emptyBuffer = ByteBuffer.allocate(0); public static ByteBuffer getBuffer(long address) { if (address == 0) return emptyBuffer; if (address >= cachedLowerAddress.get() && address < cachedHigherAddress.get()) { ByteBuffer cached = cachedBuffer.get(); if (cached != null) { return cached; } } int blockType = blockType(address); int indexBits = indexBits(blockType); int blockIndex = blockIndex(address, indexBits); long lower = (blockType << BLOCK_TYPE_BITS) | (blockIndex << indexBits); AtomicBoolean blockLock = blockLocks[blockType]; ByteBuffer buf = null; if (blockLock.compareAndSet(false, true)) { try { buf = (ByteBuffer) blockArrays[blockType].get(blockIndex); } finally { blockLock.set(false); } } cachedLowerAddress.set(lower); cachedHigherAddress.set(lower + (1 << indexBits)); cachedBuffer.set(buf); return buf; } /* Helper function that will find an allocated block below the one given. */ private static Map.Entry<Long, Integer> findLowerAllocatedAddress(NavigableMap<Long, Integer> allocatedBlocks ,long address) { Map.Entry<Long, Integer> lowerEntry = allocatedBlocks.floorEntry(Long.valueOf(address)); if (lowerEntry != null && (address <= (lowerEntry.getKey() + lowerEntry.getValue()))) { return lowerEntry; } return null; } public static Map.Entry<Long, Integer> findAllocatedAddress(long address) { Map.Entry<Long, Integer> lowerEntry = findLowerAllocatedAddress(allocatedDirectBlocks, address); if (lowerEntry == null) { lowerEntry = findLowerAllocatedAddress(allocatedHeapBlocks, address); } return lowerEntry; } /* When doing bulk operations, this can be useful. It returns a ByteBuffer positioned at the place referred to by the address. It's duplicated so the user is free to change the position as necessary. ThrowS an exception if the block that corresponds to the address has been freed. */ public static ByteBuffer getBoundedBuffer(long address) { if (address == 0) return emptyBuffer; Map.Entry<Long, Integer> lowerEntry = findAllocatedAddress(address); if (lowerEntry == null) { throw new IllegalStateException("The block that corresponds to the address "+ address+" is not allocated in memory"); } long lowerAddress = lowerEntry.getKey(); int lowerSize = lowerEntry.getValue(); int blockType = blockType(address); int indexBits = indexBits(blockType); int blockIndex = blockIndex(address, indexBits); int positionIndex = positionIndex(address, indexBits); int size = (int)(lowerAddress + lowerSize - address); ByteBuffer buf = null; AtomicBoolean blockLock = blockLocks[blockType]; if (blockLock.compareAndSet(false, true)) { try { buf = ((ByteBuffer) blockArrays[blockType].get(blockIndex)).duplicate(); } finally { blockLock.set(false); } } buf.position(positionIndex); buf.limit(positionIndex + size); return buf; } /* This returns -1 if `address` has already been freed. */ public static int allocatedSize(long address) { Integer sizeInt = allocatedDirectBlocks.get(address); if (sizeInt == null) { sizeInt = allocatedHeapBlocks.get(address); if (sizeInt == null) { return -1; } } return sizeInt.intValue(); } /** Read APIs **/ public static byte get(long address) { return getBuffer(address).get(positionIndex(address)); } public static short getShort(long address) { return getBuffer(address).getShort(positionIndex(address)); } public static char getChar(long address) { return getBuffer(address).getChar(positionIndex(address)); } public static int getInt(long address) { return getBuffer(address).getInt(positionIndex(address)); } public static long getLong(long address) { return getBuffer(address).getLong(positionIndex(address)); } public static float getFloat(long address) { return getBuffer(address).getFloat(positionIndex(address)); } public static double getDouble(long address) { return getBuffer(address).getDouble(positionIndex(address)); } /** Write APIs **/ public static void put(long address, byte val) { getBuffer(address).put(positionIndex(address), val); } public static void putShort(long address, short val) { getBuffer(address).putShort(positionIndex(address), val); } public static void putChar(long address, char val) { getBuffer(address).putChar(positionIndex(address), val); } public static void putInt(long address, int val) { getBuffer(address).putInt(positionIndex(address), val); } public static void putLong(long address, long val) { getBuffer(address).putLong(positionIndex(address), val); } public static void putFloat(long address, float val) { getBuffer(address).putFloat(positionIndex(address), val); } public static void putDouble(long address, double val) { getBuffer(address).putDouble(positionIndex(address), val); } /** Monitoring **/ private static void printHeading(String heading) { System.out.print("***"); System.out.print(heading); System.out.println("***"); } private static void printAddressMap(String heading, Map<Long, Integer> addresses) { printHeading(heading); if (addresses.size() > 0) { for (Map.Entry<Long, Integer> entry: addresses.entrySet()) { Long address = entry.getKey(); Integer size = entry.getValue(); Long end = entry.getKey() + entry.getValue() - 1; System.out.println(address + "-" + end + " [" + size + " bytes]"); } } else { System.out.println("None"); } } private static void printBlocksMap(String heading, Map<Integer,Queue<Long>> blocks) { printHeading(heading); if (blocks.size() > 0) { for (Map.Entry<Integer, Queue<Long>> entry: blocks.entrySet()) { System.out.println("Region Size: " + entry.getKey() + " bytes"); Queue<Long> freeAddresses = entry.getValue(); if (freeAddresses.size() > 0) { for (Long address: freeAddresses) { System.out.println(" " + address); } } else { System.out.println(" None"); } } } else { System.out.println("None"); } } public static void dumpMemoryManager() { System.out.println("***Eta-Managed Off-Heap Memory***"); printAddressMap("Allocated Direct Blocks", allocatedDirectBlocks); printAddressMap("Allocated Heap Blocks", allocatedHeapBlocks); printAddressMap("Free Direct Addresses", freeDirectAddresses); printAddressMap("Free Heap Addresses", freeHeapAddresses); printBlocksMap("Free Direct Blocks", freeDirectBlocks); printBlocksMap("Free Heap Blocks", freeHeapBlocks); } /** Misc. Utilities **/ private static String renderSize(int size) { return "["+ size + " bytes]"; } private static String renderIsDirect(boolean direct) { return direct? "Direct" : "Heap"; } }
fix typo
rts/src/eta/runtime/io/MemoryManager.java
fix typo
Java
bsd-3-clause
7df880f6552a71364a9ad5da4649d5bc2fdc532e
0
codehaus/xstream,codehaus/xstream
/* * Copyright (C) 2008, 2010 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 13. October 2008 by Joerg Schaible */ package com.thoughtworks.xstream.core.util; public final class FastField { private final String name; private final String declaringClass; public FastField(String definedIn, String name) { this.name = name; this.declaringClass = definedIn; } public FastField(Class definedIn, String name) { this(definedIn == null ? null : definedIn.getName(), name); } public String getName() { return this.name; } public String getDeclaringClass() { return this.declaringClass; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof FastField) { final FastField field = (FastField)obj; if ((declaringClass == null && field.declaringClass != null) || (declaringClass != null && field.declaringClass == null)) { return false; } return name.equals(field.getName()) && (declaringClass == null || declaringClass.equals(field.getDeclaringClass())); } return false; } public int hashCode() { return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode()); } public String toString() { return (declaringClass == null ? "" : declaringClass + ".") + name; } }
xstream/src/java/com/thoughtworks/xstream/core/util/FastField.java
/* * Copyright (C) 2008, 2010 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 13. October 2008 by Joerg Schaible */ package com.thoughtworks.xstream.core.util; public final class FastField { private final String name; private final String declaringClass; public FastField(String definedIn, String name) { this.name = name; this.declaringClass = definedIn; } public FastField(Class definedIn, String name) { this(name, definedIn == null ? null : definedIn.getName()); } public String getName() { return this.name; } public String getDeclaringClass() { return this.declaringClass; } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj instanceof FastField) { final FastField field = (FastField)obj; if ((declaringClass == null && field.declaringClass != null) || (declaringClass != null && field.declaringClass == null)) { return false; } return name.equals(field.getName()) && (declaringClass == null || declaringClass.equals(field.getDeclaringClass())); } return false; } public int hashCode() { return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode()); } public String toString() { return (declaringClass == null ? "" : declaringClass + ".") + name; } }
Fix stupid bug.
xstream/src/java/com/thoughtworks/xstream/core/util/FastField.java
Fix stupid bug.
Java
bsd-3-clause
a8477cab8f36475edc489597ac78488734a3d5fb
0
bureau14/qdb-api-java,bureau14/qdb-api-java
src/test/java/net/quasardb/qdb/timeseries/QueryTest.java
import org.junit.*; import org.hamcrest.Matcher; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.util.StringJoiner; import java.util.Arrays; import java.util.Map; import java.util.stream.Stream; import net.quasardb.qdb.ts.Column; import net.quasardb.qdb.ts.Query; import net.quasardb.qdb.ts.QueryBuilder; import net.quasardb.qdb.ts.Result; import net.quasardb.qdb.ts.Row; import net.quasardb.qdb.ts.WritableRow; import net.quasardb.qdb.ts.Value; import net.quasardb.qdb.ts.TimeRange; import net.quasardb.qdb.exception.InputException; import net.quasardb.qdb.Helpers; import net.quasardb.qdb.QdbTimeSeries; public class QueryTest { @Test public void canCreateEmptyQuery() throws Exception { Query q = Query.create(); } @Test public void canCreateStringyQuery() throws Exception { Query q = Query.of(""); } @Test(expected = InputException.class) public void cannotExecuteEmptyQuery() throws Exception { Query.create() .execute(Helpers.getSession()); } @Test public void canExecuteValidQuery() throws Exception { Value.Type[] valueTypes = { Value.Type.INT64, Value.Type.DOUBLE, Value.Type.TIMESTAMP, Value.Type.BLOB }; for (Value.Type valueType : valueTypes) { Column[] definition = Helpers.generateTableColumns(valueType, 1); WritableRow[] rows = Helpers.generateTableRows(definition, 1); QdbTimeSeries series = Helpers.seedTable(definition, rows); Result r = new QueryBuilder() .add("select") .add(definition[0].getName()) .add("from") .add(series.getName()) .in(Helpers.rangeFromRows(rows)) .asQuery() .execute(Helpers.getSession()); assertThat(r.columns.length, (is(definition.length))); assertThat(r.rows.length, (is(rows.length))); assertThat(r.columns[0], (is(definition[0].getName()))); Row originalRow = rows[0]; Row outputRow = r.rows[0]; assertThat(outputRow, is(originalRow)); } } @Test public void canAccessResultAsStream() throws Exception { Value.Type[] valueTypes = { Value.Type.INT64, Value.Type.DOUBLE, Value.Type.TIMESTAMP, Value.Type.BLOB }; for (Value.Type valueType : valueTypes) { Column[] definition = Helpers.generateTableColumns(valueType, 2); WritableRow[] rows = Helpers.generateTableRows(definition, 10); QdbTimeSeries series = Helpers.seedTable(definition, rows); Result r = new QueryBuilder() .add("select") .add(definition[0].getName()) .add("from") .add(series.getName()) .in(Helpers.rangeFromRows(rows)) .asQuery() .execute(Helpers.getSession()); assertThat(r.stream().count(), is(equalTo(Long.valueOf(r.rows.length)))); } } }
QDB-2873 Move query tests to JNI repo
src/test/java/net/quasardb/qdb/timeseries/QueryTest.java
QDB-2873 Move query tests to JNI repo
Java
mit
286cf17811410fd19fb77585f1d55fcee9813068
0
TechReborn/TechReborn
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package techreborn.client.gui; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.LiteralText; import org.apache.commons.lang3.tuple.Pair; import reborncore.client.gui.builder.GuiBase; import reborncore.client.gui.builder.widget.GuiButtonExtended; import reborncore.client.gui.builder.widget.GuiButtonUpDown; import reborncore.client.gui.builder.widget.GuiButtonUpDown.UpDownButtonType; import reborncore.client.gui.guibuilder.GuiBuilder; import reborncore.client.screen.builder.BuiltScreenHandler; import reborncore.common.network.NetworkManager; import reborncore.common.powerSystem.PowerSystem; import reborncore.common.util.Color; import reborncore.common.util.Torus; import techreborn.blockentity.machine.multiblock.FusionControlComputerBlockEntity; import techreborn.packets.ServerboundPackets; import java.util.Optional; public class GuiFusionReactor extends GuiBase<BuiltScreenHandler> { private final FusionControlComputerBlockEntity blockEntity; public GuiFusionReactor(int syncID, final PlayerEntity player, final FusionControlComputerBlockEntity blockEntity) { super(player, blockEntity, blockEntity.createScreenHandler(syncID, player)); this.blockEntity = blockEntity; } @Override public void init() { super.init(); addButton(new GuiButtonUpDown(x + 121, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(5), UpDownButtonType.FASTFORWARD)); addButton(new GuiButtonUpDown(x + 121 + 12, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(1), UpDownButtonType.FORWARD)); addButton(new GuiButtonUpDown(x + 121 + 24, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(-5), UpDownButtonType.REWIND)); addButton(new GuiButtonUpDown(x + 121 + 36, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(-1), UpDownButtonType.FASTREWIND)); } @Override protected void drawBackground(MatrixStack matrixStack, final float partialTicks, final int mouseX, final int mouseY) { super.drawBackground(matrixStack, partialTicks, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.BACKGROUND; drawSlot(matrixStack, 34, 47, layer); drawSlot(matrixStack, 126, 47, layer); drawOutputSlot(matrixStack, 80, 47, layer); builder.drawJEIButton(matrixStack, this, 158, 5, layer); if (blockEntity.isMultiblockValid()) { builder.drawHologramButton(matrixStack, this, 6, 4, mouseX, mouseY, layer); } } @Override protected void drawForeground(MatrixStack matrixStack, final int mouseX, final int mouseY) { super.drawForeground(matrixStack, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.FOREGROUND; builder.drawProgressBar(matrixStack, this, blockEntity.getProgressScaled(100), 100, 55, 51, mouseX, mouseY, GuiBuilder.ProgressDirection.RIGHT, layer); builder.drawProgressBar(matrixStack, this, blockEntity.getProgressScaled(100), 100, 105, 51, mouseX, mouseY, GuiBuilder.ProgressDirection.LEFT, layer); if (blockEntity.isMultiblockValid()) { addHologramButton(6, 4, 212, layer).clickHandler(this::hologramToggle); drawCentredText(matrixStack, blockEntity.getStateText(), 20, Color.BLUE.darker().getColor(), layer); if (blockEntity.state == 2) { drawCentredText(matrixStack, new LiteralText(PowerSystem.getLocalizedPower(blockEntity.getPowerChange())).append("/t"), 30, Color.GREEN.darker().getColor(), layer); } } else { builder.drawMultiblockMissingBar(matrixStack, this, layer); addHologramButton(76, 56, 212, layer).clickHandler(this::hologramToggle); builder.drawHologramButton(matrixStack, this, 76, 56, mouseX, mouseY, layer); Optional<Pair<Integer, Integer>> stackSize = getCoilStackCount(); if (stackSize.isPresent()) { if (stackSize.get().getLeft() > 0) { drawCentredText(matrixStack, new LiteralText("Required Coils: ") .append(String.valueOf(stackSize.get().getLeft())) .append("x64 +") .append(String.valueOf(stackSize.get().getRight())) , 25, 0xFFFFFF, layer); } else { drawCentredText(matrixStack, new LiteralText("Required Coils: ").append(String.valueOf(stackSize.get().getRight())), 25, 0xFFFFFF, layer); } } } drawTextWithShadow(matrixStack, client.textRenderer, new LiteralText("Size: ").append(String.valueOf(blockEntity.size)), 83, 81, 0xFFFFFF); drawTextWithShadow(matrixStack, client.textRenderer, new LiteralText(String.valueOf(blockEntity.getPowerMultiplier())).append("x"), 10, 81, 0xFFFFFF); builder.drawMultiEnergyBar(matrixStack, this, 9, 19, (int) this.blockEntity.getEnergy(), (int) this.blockEntity.getMaxStoredPower(), mouseX, mouseY, 0, layer); } public void hologramToggle(GuiButtonExtended button, double x, double y) { blockEntity.renderMultiblock ^= !hideGuiElements(); } private void sendSizeChange(int sizeDelta) { NetworkManager.sendToServer(ServerboundPackets.createPacketFusionControlSize(sizeDelta, blockEntity.getPos())); } public Optional<Pair<Integer, Integer>> getCoilStackCount() { if (!Torus.getTorusSizeCache().containsKey(blockEntity.size)) { return Optional.empty(); } int count = Torus.getTorusSizeCache().get(blockEntity.size); return Optional.of(Pair.of(count / 64, count % 64)); } }
src/main/java/techreborn/client/gui/GuiFusionReactor.java
/* * This file is part of TechReborn, licensed under the MIT License (MIT). * * Copyright (c) 2020 TechReborn * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package techreborn.client.gui; import net.minecraft.client.gui.widget.ButtonWidget; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.LiteralText; import org.apache.commons.lang3.tuple.Pair; import reborncore.client.gui.builder.GuiBase; import reborncore.client.gui.builder.widget.GuiButtonExtended; import reborncore.client.gui.builder.widget.GuiButtonUpDown; import reborncore.client.gui.builder.widget.GuiButtonUpDown.UpDownButtonType; import reborncore.client.gui.guibuilder.GuiBuilder; import reborncore.client.screen.builder.BuiltScreenHandler; import reborncore.common.network.NetworkManager; import reborncore.common.powerSystem.PowerSystem; import reborncore.common.util.Color; import reborncore.common.util.Torus; import techreborn.blockentity.machine.multiblock.FusionControlComputerBlockEntity; import techreborn.packets.ServerboundPackets; import java.util.Optional; public class GuiFusionReactor extends GuiBase<BuiltScreenHandler> { private final FusionControlComputerBlockEntity blockEntity; public GuiFusionReactor(int syncID, final PlayerEntity player, final FusionControlComputerBlockEntity blockEntity) { super(player, blockEntity, blockEntity.createScreenHandler(syncID, player)); this.blockEntity = blockEntity; } @Override public void init() { super.init(); addButton(new GuiButtonUpDown(x + 121, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(5), UpDownButtonType.FASTFORWARD)); addButton(new GuiButtonUpDown(x + 121 + 12, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(1), UpDownButtonType.FORWARD)); addButton(new GuiButtonUpDown(x + 121 + 24, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(-5), UpDownButtonType.REWIND)); addButton(new GuiButtonUpDown(x + 121 + 36, y + 79, this, (ButtonWidget buttonWidget) -> sendSizeChange(-1), UpDownButtonType.FASTREWIND)); } @Override protected void drawBackground(MatrixStack matrixStack, final float partialTicks, final int mouseX, final int mouseY) { super.drawBackground(matrixStack, partialTicks, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.BACKGROUND; drawSlot(matrixStack, 34, 47, layer); drawSlot(matrixStack, 126, 47, layer); drawOutputSlot(matrixStack, 80, 47, layer); builder.drawJEIButton(matrixStack, this, 158, 5, layer); if (blockEntity.isMultiblockValid()) { builder.drawHologramButton(matrixStack, this, 6, 4, mouseX, mouseY, layer); } } @Override protected void drawForeground(MatrixStack matrixStack, final int mouseX, final int mouseY) { super.drawForeground(matrixStack, mouseX, mouseY); final GuiBase.Layer layer = GuiBase.Layer.FOREGROUND; builder.drawProgressBar(matrixStack, this, blockEntity.getProgressScaled(100), 100, 55, 51, mouseX, mouseY, GuiBuilder.ProgressDirection.RIGHT, layer); builder.drawProgressBar(matrixStack, this, blockEntity.getProgressScaled(100), 100, 105, 51, mouseX, mouseY, GuiBuilder.ProgressDirection.LEFT, layer); if (blockEntity.isMultiblockValid()) { addHologramButton(6, 4, 212, layer).clickHandler(this::hologramToggle); drawCentredText(matrixStack, blockEntity.getStateText(), 20, Color.BLUE.darker().getColor(), layer); if (blockEntity.state == 2) { drawCentredText(matrixStack, new LiteralText(PowerSystem.getLocalizedPower(blockEntity.getPowerChange())).append("/t"), 30, Color.GREEN.darker().getColor(), layer); } } else { builder.drawMultiblockMissingBar(matrixStack, this, layer); addHologramButton(76, 56, 212, layer).clickHandler(this::hologramToggle); builder.drawHologramButton(matrixStack, this, 76, 56, mouseX, mouseY, layer); Optional<Pair<Integer, Integer>> stackSize = getCoilStackCount(); if (stackSize.isPresent()) { if (stackSize.get().getLeft() > 0) { drawCentredText(matrixStack, new LiteralText("Required Coils: ") .append(String.valueOf(stackSize.get().getLeft())) .append("x64 +") .append(String.valueOf(stackSize.get().getRight())) , 25, 0xFFFFFF, layer); } else { drawCentredText(matrixStack, new LiteralText("Required Coils: ").append(String.valueOf(stackSize.get().getRight())), 25, 0xFFFFFF, layer); } } } drawTextWithShadow(matrixStack, client.textRenderer, new LiteralText("Size: ").append(String.valueOf(blockEntity.size)), 83, 81, 0xFFFFFF); drawTextWithShadow(matrixStack, client.textRenderer, new LiteralText(String.valueOf(blockEntity.getPowerMultiplier())).append("x"), 10, 81, 0xFFFFFF); builder.drawMultiEnergyBar(matrixStack, this, 9, 19, (int) this.blockEntity.getEnergy(), (int) this.blockEntity.getMaxStoredPower(), mouseX, mouseY, 0, layer); } public void hologramToggle(GuiButtonExtended button, double x, double y) { blockEntity.renderMultiblock ^= !hideGuiElements(); } private void sendSizeChange(int sizeDelta) { NetworkManager.sendToServer(ServerboundPackets.createPacketFusionControlSize(sizeDelta, blockEntity.getPos())); } public Optional<Pair<Integer, Integer>> getCoilStackCount() { if (!Torus.TORUS_SIZE_MAP.containsKey(blockEntity.size)) { return Optional.empty(); } int count = Torus.TORUS_SIZE_MAP.get(blockEntity.size); return Optional.of(Pair.of(count / 64, count % 64)); } }
Use new getTorusSizeCache
src/main/java/techreborn/client/gui/GuiFusionReactor.java
Use new getTorusSizeCache
Java
mit
42551fb15d3b8b797791f2c6d5d15896c9931fb8
0
ruslan120101/JavaFX-TankAttack,ruslan120101/JavaFX-TankAttack,ruslan120101/TankAttack-JavaFX,ruslan120101/TankAttack-JavaFX,ruslan120101/JavaFX-TankAttack,ruslan120101/TankAttack-JavaFX
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tankattack; import Sprites.*; import java.util.*; import javafx.animation.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.stage.*; import javafx.util.*; /** * * @author Ruslan */ public abstract class World { public static boolean isListeningForInput = true; private Stage myStage; private Scene scene; private Group root; private Circle myEnemy; private Point2D myEnemyVelocity; private Random myGenerator = new Random(); private ArrayList<Sprite> sprites; private Player playerSprite; private Timeline timeline; // Setters, Getters public synchronized void addSprite(Sprite s) { if (sprites == null) { sprites = new ArrayList(); } synchronized(sprites) { sprites.add(s); root.getChildren().add(s); } } public synchronized void removeSprite(Sprite s) { synchronized(sprites) { if (sprites == null) { return; } sprites.remove(s); root.getChildren().remove(s); } } public void setPlayerSprite(Player player) { playerSprite = player; } public Player getPlayerSprite() { return playerSprite; } public Group getGroup() { return this.root; } public void setGroup(Group root) { this.root = root; } public Scene getScene() { return this.scene; } public void setScene(Scene scene) { this.scene = scene; } // Real Methods // Constructors // Create Scene, Then Init Animation. Rest of methods are helpers. public World() { throw new UnsupportedOperationException("need to pass in a stage"); } public World(Stage stage) { this.myStage = stage; } public Scene createScene() { root = new Group(); createInitialSprites(); scene = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE); scene.setOnKeyPressed(e -> handleKeyInput(e)); scene.setOnKeyReleased(e -> handleKeyRelease(e)); return scene; } public void initAnimation() { KeyFrame frame = new KeyFrame(Duration.millis(1000 / TankAttack.NUM_FRAMES_PER_SECOND), e -> updateSprites()); if (timeline == null) { timeline = new Timeline(); } timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(frame); timeline.play(); } public abstract void createInitialSprites(); public void createPlayerSprite() { Player player = new Player(TankAttack.gameWidth/2 , TankAttack.gameHeight / 2, this); setPlayerSprite(player); } private void updateSprites() { // System.out.println("All is well. Printing animation 60 times a second."); ////// DONE //////////////////////////// playerSprite.updateLocation(); ////// DONE //////////////////////////// ////// IMPLEMENT //////////////////////////// // Handle Player Firing handleFiring(); // Other Updates updateEnemySprites(); // also handles enemy fire // Bullet Movement updateBulletMovements(); // Register Collisions / Hits // handleCollision(); // Check for win checkForWin(); ////// IMPLEMENT //////////////////////////// } private void endOfLevel() { timeline.pause(); // TODO: Display level complete. showEndOfLevelText(); // Tell TankAttack to put up the next world. signalEndOfLevel(); } private void showEndOfLevelText() { System.out.println("TODO: Animate text over this level's end saying END OF LEVEL."); } public abstract void signalEndOfLevel(); public void handleKeyInput(KeyEvent e) { modifyDirControllerState(e, true); } public void handleKeyRelease(KeyEvent e) { modifyDirControllerState(e, false); } private void modifyDirControllerState(KeyEvent key, boolean newState) { KeyCode keyCode = key.getCode(); if (keyCode == KeyCode.RIGHT) { DirController.rightPressed = newState; } else if (keyCode == KeyCode.LEFT) { DirController.leftPressed = newState; } else if (keyCode == KeyCode.UP) { DirController.upPressed = newState; } else if (keyCode == KeyCode.DOWN) { DirController.downPressed = newState; } else if (keyCode == KeyCode.SPACE) { DirController.spacePressed = newState; } // TODO: Implement space bar to shoot, and cheat codes, here. } private void checkForWin() { // Temporary end to game if (playerSprite.getTranslateX() < 10) { System.out.println("updateSprites calling finish."); endOfLevel(); // TODO Implement this. // Player is left all alone. Stop animation. Level defeated. } } private void handleCollision() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private void updateEnemySprites() { Enemy enemy; for (Sprite s : sprites) { if (s instanceof Enemy) { enemy = (Enemy)s; // Movement enemy.updateEnemyXY(); // Firing if (enemy.isFiring()) { handleEnemyFiring(enemy); } } } } // Player firing, NOT enemy firing. private void handleFiring() { // Check if space bar pressed, create new bullets for Player if (DirController.spacePressed) { new Bullet(playerSprite.getBulletOffsetX(), playerSprite.getBulletOffsetY(), this, true); } } private void handleEnemyFiring(Enemy enemy) { System.out.println("TODO: implement enemy firing inside World [handleEnemyFiring]"); } private void updateBulletMovements() { Bullet b; for (Sprite s : sprites) { if (s instanceof Bullet) { b = (Bullet)s; b.updateXY(); } } } }
src/tankattack/World.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package tankattack; import Sprites.*; import java.util.*; import javafx.animation.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.image.*; import javafx.scene.input.*; import javafx.scene.paint.*; import javafx.scene.shape.*; import javafx.stage.*; import javafx.util.*; /** * * @author Ruslan */ public abstract class World { public static boolean isListeningForInput = true; private Stage myStage; private Scene scene; private Group root; private Circle myEnemy; private Point2D myEnemyVelocity; private Random myGenerator = new Random(); private ArrayList<Sprite> sprites; private Player playerSprite; private Timeline timeline; // Setters, Getters public void addSprite(Sprite s) { if (sprites == null) { sprites = new ArrayList(); } sprites.add(s); root.getChildren().add(s); } public void removeSprite(Sprite s) { if (sprites == null) { return; } sprites.remove(s); root.getChildren().remove(s); } public void setPlayerSprite(Player player) { playerSprite = player; } public Player getPlayerSprite() { return playerSprite; } public Group getGroup() { return this.root; } public void setGroup(Group root) { this.root = root; } public Scene getScene() { return this.scene; } public void setScene(Scene scene) { this.scene = scene; } // Real Methods // Constructors // Create Scene, Then Init Animation. Rest of methods are helpers. public World() { throw new UnsupportedOperationException("need to pass in a stage"); } public World(Stage stage) { this.myStage = stage; } public Scene createScene() { root = new Group(); createInitialSprites(); scene = new Scene(root, TankAttack.gameWidth, TankAttack.gameHeight, Color.CORNFLOWERBLUE); scene.setOnKeyPressed(e -> handleKeyInput(e)); scene.setOnKeyReleased(e -> handleKeyRelease(e)); return scene; } public void initAnimation() { KeyFrame frame = new KeyFrame(Duration.millis(1000 / TankAttack.NUM_FRAMES_PER_SECOND), e -> updateSprites()); if (timeline == null) { timeline = new Timeline(); } timeline.setCycleCount(Animation.INDEFINITE); timeline.getKeyFrames().add(frame); timeline.play(); } public abstract void createInitialSprites(); public void createPlayerSprite() { Player player = new Player(TankAttack.gameWidth/2 , TankAttack.gameHeight / 2, this); setPlayerSprite(player); } private void updateSprites() { // System.out.println("All is well. Printing animation 60 times a second."); ////// DONE //////////////////////////// playerSprite.updateLocation(); ////// DONE //////////////////////////// ////// IMPLEMENT //////////////////////////// // Other Updates updateEnemySprites(); // Handle Firing handleFiring(); // Register Collisions / Hits // handleCollision(); // Check for win checkForWin(); ////// IMPLEMENT //////////////////////////// } private void endOfLevel() { timeline.pause(); // TODO: Display level complete. showEndOfLevelText(); // Tell TankAttack to put up the next world. signalEndOfLevel(); } private void showEndOfLevelText() { System.out.println("TODO: Animate text over this level's end saying END OF LEVEL."); } public abstract void signalEndOfLevel(); public void handleKeyInput(KeyEvent e) { modifyDirControllerState(e, true); } public void handleKeyRelease(KeyEvent e) { modifyDirControllerState(e, false); } private void modifyDirControllerState(KeyEvent key, boolean newState) { KeyCode keyCode = key.getCode(); if (keyCode == KeyCode.RIGHT) { DirController.rightPressed = newState; } else if (keyCode == KeyCode.LEFT) { DirController.leftPressed = newState; } else if (keyCode == KeyCode.UP) { DirController.upPressed = newState; } else if (keyCode == KeyCode.DOWN) { DirController.downPressed = newState; } else if (keyCode == KeyCode.SPACE) { DirController.spacePressed = newState; } // TODO: Implement space bar to shoot, and cheat codes, here. } private void checkForWin() { // Temporary end to game if (playerSprite.getTranslateX() < 10) { System.out.println("updateSprites calling finish."); endOfLevel(); // TODO Implement this. // Player is left all alone. Stop animation. Level defeated. } } private void handleCollision() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } private void updateEnemySprites() { Enemy enemy; for (Sprite s : sprites) { if (s instanceof Enemy) { enemy = (Enemy)s; // Movement enemy.updateEnemyXY(); // Firing if (enemy.isFiring()) { handleEnemyFiring(enemy); } } } } // Player firing, NOT enemy firing. private void handleFiring() { // Check if space bar pressed, create new bullets for Player if (DirController.spacePressed) { // Implement. System.out.println("PEW PEW"); } // Update existing bullets that are moving // Handle enemy firing } private void handleEnemyFiring(Enemy enemy) { System.out.println("TODO: implement enemy firing inside World [handleEnemyFiring]"); } }
big sloppy commit. yolo.
src/tankattack/World.java
big sloppy commit. yolo.
Java
agpl-3.0
01aa97b1fd52cce6b127fda83dc5195a8cf25f8d
0
kuali/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs-devops-automation-fork,ua-eas/kfs-devops-automation-fork,bhutchinson/kfs,bhutchinson/kfs,quikkian-ua-devops/will-financials,ua-eas/kfs,kuali/kfs,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,UniversityOfHawaii/kfs,ua-eas/kfs,ua-eas/kfs,bhutchinson/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,UniversityOfHawaii/kfs,quikkian-ua-devops/kfs,kuali/kfs,kkronenb/kfs,ua-eas/kfs-devops-automation-fork,UniversityOfHawaii/kfs,smith750/kfs,kkronenb/kfs,kkronenb/kfs,kuali/kfs,quikkian-ua-devops/will-financials,smith750/kfs,smith750/kfs,quikkian-ua-devops/kfs,bhutchinson/kfs,kkronenb/kfs,ua-eas/kfs,quikkian-ua-devops/will-financials,quikkian-ua-devops/kfs,smith750/kfs,kuali/kfs,ua-eas/kfs-devops-automation-fork
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.tem.document.validation.impl; import org.kuali.kfs.module.tem.TemKeyConstants; import org.kuali.kfs.module.tem.TemPropertyConstants; import org.kuali.kfs.module.tem.document.TravelAuthorizationDocument; import org.kuali.kfs.sys.document.validation.GenericValidation; import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.util.ObjectUtils; public class TravelAuthBlanketTripTypeValidation extends GenericValidation { //@Override @Override public boolean validate(AttributedDocumentEvent event) { boolean rulePassed = true; TravelAuthorizationDocument taDocument = (TravelAuthorizationDocument)event.getDocument(); if (!ObjectUtils.isNull(taDocument.getTripType())) { if (taDocument.getTripType().isBlanketTravel()) { // If the user selects Blanket Trip Type, airfare amount and the Trip Detail Estimate should not be completed. (Note: // Blanket Travel implies in-state travel) if (!ObjectUtils.isNull(taDocument.getPerDiemExpenses()) && !taDocument.getPerDiemExpenses().isEmpty()) { GlobalVariables.getMessageMap().putError(TemPropertyConstants.PER_DIEM_EXP, TemKeyConstants.ERROR_TA_BLANKET_TYPE_NO_ESTIMATE); taDocument.logErrors(); rulePassed = false; } if (!ObjectUtils.isNull(taDocument.getActualExpenses()) && !taDocument.getActualExpenses().isEmpty()) { GlobalVariables.getMessageMap().putError(TemPropertyConstants.NEW_ACTUAL_EXPENSE_LINE, TemKeyConstants.ERROR_TA_BLANKET_TYPE_NO_EXPENSES); taDocument.logErrors(); rulePassed = false; } } } return rulePassed; } }
work/src/org/kuali/kfs/module/tem/document/validation/impl/TravelAuthBlanketTripTypeValidation.java
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.kfs.module.tem.document.validation.impl; import org.kuali.kfs.module.tem.TemKeyConstants; import org.kuali.kfs.module.tem.TemPropertyConstants; import org.kuali.kfs.module.tem.document.TravelAuthorizationDocument; import org.kuali.kfs.sys.document.validation.GenericValidation; import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent; import org.kuali.rice.krad.util.GlobalVariables; public class TravelAuthBlanketTripTypeValidation extends GenericValidation { //@Override @Override public boolean validate(AttributedDocumentEvent event) { boolean rulePassed = true; TravelAuthorizationDocument taDocument = (TravelAuthorizationDocument)event.getDocument(); if (taDocument.getTripType() != null) { if (taDocument.getTripType().isBlanketTravel()) { // If the user selects Blanket Trip Type, airfare amount and the Trip Detail Estimate should not be completed. (Note: // Blanket Travel implies in-state travel) if (taDocument.getPerDiemExpenses() != null && taDocument.getPerDiemExpenses().size() > 0) { GlobalVariables.getMessageMap().putError(TemPropertyConstants.PER_DIEM_EXP, TemKeyConstants.ERROR_TA_BLANKET_TYPE_NO_ESTIMATE); taDocument.logErrors(); rulePassed = false; } if (taDocument.getActualExpenses() != null && taDocument.getActualExpenses().size() > 0) { GlobalVariables.getMessageMap().putError(TemPropertyConstants.NEW_ACTUAL_EXPENSE_LINE, TemKeyConstants.ERROR_TA_BLANKET_TYPE_NO_EXPENSES); taDocument.logErrors(); rulePassed = false; } } } return rulePassed; } }
KFSMI-11272: avoid npe's in TravelAuthBlanketTripTypeValidation
work/src/org/kuali/kfs/module/tem/document/validation/impl/TravelAuthBlanketTripTypeValidation.java
KFSMI-11272: avoid npe's in TravelAuthBlanketTripTypeValidation
Java
lgpl-2.1
a6f527a4c650c478d27ac654015d254cdd2858de
0
fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui,fjalvingh/domui
package to.etc.domui.component2.form4; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.component.binding.BindReference; import to.etc.domui.component.binding.IBidiBindingConverter; import to.etc.domui.component.meta.MetaManager; import to.etc.domui.component.meta.PropertyMetaModel; import to.etc.domui.component2.controlfactory.ControlCreatorRegistry; import to.etc.domui.dom.html.BindingBuilderBidi; import to.etc.domui.dom.html.IControl; import to.etc.domui.dom.html.Label; import to.etc.domui.dom.html.NodeBase; import to.etc.domui.dom.html.NodeContainer; import to.etc.domui.server.DomApplication; import to.etc.domui.util.DomUtil; import to.etc.webapp.ProgrammerErrorException; import to.etc.webapp.annotations.GProperty; import to.etc.webapp.query.QField; /** * Yet another attempt at a generic form builder, using the Builder pattern. The builder * starts in vertical mode - call horizontal() to move horizontally. * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jun 17, 2014 */ final public class FormBuilder { /** * Handle adding nodes generated by the form builder to the page. * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jun 13, 2012 */ interface IAppender { void add(@NonNull NodeBase formNode); } @NonNull final private IAppender m_appender; private IFormLayouter m_layouter; private boolean m_horizontal; private boolean m_append; private boolean m_currentDirection; /** While set, all controls added will have their readOnly property bound to this reference unless otherwise specified */ @Nullable private BindReference<?, Boolean> m_readOnlyGlobal; @Nullable private BindReference<?, String> m_disabledMessageGlobal; @Nullable private BindReference<?, Boolean> m_disabledGlobal; @Nullable private BuilderData<?, ?> m_currentBuilder; public FormBuilder(@NonNull IAppender appender) { m_appender = appender; m_layouter = new ResponsiveFormLayouter(appender); // m_layouter = new TableFormLayouter(appender); } public FormBuilder(@NonNull IFormLayouter layout, @NonNull IAppender appender) { m_appender = appender; m_layouter = layout; } public FormBuilder(@NonNull final NodeContainer nb) { this(nb::add); } @NonNull public FormBuilder append() { m_append = true; return this; } public FormBuilder nl() { m_layouter.clear(); return this; } @NonNull public FormBuilder horizontal() { m_horizontal = true; m_layouter.setHorizontal(true); return this; } @NonNull public FormBuilder vertical() { m_horizontal = false; m_layouter.setHorizontal(false); return this; } static private <I, V> BindReference<I, V> createRef(@NonNull I instance, @NonNull String property, @NonNull Class<V> type) { PropertyMetaModel<?> pmm = MetaManager.getPropertyMeta(instance.getClass(), property); if(DomUtil.getBoxedForPrimitive(pmm.getActualType()) != DomUtil.getBoxedForPrimitive(type)) { throw new ProgrammerErrorException(pmm + " must be of type " + type.getName()); } return new BindReference<>(instance, (PropertyMetaModel<V>) pmm); } static private <I, V> BindReference<I, V> createRef(@NonNull I instance, @NonNull QField<I, V> property) { PropertyMetaModel<V> pmm = MetaManager.getPropertyMeta(instance.getClass(), property); //if(DomUtil.getBoxedForPrimitive(pmm.getActualType()) != DomUtil.getBoxedForPrimitive(property.)) { // throw new ProgrammerErrorException(pmm + " must be of type " + type.getName()); //} return new BindReference<>(instance, pmm); } /** * By default bind all next components' readOnly property to the specified Boolean property. This binding * takes effect except if a more detailed readOnly binding is specified. */ @NonNull public <I> FormBuilder readOnlyAll(@NonNull I instance, @NonNull String property) { m_readOnlyGlobal = createRef(instance, property, Boolean.class); return this; } /** * Clear the global "read only" binding as set by {@link #readOnlyAll(Object, String)}, so that components * after this are no longer bound to the previously set property. */ @NonNull public FormBuilder readOnlyAllClear() { m_readOnlyGlobal = null; return this; } /** * By default bind all next components' disabled property to the specified Boolean property. This binding * takes effect except if a more detailed binding is specified. */ @NonNull public <I> FormBuilder disabledAll(@NonNull I instance, @NonNull String property) { m_disabledGlobal = createRef(instance, property, Boolean.class); return this; } /** * Clear the global "disabled" binding as set by {@link #disabledAll(Object, String)}, so that components * after this are no longer bound to the previously set property. */ @NonNull public FormBuilder disabledAllClear() { m_disabledGlobal = null; return this; } @NonNull public <I> FormBuilder disabledBecauseAll(@NonNull I instance, @NonNull String property) { m_disabledMessageGlobal = createRef(instance, property, String.class); return this; } @NonNull public FormBuilder disabledBecauseClear() { m_disabledMessageGlobal = null; return this; } /*--------------------------------------------------------------*/ /* CODING: defining (manually created) controls. */ /*--------------------------------------------------------------*/ @NonNull public <T> UntypedControlBuilder<T> property(@NonNull T instance, @GProperty String property) { check(); UntypedControlBuilder<T> currentBuilder = new UntypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = currentBuilder; return currentBuilder; } private void check() { if(null != m_currentBuilder) throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); } //@NonNull //public <T, V, C> ControlBuilder<T, V, C> property(@NonNull T instance, @GProperty String property, IBidiBindingConverter<C, V> converter) { // if(null != m_currentBuilder) // throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); // ControlBuilder<T, V, C> builder = new ControlBuilder<>(instance, (PropertyMetaModel<V>) MetaManager.getPropertyMeta(instance.getClass(), property), converter); // m_currentBuilder = builder; // return builder; //} @NonNull public <T, V> TypedControlBuilder<T, V> property(@NonNull T instance, QField<?, V> property) { check(); TypedControlBuilder<T, V> builder = new TypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = builder; return builder; } //@NonNull //public <T, V, C> ControlBuilder<T, V, C> property(@NonNull T instance, QField<?, V> property, IBidiBindingConverter<C, V> converter) { // if(null != m_currentBuilder) // throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); // ControlBuilder<T, V, C> builder = new ControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property), converter); // m_currentBuilder = builder; // return builder; //} /*----------------------------------------------------------------------*/ /* CODING: Propertyless items. */ /*----------------------------------------------------------------------*/ public ItemBuilder label(@Nullable String label) { check(); ItemBuilder b = new ItemBuilder().label(label); m_currentBuilder = b; return b; } public ItemBuilder label(@Nullable NodeContainer label) { check(); ItemBuilder b = new ItemBuilder().label(label); m_currentBuilder = b; return b; } public void item(@NonNull NodeBase item) throws Exception { addControl(new ItemBuilder(), item, null); resetBuilder(); } public void control(@NonNull NodeBase item) throws Exception { addControl(new ItemBuilder(), item, null); resetBuilder(); } private void resetBuilder() { m_append = false; m_currentBuilder = null; } /*--------------------------------------------------------------*/ /* CODING: Form building code. */ /*--------------------------------------------------------------*/ @NonNull private <I, T, UI extends IControl<T>> UI controlMain(BuilderData<I, T> cb, @Nullable Class<UI> controlClass) throws Exception { ControlCreatorRegistry builder = DomApplication.get().getControlCreatorRegistry(); PropertyMetaModel<T> pmm = cb.m_propertyMetaModel; UI control = builder.createControl(pmm, controlClass); addControl(cb, (NodeBase) control, null); resetBuilder(); return control; } private <I, V> void addControl(BuilderData<I, V> builder,@NonNull NodeBase control, @Nullable IBidiBindingConverter<?, ?> conv) throws Exception { if (control.getClass().getSimpleName().contains("TextArea") && builder.m_labelCss == null) { builder.m_labelCss = "ui-f4-ta"; } NodeContainer lbl = builder.determineLabel(); resetDirection(); m_layouter.addControl(control, lbl, builder.m_controlCss, builder.m_labelCss, m_append); String testid = builder.m_testid; PropertyMetaModel<?> pmm = builder.m_propertyMetaModel; if(null != testid) control.setTestID(testid); else if(control.getTestID() == null) { if(pmm != null) control.setTestID(pmm.getName()); } if(control instanceof IControl) { IControl< ? > ctl = (IControl< ? >) control; if(null != pmm) { Object instance = builder.m_instance; if(null != instance) { //IBidiBindingConverter<Object, Object> conv = (IBidiBindingConverter<Object, Object>) builder.m_converter; if(null == conv) { control.bind().to(instance, pmm); } else { BindingBuilderBidi<?> bind = control.bind(); ((BindingBuilderBidi<Object>) bind).to(instance, (PropertyMetaModel<Object>)pmm, (IBidiBindingConverter<Object, Object>) conv); } } } //-- Do all the readOnly chores Boolean readOnly = builder.m_readOnly; BindReference<?, Boolean> roOnce = builder.m_readOnlyOnce; BindReference<?, Boolean> roGlob = m_readOnlyGlobal; if(null != readOnly) { ctl.setReadOnly(readOnly.booleanValue()); } else if(roOnce != null) { control.bind("readOnly").to(roOnce); } else if(roGlob != null) { control.bind("readOnly").to(roGlob); } //-- Same for disabled - prefer message above the boolean disabled. String diMsg = builder.m_disabledMessage; BindReference<?, String> diMsgOnce = builder.m_disabledMessageOnce; BindReference<?, String> diMsgGlob = m_disabledMessageGlobal; Boolean di = builder.m_disabled; BindReference<?, Boolean> diOnce = builder.m_disabledOnce; BindReference<?, Boolean> diGlob = m_disabledGlobal; if(diMsg != null) { //ctl.setDisabledBecause(diMsg); // FIXME ctl.setDisabled(true); } else if(diMsgOnce != null) { control.bind("disabledBecause").to(diMsgOnce); } else if(diMsgGlob != null) { control.bind("disabledBecause").to(diMsgGlob); } else if(di != null) { ctl.setDisabled(di.booleanValue()); } else if(diOnce != null) { control.bind("disabled").to(diOnce); } else if(diGlob != null) { control.bind("disabled").to(diGlob); } if(builder.isMandatory()) { ctl.setMandatory(true); } } String label = builder.labelTextCalculated(); if (null != builder.m_errorLocation){ control.setErrorLocation(builder.m_errorLocation); } else { if(null != label) { control.setErrorLocation(label); } } if(null != label) control.setCalculcatedId(label.toLowerCase()); } private void resetDirection() { if(m_horizontal == m_currentDirection) return; m_layouter.clear(); m_currentDirection = m_horizontal; } public void appendAfterControl(@NonNull NodeBase what) { m_layouter.appendAfterControl(what); } private class BuilderData<I, V> { protected final I m_instance; protected final PropertyMetaModel<V> m_propertyMetaModel; protected String m_errorLocation; protected String m_nextLabel; protected NodeContainer m_nextLabelControl; protected Boolean m_mandatory; @Nullable protected String m_controlCss; @Nullable protected String m_labelCss; @Nullable protected String m_testid; /** ReadOnly as set directly in the Builder */ protected Boolean m_readOnly; /** When set, the next control's readOnly property will be bound to this reference, after which it will be cleared */ @Nullable protected BindReference<?, Boolean> m_readOnlyOnce; /** disabled as set directly in the Builder */ protected Boolean m_disabled; @Nullable protected BindReference<?, Boolean> m_disabledOnce; /** When set, disable the next component with the specified message. */ @Nullable protected String m_disabledMessage; @Nullable protected BindReference<?, String> m_disabledMessageOnce; public BuilderData(I instance, PropertyMetaModel<V> propertyMetaModel) { m_instance = instance; m_propertyMetaModel = propertyMetaModel; } @Nullable public NodeContainer determineLabel() { NodeContainer res = null; String txt = m_nextLabel; if(null != txt) { //m_nextLabel = null; if(txt.length() != 0) // Not "unlabeled"? res = new Label(txt); } else { res = m_nextLabelControl; if(res == null) { //-- Property known? PropertyMetaModel< ? > pmm = m_propertyMetaModel; if(null != pmm) { txt = pmm.getDefaultLabel(); if(txt != null && txt.length() > 0) res = new Label(txt); } } } if(res != null && calculateMandatory() && !isReadOnly()) { res.addCssClass("ui-f4-mandatory"); } return res; } private boolean calculateMandatory() { Boolean m = m_mandatory; if(null != m) return m.booleanValue(); // If explicitly set: obey that PropertyMetaModel<?> pmm = m_propertyMetaModel; if(null != pmm) { return pmm.isRequired(); } return false; } @Nullable private String labelTextCalculated() { String txt = m_nextLabel; if(null != txt) { if(txt.length() != 0) // Not "unlabeled"? return txt; return null; } else { NodeContainer res = m_nextLabelControl; if(res != null) { return res.getTextContents(); } else { //-- Property known? PropertyMetaModel< ? > pmm = m_propertyMetaModel; if(null != pmm) { txt = pmm.getDefaultLabel(); if(txt != null && txt.length() > 0) return txt; } } } return null; } private boolean isMandatory() { Boolean man = m_mandatory; if(null != man) { return man.booleanValue(); } return false; } private boolean isReadOnly() { Boolean ro = m_readOnly; if(null != ro) { return ro.booleanValue(); } return false; } protected void copyFrom(ItemBuilder o) { this.m_controlCss = o.m_controlCss; this.m_disabled = o.m_disabled; this.m_disabledMessage = o.m_disabledMessage; this.m_disabledMessageOnce = o.m_disabledMessageOnce; this.m_disabledOnce = o.m_disabledOnce; this.m_errorLocation = o.m_errorLocation; this.m_labelCss = o.m_labelCss; this.m_mandatory = o.m_mandatory; this.m_nextLabel = o.m_nextLabel; this.m_nextLabelControl = o.m_nextLabelControl; this.m_readOnly = o.m_readOnly; this.m_readOnlyOnce = o.m_readOnlyOnce; this.m_testid = o.m_testid; } } /** * This builder is for propertyless items, and hence does not contain type information. */ final public class ItemBuilder extends BuilderData<Void, Void>{ public ItemBuilder() { super(null, null); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public ItemBuilder label(@Nullable String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public ItemBuilder label(@Nullable NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public ItemBuilder unlabeled() { label(""); return this; } @NonNull public ItemBuilder mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public ItemBuilder mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } public void item(@NonNull NodeBase item) throws Exception { addControl(this, item, null); resetBuilder(); } public void control(@NonNull NodeBase item) throws Exception { addControl(this, item, null); resetBuilder(); } @NonNull public <T> UntypedControlBuilder<T> property(@NonNull T instance, @GProperty String property) { UntypedControlBuilder<T> currentBuilder = new UntypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = currentBuilder; // This is now current //-- Copy all fields. currentBuilder.copyFrom(this); return currentBuilder; } } /** * A builder that will end in a control, with full types - used with QFields. * * @param <I> The instance. * @param <V> The value type of the property of the instance. */ final public class TypedControlBuilder<I, V> extends BuilderData<I, V> { public TypedControlBuilder(I instance, PropertyMetaModel<V> propertyMeta) { super(instance, propertyMeta); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public TypedControlBuilder<I, V> label(@NonNull String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public TypedControlBuilder<I, V> label(@NonNull NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public TypedControlBuilder<I, V> unlabeled() { label(""); return this; } @NonNull public TypedControlBuilder<I, V> mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public TypedControlBuilder<I, V> mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } @NonNull public TypedControlBuilder<I, V> errorLocation(@NonNull String errorLocation) { m_errorLocation = errorLocation; return this; } /*--------------------------------------------------------------*/ /* CODING: Readonly, mandatory, disabled. */ /*--------------------------------------------------------------*/ @NonNull public TypedControlBuilder<I, V> readOnly() { m_readOnly = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for readOnly. */ @NonNull public TypedControlBuilder<I, V> readOnly(boolean ro) { m_readOnly = Boolean.valueOf(ro); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> TypedControlBuilder<I, V> readOnly(@NonNull X instance, @NonNull String property) { m_readOnlyOnce = createRef(instance, property, Boolean.class); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> TypedControlBuilder<I, V> readOnly(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_readOnlyOnce = createRef(instance, property); return this; } @NonNull public TypedControlBuilder<I, V> disabled() { m_disabled = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for disabled. */ @NonNull public TypedControlBuilder<I, V> disabled(boolean ro) { m_disabled = Boolean.valueOf(ro); return this; } @NonNull public TypedControlBuilder<I, V> testId(String id) { m_testid = id; return this; } @NonNull public <X> TypedControlBuilder<I, V> disabled(@NonNull X instance, @NonNull String property) { m_disabledOnce = createRef(instance, property, Boolean.class); return this; } @NonNull public <X> TypedControlBuilder<I, V> disabled(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_disabledOnce = createRef(instance, property); return this; } /** * Disables the next component with the specified disable message. */ @NonNull public TypedControlBuilder<I, V> disabledBecause(@Nullable String message) { m_disabledMessage = message; return this; } @NonNull public <X> TypedControlBuilder<I, V> disabledBecause(@NonNull X instance, @NonNull String property) { m_disabledMessageOnce = createRef(instance, property, String.class); return this; } @NonNull public <X> TypedControlBuilder<I, V> disabledBecause(@NonNull X instance, @NonNull QField<X, String> property) { m_disabledMessageOnce = createRef(instance, property); return this; } /** * Adds the specified css class to the control cell. */ @NonNull public TypedControlBuilder<I, V> cssControl(@NonNull String cssClass) { m_controlCss = cssClass; return this; } /** * Adds the specified css class to the label cell. */ @NonNull public TypedControlBuilder<I, V> cssLabel(@NonNull String cssClass) { m_labelCss = cssClass; return this; } /** * Add the specified control. Since the control is manually created this code assumes that the * control is <b>properly configured</b> for it's task! This means that this code will not * make any changes to the control! Specifically: if the form item is marked as "mandatory" * but the control here is not then the control stays optional. * The reverse however is not true: if the control passed in is marked as mandatory then the * form item will be marked as such too. */ public void control(@NonNull IControl<V> control) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, null); resetBuilder(); } public <CV> void control(@NonNull IControl<CV> control, IBidiBindingConverter<CV, V> converter) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, converter); resetBuilder(); } @NonNull public IControl<V> control() throws Exception { return controlMain(this, null); } @NonNull public <C extends IControl<V>> C control(@Nullable Class<C> controlClass) throws Exception { return controlMain(this, controlClass); } } final public class UntypedControlBuilder<I> extends BuilderData<I, Object> { public UntypedControlBuilder(I instance, PropertyMetaModel<?> propertyMeta) { super(instance, (PropertyMetaModel<Object>) propertyMeta); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public UntypedControlBuilder<I> label(@NonNull String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public UntypedControlBuilder<I> label(@NonNull NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public UntypedControlBuilder<I> unlabeled() { label(""); return this; } @NonNull public UntypedControlBuilder<I> mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public UntypedControlBuilder<I> mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } @NonNull public UntypedControlBuilder<I> errorLocation(@NonNull String errorLocation) { m_errorLocation = errorLocation; return this; } /*--------------------------------------------------------------*/ /* CODING: Readonly, mandatory, disabled. */ /*--------------------------------------------------------------*/ @NonNull public UntypedControlBuilder<I> readOnly() { m_readOnly = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for readOnly. */ @NonNull public UntypedControlBuilder<I> readOnly(boolean ro) { m_readOnly = Boolean.valueOf(ro); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> UntypedControlBuilder<I> readOnly(@NonNull X instance, @NonNull String property) { m_readOnlyOnce = createRef(instance, property, Boolean.class); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> UntypedControlBuilder<I> readOnly(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_readOnlyOnce = createRef(instance, property); return this; } @NonNull public UntypedControlBuilder<I> disabled() { m_disabled = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for disabled. */ @NonNull public UntypedControlBuilder<I> disabled(boolean ro) { m_disabled = Boolean.valueOf(ro); return this; } @NonNull public UntypedControlBuilder<I> testId(String id) { m_testid = id; return this; } @NonNull public <X> UntypedControlBuilder<I> disabled(@NonNull X instance, @NonNull String property) { m_disabledOnce = createRef(instance, property, Boolean.class); return this; } @NonNull public <X> UntypedControlBuilder<I> disabled(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_disabledOnce = createRef(instance, property); return this; } /** * Disables the next component with the specified disable message. */ @NonNull public UntypedControlBuilder<I> disabledBecause(@Nullable String message) { m_disabledMessage = message; return this; } @NonNull public <X> UntypedControlBuilder<I> disabledBecause(@NonNull X instance, @NonNull String property) { m_disabledMessageOnce = createRef(instance, property, String.class); return this; } @NonNull public <X> UntypedControlBuilder<I> disabledBecause(@NonNull X instance, @NonNull QField<X, String> property) { m_disabledMessageOnce = createRef(instance, property); return this; } /** * Adds the specified css class to the control cell. */ @NonNull public UntypedControlBuilder<I> cssControl(@NonNull String cssClass) { m_controlCss = cssClass; return this; } /** * Adds the specified css class to the label cell. */ @NonNull public UntypedControlBuilder<I> cssLabel(@NonNull String cssClass) { m_labelCss = cssClass; return this; } /** * Add the specified control. Since the control is manually created this code assumes that the * control is <b>properly configured</b> for it's task! This means that this code will not * make any changes to the control! Specifically: if the form item is marked as "mandatory" * but the control here is not then the control stays optional. * The reverse however is not true: if the control passed in is marked as mandatory then the * form item will be marked as such too. */ public void control(@NonNull IControl<?> control) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, null); resetBuilder(); } public <CV> void control(@NonNull IControl<?> control, IBidiBindingConverter<?, ?> converter) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, converter); resetBuilder(); } @NonNull public IControl<?> control() throws Exception { return controlMain(this, null); } @NonNull public <C extends IControl<?>> C control(@Nullable Class<C> controlClass) throws Exception { ControlCreatorRegistry builder = DomApplication.get().getControlCreatorRegistry(); PropertyMetaModel<Object> pmm = m_propertyMetaModel; C control = (C) builder.createControl(pmm, (Class<IControl<Object>>) controlClass); addControl(this, (NodeBase) control, null); resetBuilder(); return control; } } }
to.etc.domui/src/main/java/to/etc/domui/component2/form4/FormBuilder.java
package to.etc.domui.component2.form4; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.component.binding.BindReference; import to.etc.domui.component.binding.IBidiBindingConverter; import to.etc.domui.component.meta.MetaManager; import to.etc.domui.component.meta.PropertyMetaModel; import to.etc.domui.component2.controlfactory.ControlCreatorRegistry; import to.etc.domui.dom.html.BindingBuilderBidi; import to.etc.domui.dom.html.IControl; import to.etc.domui.dom.html.Label; import to.etc.domui.dom.html.NodeBase; import to.etc.domui.dom.html.NodeContainer; import to.etc.domui.server.DomApplication; import to.etc.domui.util.DomUtil; import to.etc.webapp.ProgrammerErrorException; import to.etc.webapp.annotations.GProperty; import to.etc.webapp.query.QField; /** * Yet another attempt at a generic form builder, using the Builder pattern. The builder * starts in vertical mode - call horizontal() to move horizontally. * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jun 17, 2014 */ final public class FormBuilder { /** * Handle adding nodes generated by the form builder to the page. * * @author <a href="mailto:[email protected]">Frits Jalvingh</a> * Created on Jun 13, 2012 */ interface IAppender { void add(@NonNull NodeBase formNode); } @NonNull final private IAppender m_appender; private IFormLayouter m_layouter; private boolean m_horizontal; private boolean m_append; private boolean m_currentDirection; /** While set, all controls added will have their readOnly property bound to this reference unless otherwise specified */ @Nullable private BindReference<?, Boolean> m_readOnlyGlobal; @Nullable private BindReference<?, String> m_disabledMessageGlobal; @Nullable private BindReference<?, Boolean> m_disabledGlobal; @Nullable private BuilderData<?, ?> m_currentBuilder; public FormBuilder(@NonNull IAppender appender) { m_appender = appender; m_layouter = new ResponsiveFormLayouter(appender); // m_layouter = new TableFormLayouter(appender); } public FormBuilder(@NonNull IFormLayouter layout, @NonNull IAppender appender) { m_appender = appender; m_layouter = layout; } public FormBuilder(@NonNull final NodeContainer nb) { this(nb::add); } @NonNull public FormBuilder append() { m_append = true; return this; } public FormBuilder nl() { m_layouter.clear(); return this; } @NonNull public FormBuilder horizontal() { m_horizontal = true; m_layouter.setHorizontal(true); return this; } @NonNull public FormBuilder vertical() { m_horizontal = false; m_layouter.setHorizontal(false); return this; } static private <I, V> BindReference<I, V> createRef(@NonNull I instance, @NonNull String property, @NonNull Class<V> type) { PropertyMetaModel<?> pmm = MetaManager.getPropertyMeta(instance.getClass(), property); if(DomUtil.getBoxedForPrimitive(pmm.getActualType()) != DomUtil.getBoxedForPrimitive(type)) { throw new ProgrammerErrorException(pmm + " must be of type " + type.getName()); } return new BindReference<>(instance, (PropertyMetaModel<V>) pmm); } static private <I, V> BindReference<I, V> createRef(@NonNull I instance, @NonNull QField<I, V> property) { PropertyMetaModel<V> pmm = MetaManager.getPropertyMeta(instance.getClass(), property); //if(DomUtil.getBoxedForPrimitive(pmm.getActualType()) != DomUtil.getBoxedForPrimitive(property.)) { // throw new ProgrammerErrorException(pmm + " must be of type " + type.getName()); //} return new BindReference<>(instance, pmm); } /** * By default bind all next components' readOnly property to the specified Boolean property. This binding * takes effect except if a more detailed readOnly binding is specified. */ @NonNull public <I> FormBuilder readOnlyAll(@NonNull I instance, @NonNull String property) { m_readOnlyGlobal = createRef(instance, property, Boolean.class); return this; } /** * Clear the global "read only" binding as set by {@link #readOnlyAll(Object, String)}, so that components * after this are no longer bound to the previously set property. */ @NonNull public FormBuilder readOnlyAllClear() { m_readOnlyGlobal = null; return this; } /** * By default bind all next components' disabled property to the specified Boolean property. This binding * takes effect except if a more detailed binding is specified. */ @NonNull public <I> FormBuilder disabledAll(@NonNull I instance, @NonNull String property) { m_disabledGlobal = createRef(instance, property, Boolean.class); return this; } /** * Clear the global "disabled" binding as set by {@link #disabledAll(Object, String)}, so that components * after this are no longer bound to the previously set property. */ @NonNull public FormBuilder disabledAllClear() { m_disabledGlobal = null; return this; } @NonNull public <I> FormBuilder disabledBecauseAll(@NonNull I instance, @NonNull String property) { m_disabledMessageGlobal = createRef(instance, property, String.class); return this; } @NonNull public FormBuilder disabledBecauseClear() { m_disabledMessageGlobal = null; return this; } /*--------------------------------------------------------------*/ /* CODING: defining (manually created) controls. */ /*--------------------------------------------------------------*/ @NonNull public <T> UntypedControlBuilder<T> property(@NonNull T instance, @GProperty String property) { check(); UntypedControlBuilder<T> currentBuilder = new UntypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = currentBuilder; return currentBuilder; } private void check() { if(null != m_currentBuilder) throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); } //@NonNull //public <T, V, C> ControlBuilder<T, V, C> property(@NonNull T instance, @GProperty String property, IBidiBindingConverter<C, V> converter) { // if(null != m_currentBuilder) // throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); // ControlBuilder<T, V, C> builder = new ControlBuilder<>(instance, (PropertyMetaModel<V>) MetaManager.getPropertyMeta(instance.getClass(), property), converter); // m_currentBuilder = builder; // return builder; //} @NonNull public <T, V> TypedControlBuilder<T, V> property(@NonNull T instance, QField<?, V> property) { check(); TypedControlBuilder<T, V> builder = new TypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = builder; return builder; } //@NonNull //public <T, V, C> ControlBuilder<T, V, C> property(@NonNull T instance, QField<?, V> property, IBidiBindingConverter<C, V> converter) { // if(null != m_currentBuilder) // throw new IllegalStateException("You need to end the builder pattern with a call to 'control()'"); // ControlBuilder<T, V, C> builder = new ControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property), converter); // m_currentBuilder = builder; // return builder; //} /*----------------------------------------------------------------------*/ /* CODING: Propertyless items. */ /*----------------------------------------------------------------------*/ public ItemBuilder label(@Nullable String label) { check(); ItemBuilder b = new ItemBuilder().label(label); m_currentBuilder = b; return b; } public ItemBuilder label(@Nullable NodeContainer label) { check(); ItemBuilder b = new ItemBuilder().label(label); m_currentBuilder = b; return b; } public void item(@NonNull NodeBase item) throws Exception { addControl(new ItemBuilder(), item, null); resetBuilder(); } public void control(@NonNull NodeBase item) throws Exception { addControl(new ItemBuilder(), item, null); resetBuilder(); } private void resetBuilder() { m_append = false; m_currentBuilder = null; } /*--------------------------------------------------------------*/ /* CODING: Form building code. */ /*--------------------------------------------------------------*/ @NonNull private <I, T, UI extends IControl<T>> UI controlMain(BuilderData<I, T> cb, @Nullable Class<UI> controlClass) throws Exception { ControlCreatorRegistry builder = DomApplication.get().getControlCreatorRegistry(); PropertyMetaModel<T> pmm = cb.m_propertyMetaModel; UI control = builder.createControl(pmm, controlClass); addControl(cb, (NodeBase) control, null); resetBuilder(); return control; } private <I, V> void addControl(BuilderData<I, V> builder,@NonNull NodeBase control, @Nullable IBidiBindingConverter<?, ?> conv) throws Exception { if (control.getClass().getSimpleName().contains("TextArea") && builder.m_labelCss == null) { builder.m_labelCss = "ui-f4-ta"; } NodeContainer lbl = builder.determineLabel(); resetDirection(); m_layouter.addControl(control, lbl, builder.m_controlCss, builder.m_labelCss, m_append); String testid = builder.m_testid; PropertyMetaModel<?> pmm = builder.m_propertyMetaModel; if(null != testid) control.setTestID(testid); else if(control.getTestID() == null) { if(pmm != null) control.setTestID(pmm.getName()); } if(control instanceof IControl) { IControl< ? > ctl = (IControl< ? >) control; if(null != pmm) { Object instance = builder.m_instance; if(null != instance) { //IBidiBindingConverter<Object, Object> conv = (IBidiBindingConverter<Object, Object>) builder.m_converter; if(null == conv) { control.bind().to(instance, pmm); } else { BindingBuilderBidi<?> bind = control.bind(); ((BindingBuilderBidi<Object>) bind).to(instance, (PropertyMetaModel<Object>)pmm, (IBidiBindingConverter<Object, Object>) conv); } } } //-- Do all the readOnly chores Boolean readOnly = builder.m_readOnly; BindReference<?, Boolean> roOnce = builder.m_readOnlyOnce; BindReference<?, Boolean> roGlob = m_readOnlyGlobal; if(null != readOnly) { ctl.setReadOnly(readOnly.booleanValue()); } else if(roOnce != null) { control.bind("readOnly").to(roOnce); } else if(roGlob != null) { control.bind("readOnly").to(roGlob); } //-- Same for disabled - prefer message above the boolean disabled. String diMsg = builder.m_disabledMessage; BindReference<?, String> diMsgOnce = builder.m_disabledMessageOnce; BindReference<?, String> diMsgGlob = m_disabledMessageGlobal; Boolean di = builder.m_disabled; BindReference<?, Boolean> diOnce = builder.m_disabledOnce; BindReference<?, Boolean> diGlob = m_disabledGlobal; if(diMsg != null) { //ctl.setDisabledBecause(diMsg); // FIXME ctl.setDisabled(true); } else if(diMsgOnce != null) { control.bind("disabledBecause").to(diMsgOnce); } else if(diMsgGlob != null) { control.bind("disabledBecause").to(diMsgGlob); } else if(di != null) { ctl.setDisabled(di.booleanValue()); } else if(diOnce != null) { control.bind("disabled").to(diOnce); } else if(diGlob != null) { control.bind("disabled").to(diGlob); } if(builder.isMandatory()) { ctl.setMandatory(true); } } String label = builder.labelTextCalculated(); if (null != builder.m_errorLocation){ control.setErrorLocation(builder.m_errorLocation); } else { if(null != label) { control.setErrorLocation(label); } } if(null != label) control.setCalculcatedId(label.toLowerCase()); } private void resetDirection() { if(m_horizontal == m_currentDirection) return; m_layouter.clear(); m_currentDirection = m_horizontal; } public void appendAfterControl(@NonNull NodeBase what) { m_layouter.appendAfterControl(what); } private class BuilderData<I, V> { protected final I m_instance; protected final PropertyMetaModel<V> m_propertyMetaModel; protected String m_errorLocation; protected String m_nextLabel; protected NodeContainer m_nextLabelControl; protected Boolean m_mandatory; @Nullable protected String m_controlCss; @Nullable protected String m_labelCss; @Nullable protected String m_testid; /** ReadOnly as set directly in the Builder */ protected Boolean m_readOnly; /** When set, the next control's readOnly property will be bound to this reference, after which it will be cleared */ @Nullable protected BindReference<?, Boolean> m_readOnlyOnce; /** disabled as set directly in the Builder */ protected Boolean m_disabled; @Nullable protected BindReference<?, Boolean> m_disabledOnce; /** When set, disable the next component with the specified message. */ @Nullable protected String m_disabledMessage; @Nullable protected BindReference<?, String> m_disabledMessageOnce; public BuilderData(I instance, PropertyMetaModel<V> propertyMetaModel) { m_instance = instance; m_propertyMetaModel = propertyMetaModel; } @Nullable public NodeContainer determineLabel() { NodeContainer res = null; String txt = m_nextLabel; if(null != txt) { //m_nextLabel = null; if(txt.length() != 0) // Not "unlabeled"? res = new Label(txt); } else { res = m_nextLabelControl; if(res == null) { //-- Property known? PropertyMetaModel< ? > pmm = m_propertyMetaModel; if(null != pmm) { txt = pmm.getDefaultLabel(); if(txt != null && txt.length() > 0) res = new Label(txt); } } } if(res != null && calculateMandatory() && !isReadOnly()) { res.addCssClass("ui-f4-mandatory"); } return res; } private boolean calculateMandatory() { Boolean m = m_mandatory; if(null != m) return m.booleanValue(); // If explicitly set: obey that PropertyMetaModel<?> pmm = m_propertyMetaModel; if(null != pmm) { return pmm.isRequired(); } return false; } @Nullable private String labelTextCalculated() { String txt = m_nextLabel; if(null != txt) { if(txt.length() != 0) // Not "unlabeled"? return txt; return null; } else { NodeContainer res = m_nextLabelControl; if(res != null) { return res.getTextContents(); } else { //-- Property known? PropertyMetaModel< ? > pmm = m_propertyMetaModel; if(null != pmm) { txt = pmm.getDefaultLabel(); if(txt != null && txt.length() > 0) return txt; } } } return null; } private boolean isMandatory() { Boolean man = m_mandatory; if(null != man) { return man.booleanValue(); } return false; } private boolean isReadOnly() { Boolean ro = m_readOnly; if(null != ro) { return ro.booleanValue(); } return false; } protected void copyFrom(ItemBuilder o) { this.m_controlCss = o.m_controlCss; this.m_disabled = o.m_disabled; this.m_disabledMessage = o.m_disabledMessage; this.m_disabledMessageOnce = o.m_disabledMessageOnce; this.m_disabledOnce = o.m_disabledOnce; this.m_errorLocation = o.m_errorLocation; this.m_labelCss = o.m_labelCss; this.m_mandatory = o.m_mandatory; this.m_nextLabel = o.m_nextLabel; this.m_nextLabelControl = o.m_nextLabelControl; this.m_readOnly = o.m_readOnly; this.m_readOnlyOnce = o.m_readOnlyOnce; this.m_testid = o.m_testid; } } /** * This builder is for propertyless items, and hence does not contain type information. */ final public class ItemBuilder extends BuilderData<Void, Void>{ public ItemBuilder() { super(null, null); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public ItemBuilder label(@Nullable String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public ItemBuilder label(@Nullable NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public ItemBuilder unlabeled() { label(""); return this; } @NonNull public ItemBuilder mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public ItemBuilder mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } public void item(@NonNull NodeBase item) throws Exception { addControl(this, item, null); } public void control(@NonNull NodeBase item) throws Exception { addControl(this, item, null); } @NonNull public <T> UntypedControlBuilder<T> property(@NonNull T instance, @GProperty String property) { UntypedControlBuilder<T> currentBuilder = new UntypedControlBuilder<>(instance, MetaManager.getPropertyMeta(instance.getClass(), property)); m_currentBuilder = currentBuilder; // This is now current //-- Copy all fields. currentBuilder.copyFrom(this); return currentBuilder; } } /** * A builder that will end in a control, with full types - used with QFields. * * @param <I> The instance. * @param <V> The value type of the property of the instance. */ final public class TypedControlBuilder<I, V> extends BuilderData<I, V> { public TypedControlBuilder(I instance, PropertyMetaModel<V> propertyMeta) { super(instance, propertyMeta); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public TypedControlBuilder<I, V> label(@NonNull String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public TypedControlBuilder<I, V> label(@NonNull NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public TypedControlBuilder<I, V> unlabeled() { label(""); return this; } @NonNull public TypedControlBuilder<I, V> mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public TypedControlBuilder<I, V> mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } @NonNull public TypedControlBuilder<I, V> errorLocation(@NonNull String errorLocation) { m_errorLocation = errorLocation; return this; } /*--------------------------------------------------------------*/ /* CODING: Readonly, mandatory, disabled. */ /*--------------------------------------------------------------*/ @NonNull public TypedControlBuilder<I, V> readOnly() { m_readOnly = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for readOnly. */ @NonNull public TypedControlBuilder<I, V> readOnly(boolean ro) { m_readOnly = Boolean.valueOf(ro); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> TypedControlBuilder<I, V> readOnly(@NonNull X instance, @NonNull String property) { m_readOnlyOnce = createRef(instance, property, Boolean.class); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> TypedControlBuilder<I, V> readOnly(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_readOnlyOnce = createRef(instance, property); return this; } @NonNull public TypedControlBuilder<I, V> disabled() { m_disabled = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for disabled. */ @NonNull public TypedControlBuilder<I, V> disabled(boolean ro) { m_disabled = Boolean.valueOf(ro); return this; } @NonNull public TypedControlBuilder<I, V> testId(String id) { m_testid = id; return this; } @NonNull public <X> TypedControlBuilder<I, V> disabled(@NonNull X instance, @NonNull String property) { m_disabledOnce = createRef(instance, property, Boolean.class); return this; } @NonNull public <X> TypedControlBuilder<I, V> disabled(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_disabledOnce = createRef(instance, property); return this; } /** * Disables the next component with the specified disable message. */ @NonNull public TypedControlBuilder<I, V> disabledBecause(@Nullable String message) { m_disabledMessage = message; return this; } @NonNull public <X> TypedControlBuilder<I, V> disabledBecause(@NonNull X instance, @NonNull String property) { m_disabledMessageOnce = createRef(instance, property, String.class); return this; } @NonNull public <X> TypedControlBuilder<I, V> disabledBecause(@NonNull X instance, @NonNull QField<X, String> property) { m_disabledMessageOnce = createRef(instance, property); return this; } /** * Adds the specified css class to the control cell. */ @NonNull public TypedControlBuilder<I, V> cssControl(@NonNull String cssClass) { m_controlCss = cssClass; return this; } /** * Adds the specified css class to the label cell. */ @NonNull public TypedControlBuilder<I, V> cssLabel(@NonNull String cssClass) { m_labelCss = cssClass; return this; } /** * Add the specified control. Since the control is manually created this code assumes that the * control is <b>properly configured</b> for it's task! This means that this code will not * make any changes to the control! Specifically: if the form item is marked as "mandatory" * but the control here is not then the control stays optional. * The reverse however is not true: if the control passed in is marked as mandatory then the * form item will be marked as such too. */ public void control(@NonNull IControl<V> control) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, null); resetBuilder(); } public <CV> void control(@NonNull IControl<CV> control, IBidiBindingConverter<CV, V> converter) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, converter); resetBuilder(); } @NonNull public IControl<V> control() throws Exception { return controlMain(this, null); } @NonNull public <C extends IControl<V>> C control(@Nullable Class<C> controlClass) throws Exception { return controlMain(this, controlClass); } } final public class UntypedControlBuilder<I> extends BuilderData<I, Object> { public UntypedControlBuilder(I instance, PropertyMetaModel<?> propertyMeta) { super(instance, (PropertyMetaModel<Object>) propertyMeta); } /*--------------------------------------------------------------*/ /* CODING: Label control. */ /*--------------------------------------------------------------*/ @NonNull public UntypedControlBuilder<I> label(@NonNull String label) { if(null != m_nextLabelControl) throw new IllegalStateException("You already set a Label instance"); m_nextLabel = label; return this; } @NonNull public UntypedControlBuilder<I> label(@NonNull NodeContainer label) { if(null != m_nextLabel) throw new IllegalStateException("You already set a String label instance"); m_nextLabelControl = label; return this; } @NonNull public UntypedControlBuilder<I> unlabeled() { label(""); return this; } @NonNull public UntypedControlBuilder<I> mandatory() { m_mandatory = Boolean.TRUE; return this; } @NonNull public UntypedControlBuilder<I> mandatory(boolean yes) { m_mandatory = Boolean.valueOf(yes); return this; } @NonNull public UntypedControlBuilder<I> errorLocation(@NonNull String errorLocation) { m_errorLocation = errorLocation; return this; } /*--------------------------------------------------------------*/ /* CODING: Readonly, mandatory, disabled. */ /*--------------------------------------------------------------*/ @NonNull public UntypedControlBuilder<I> readOnly() { m_readOnly = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for readOnly. */ @NonNull public UntypedControlBuilder<I> readOnly(boolean ro) { m_readOnly = Boolean.valueOf(ro); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> UntypedControlBuilder<I> readOnly(@NonNull X instance, @NonNull String property) { m_readOnlyOnce = createRef(instance, property, Boolean.class); return this; } /** * Bind only the next component to the specified boolean property. See */ @NonNull public <X> UntypedControlBuilder<I> readOnly(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_readOnlyOnce = createRef(instance, property); return this; } @NonNull public UntypedControlBuilder<I> disabled() { m_disabled = Boolean.TRUE; return this; } /** * Force the next component to have the specified value for disabled. */ @NonNull public UntypedControlBuilder<I> disabled(boolean ro) { m_disabled = Boolean.valueOf(ro); return this; } @NonNull public UntypedControlBuilder<I> testId(String id) { m_testid = id; return this; } @NonNull public <X> UntypedControlBuilder<I> disabled(@NonNull X instance, @NonNull String property) { m_disabledOnce = createRef(instance, property, Boolean.class); return this; } @NonNull public <X> UntypedControlBuilder<I> disabled(@NonNull X instance, @NonNull QField<X, Boolean> property) { m_disabledOnce = createRef(instance, property); return this; } /** * Disables the next component with the specified disable message. */ @NonNull public UntypedControlBuilder<I> disabledBecause(@Nullable String message) { m_disabledMessage = message; return this; } @NonNull public <X> UntypedControlBuilder<I> disabledBecause(@NonNull X instance, @NonNull String property) { m_disabledMessageOnce = createRef(instance, property, String.class); return this; } @NonNull public <X> UntypedControlBuilder<I> disabledBecause(@NonNull X instance, @NonNull QField<X, String> property) { m_disabledMessageOnce = createRef(instance, property); return this; } /** * Adds the specified css class to the control cell. */ @NonNull public UntypedControlBuilder<I> cssControl(@NonNull String cssClass) { m_controlCss = cssClass; return this; } /** * Adds the specified css class to the label cell. */ @NonNull public UntypedControlBuilder<I> cssLabel(@NonNull String cssClass) { m_labelCss = cssClass; return this; } /** * Add the specified control. Since the control is manually created this code assumes that the * control is <b>properly configured</b> for it's task! This means that this code will not * make any changes to the control! Specifically: if the form item is marked as "mandatory" * but the control here is not then the control stays optional. * The reverse however is not true: if the control passed in is marked as mandatory then the * form item will be marked as such too. */ public void control(@NonNull IControl<?> control) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, null); resetBuilder(); } public <CV> void control(@NonNull IControl<?> control, IBidiBindingConverter<?, ?> converter) throws Exception { if(control.isMandatory()) { m_mandatory = Boolean.TRUE; } addControl(this, (NodeBase) control, converter); resetBuilder(); } @NonNull public IControl<?> control() throws Exception { return controlMain(this, null); } @NonNull public <C extends IControl<?>> C control(@Nullable Class<C> controlClass) throws Exception { ControlCreatorRegistry builder = DomApplication.get().getControlCreatorRegistry(); PropertyMetaModel<Object> pmm = m_propertyMetaModel; C control = (C) builder.createControl(pmm, (Class<IControl<Object>>) controlClass); addControl(this, (NodeBase) control, null); resetBuilder(); return control; } } }
[*tweak] Add list-of-tweaks fragment and tweak edit page base.
to.etc.domui/src/main/java/to/etc/domui/component2/form4/FormBuilder.java
[*tweak] Add list-of-tweaks fragment and tweak edit page base.
Java
lgpl-2.1
6382747585ddef8dd70c1c17c59a19d977b10eb2
0
sbliven/biojava,sbliven/biojava,sbliven/biojava
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.utils.lsid; import java.io.Serializable; import java.util.StringTokenizer; /** * Life Science Identifier (LSID). * * LSID syntax: * <p> * &lt;authority&gt;:&lt;namespace&gt;:&lt;objectId&gt;:&lt;version&gt;:&lt;security&gt; * <p> * The elements of a LSID are as follows: * <ul> * <li>authority = &lt;authority&gt; identifies the organization * <li>namespace = &lt;namespace&gt; namespace to scope the identifier value * <li>object_id = &lt;objectId&gt; identifier of the object within namespace * <li>version = &lt;version&gt; version information * <li>security = &lt;security&gt; optional security information * </ul> * * @author Michael Heuer */ public final class LifeScienceIdentifier implements Serializable { private final String authority; private final String namespace; private final String objectId; private final int version; private final String security; /** * Create a new LifeScienceIdentifier. * * @param authority identifies the organization * @param namespace namespace to scope the identifier value * @param objectId identifer of the object within namespace * @param version version information * @param security optional security information * * @throws IllegalArgumentException if any of <code>authority</code>, * <code>namespace</code>, or <code>objectId</code> are null */ private LifeScienceIdentifier(String authority, String namespace, String objectId, int version, String security) { if (authority == null) throw new IllegalArgumentException("authority must not be null"); if (namespace == null) throw new IllegalArgumentException("namespace must not be null"); if (objectId == null) throw new IllegalArgumentException("objectId must not be null"); this.authority = authority; this.namespace = namespace; this.objectId = objectId; this.version = version; this.security = security; } /** * Return the authority for this identifier. */ public String getAuthority() { return authority; } /** * Return the namespace for this identifier * within the authority. */ public String getNamespace() { return namespace; } /** * Return the object id of this identifier. */ public String getObjectId() { return objectId; } /** * Return the version of the object id of * this identifier. */ public int getVersion() { return version; } /** * Return the security information of this identifier. * May return null. */ public String getSecurity() { return security; } public boolean equals(Object value) { if (this == value) return true; if (!(value instanceof LifeScienceIdentifier)) return false; LifeScienceIdentifier lsid = (LifeScienceIdentifier) value; return (authority.equals(lsid.getAuthority()) && namespace.equals(lsid.getNamespace()) && objectId.equals(lsid.getObjectId()) && version == lsid.getVersion() && (security == null ? lsid.getSecurity() == null : security.equals(lsid.getSecurity()))); } public int hashCode() { return (this.toString().hashCode()); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getAuthority()); sb.append(":"); sb.append(getNamespace()); sb.append(":"); sb.append(getObjectId()); sb.append(":"); sb.append(getVersion()); if (getSecurity() != null) { sb.append(":"); sb.append(getSecurity()); } return (sb.toString()); } /** * Create a new LifeScienceIdentifier parsed * from the properly formatted string <code>lsid</code>. * * @param lsid formatted LifeScienceIdentifier string * * @throws LifeScienceIdentifierParseException if <code>lsid</code> * is not properly formatted */ public static LifeScienceIdentifier valueOf(String lsid) { try { StringTokenizer st = new StringTokenizer(lsid, ":"); if (st.countTokens() >= 4) { String authority = st.nextToken(); String namespace = st.nextToken(); String objectId = st.nextToken(); int version = Integer.parseInt(st.nextToken()); String security = null; if (st.hasMoreTokens()) { security = st.nextToken(); } return valueOf(authority, namespace, objectId, version, security); } else { throw new LifeScienceIdentifierParseException("couldn't parse: " + lsid); } } catch (NumberFormatException nfe) { throw new LifeScienceIdentifierParseException("couldn't parse: " + lsid + " " + nfe); } } /** * Create a new LifeScienceIdentifier from the * specified parameters. * * @param authority identifies the organization * @param namespace namespace to scope the identifier value * @param objectId identifer of the object within namespace * @param version version information * @param security optional security information * * @throws IllegalArgumentException if any of <code>authority</code>, * <code>namespace</code>, or <code>objectId</code> are null */ public static LifeScienceIdentifier valueOf(String authority, String namespace, String objectId, int version, String security) { return new LifeScienceIdentifier(authority, namespace, objectId, version, security); } private static final long serialVersionUID = 1836992936659290633L; }
src-1.4/org/biojava/utils/lsid/LifeScienceIdentifier.java
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.utils.lsid; import java.io.Serializable; import java.util.StringTokenizer; /** * Life Science Identifier (LSID). * * LSID syntax: * <p> * &lt;authority&gt;:&lt;namespace&gt;:&lt;objectId&gt;:&lt;version&gt;:&lt;security&gt; * <p> * The elements of a LSID are as follows: * <ul> * <li>authority = &lt;authority&gt; identifies the organization * <li>namespace = &lt;namespace&gt; namespace to scope the identifier value * <li>object_id = &lt;objectId&gt; identifier of the object within namespace * <li>version = &lt;version&gt; version information * <li>security = &lt;security&gt; optional security information * </ul> * * @author Michael Heuer */ public final class LifeScienceIdentifier implements Serializable { private final String authority; private final String namespace; private final String objectId; private final int version; private final String security; /** * Create a new LifeScienceIdentifier. * * @param authority identifies the organization * @param namespace namespace to scope the identifier value * @param objectId identifer of the object within namespace * @param version version information * @param security optional security information * * @throws IllegalArgumentException if any of <code>authority</code>, * <code>namespace</code>, or <code>objectId</code> are null */ private LifeScienceIdentifier(String authority, String namespace, String objectId, int version, String security) { if (authority == null) throw new IllegalArgumentException("authority must not be null"); if (namespace == null) throw new IllegalArgumentException("namespace must not be null"); if (objectId == null) throw new IllegalArgumentException("objectId must not be null"); this.authority = authority; this.namespace = namespace; this.objectId = objectId; this.version = version; this.security = security; } /** * Return the authority for this identifier. */ public String getAuthority() { return authority; } /** * Return the namespace for this identifier * within the authority. */ public String getNamespace() { return namespace; } /** * Return the object id of this identifier. */ public String getObjectId() { return objectId; } /** * Return the version of the object id of * this identifier. */ public int getVersion() { return version; } /** * Return the security information of this identifier. * May return null. */ public String getSecurity() { return security; } public boolean equals(Object value) { if (this == value) return true; if (!(value instanceof LifeScienceIdentifier)) return false; LifeScienceIdentifier lsid = (LifeScienceIdentifier) value; return (authority.equals(lsid.getAuthority()) && namespace.equals(lsid.getNamespace()) && objectId.equals(lsid.getObjectId()) && version == lsid.getVersion() && (security == null ? lsid.getSecurity() == null : security.equals(lsid.getSecurity()))); } public int hashCode() { return (this.toString().hashCode()); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getAuthority()); sb.append(":"); sb.append(getNamespace()); sb.append(":"); sb.append(getObjectId()); sb.append(":"); sb.append(getVersion()); if (getSecurity() != null) { sb.append(":"); sb.append(getSecurity()); } return (sb.toString()); } /** * Create a new LifeScienceIdentifier parsed * from the properly formatted string <code>lsid</code>. * * @param lsid formatted LifeScienceIdentifier string * * @throws LifeScienceIdentifierParseException if <code>lsid</code> * is not properly formatted */ public static LifeScienceIdentifier valueOf(String lsid) { try { StringTokenizer st = new StringTokenizer(lsid, ":"); if (st.countTokens() >= 4) { String authority = st.nextToken(); String namespace = st.nextToken(); String objectId = st.nextToken(); int version = Integer.parseInt(st.nextToken()); String security = null; if (st.hasMoreTokens()) { security = st.nextToken(); } return valueOf(authority, namespace, objectId, version, security); } else { throw new LifeScienceIdentifierParseException("couldn't parse: " + lsid); } } catch (NumberFormatException nfe) { throw new LifeScienceIdentifierParseException("couldn't parse: " + lsid + " " + nfe); } } /** * Create a new LifeScienceIdentifier from the * specified parameters. * * @param authority identifies the organization * @param namespace namespace to scope the identifier value * @param objectId identifer of the object within namespace * @param version version information * @param security optional security information * * @throws IllegalArgumentException if any of <code>authority</code>, * <code>namespace</code>, or <code>objectId</code> are null */ public static LifeScienceIdentifier valueOf(String authority, String namespace, String objectId, int version, String security) { return new LifeScienceIdentifier(authority, namespace, objectId, version, security); } //private static final long serialVersionUID = (long) 1; }
added a reasonable serialVersionUID git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@2106 7c6358e6-4a41-0410-a743-a5b2a554c398
src-1.4/org/biojava/utils/lsid/LifeScienceIdentifier.java
added a reasonable serialVersionUID
Java
lgpl-2.1
fc9bcf637abca3ed5adef7510bf29d2cb6dc7d35
0
i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,i2geo/i2gCurrikiFork,xwiki-contrib/currikiorg,xwiki-contrib/currikiorg
package org.curriki.xwiki.servlet.restlet.resource.assets; import org.restlet.resource.Representation; import org.restlet.resource.Variant; import org.restlet.resource.ResourceException; import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.curriki.xwiki.plugin.asset.Asset; import org.curriki.xwiki.servlet.restlet.resource.BaseResource; import net.sf.json.JSONObject; import com.xpn.xwiki.api.Property; import com.xpn.xwiki.XWikiException; import java.util.List; import java.util.Date; import java.util.ArrayList; /** */ public class AssetManagerResource extends BaseResource { public AssetManagerResource(Context context, Request request, Response response) { super(context, request, response); setReadable(true); setModifiable(true); defaultVariants(); } @Override public Representation represent(Variant variant) throws ResourceException { return null; } @Override public void storeRepresentation(Representation representation) throws ResourceException { setupXWiki(); JSONObject json = representationToJSONObject(representation); /** * this json parameter indicate the action to execute */ String action = json.getString("action"); if (action!=null) { if (action.equalsIgnoreCase("setAsterixReview")) { setAsterixReview(json.getString("asterixReviewValue")); } else if (action.equalsIgnoreCase("removeAsterixReview")) { removeAsterixReview(); } } } /** * remove the asterix review of a resource * @throws ResourceException */ private void removeAsterixReview() throws ResourceException { Request request = getRequest(); String assetName = (String) request.getAttributes().get("assetName"); Asset asset; try { asset = plugin.fetchAsset(assetName); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } asset.use("CRS.CurrikiReviewStatusClass"); String asterixReviewValue = (String) asset.getValue("status"); asset.set("status", "100"); try { List<String> crsvalue = new ArrayList<String>(1); crsvalue.add(xwikiContext.getMessageTool().get("curriki.crs.review.setas"+asterixReviewValue)); asset.save(xwikiContext.getMessageTool().get("curriki.comment.crsvalueremoved", crsvalue)); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } String newPage = getRequest().getRootRef().toString(); if (!newPage.endsWith("/")) { newPage += "/"; } newPage += "assets/"+asset.getFullName(); getResponse().redirectSeeOther(newPage); } /** * set the asterix review of a resource * @param asterixReviewValue = new asterix review value * @throws ResourceException */ private void setAsterixReview(String asterixReviewValue) throws ResourceException { Request request = getRequest(); String assetName = (String) request.getAttributes().get("assetName"); Asset asset; try { asset = plugin.fetchAsset(assetName); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } try { com.xpn.xwiki.api.Object obj = asset.getObject("CRS.CurrikiReviewStatusClass"); if (obj==null) { obj = asset.newObject("CRS.CurrikiReviewStatusClass"); obj.set("name",asset.getFullName()); obj.set("number",0); obj.set("reviewpending", 0); obj.set("status", "100"); asset.save(); } } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } asset.use("CRS.CurrikiReviewStatusClass"); asset.set("status", asterixReviewValue); asset.set("reviewpending", 0); asset.set("lastreview_user", xwikiContext.getUser()); asset.set("lastreview_date", xwikiContext.getWiki().formatDate(new Date(), "MM/dd/yyyy HH:mm:ss", xwikiContext)); try { List<String> crsvalue = new ArrayList<String>(1); crsvalue.add(xwikiContext.getMessageTool().get("curriki.crs.review.setas"+asterixReviewValue)); asset.save(xwikiContext.getMessageTool().get("curriki.comment.crsvalueadded", crsvalue)); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } String newPage = getRequest().getRootRef().toString(); if (!newPage.endsWith("/")) { newPage += "/"; } newPage += "assets/"+asset.getFullName(); getResponse().redirectSeeOther(newPage); } }
plugins/servlet/src/main/java/org/curriki/xwiki/servlet/restlet/resource/assets/AssetManagerResource.java
package org.curriki.xwiki.servlet.restlet.resource.assets; import org.restlet.resource.Representation; import org.restlet.resource.Variant; import org.restlet.resource.ResourceException; import org.restlet.Context; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.data.Status; import org.curriki.xwiki.plugin.asset.Asset; import org.curriki.xwiki.servlet.restlet.resource.BaseResource; import net.sf.json.JSONObject; import com.xpn.xwiki.api.Property; import com.xpn.xwiki.XWikiException; import java.util.List; import java.util.Date; import java.util.ArrayList; /** */ public class AssetManagerResource extends BaseResource { public AssetManagerResource(Context context, Request request, Response response) { super(context, request, response); setReadable(true); setModifiable(true); defaultVariants(); } @Override public Representation represent(Variant variant) throws ResourceException { return null; } @Override public void storeRepresentation(Representation representation) throws ResourceException { setupXWiki(); JSONObject json = representationToJSONObject(representation); /** * this json parameter indicate the action to execute */ String action = json.getString("action"); if (action!=null) { if (action.equalsIgnoreCase("setAsterixReview")) { setAsterixReview(json.getString("asterixReviewValue")); } else if (action.equalsIgnoreCase("removeAsterixReview")) { removeAsterixReview(); } } } /** * remove the asterix review of a resource * @throws ResourceException */ private void removeAsterixReview() throws ResourceException { Request request = getRequest(); String assetName = (String) request.getAttributes().get("assetName"); Asset asset; try { asset = plugin.fetchAsset(assetName); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } asset.use("CRS.CurrikiReviewStatusClass"); String asterixReviewValue = (String) asset.getValue("status"); asset.set("status", "100"); try { List<String> crsvalue = new ArrayList<String>(1); crsvalue.add(xwikiContext.getMessageTool().get("curriki.crs.review.setas"+asterixReviewValue)); asset.save(xwikiContext.getMessageTool().get("curriki.coment.crsvalueremoved", crsvalue)); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } String newPage = getRequest().getRootRef().toString(); if (!newPage.endsWith("/")) { newPage += "/"; } newPage += "assets/"+asset.getFullName(); getResponse().redirectSeeOther(newPage); } /** * set the asterix review of a resource * @param asterixReviewValue = new asterix review value * @throws ResourceException */ private void setAsterixReview(String asterixReviewValue) throws ResourceException { Request request = getRequest(); String assetName = (String) request.getAttributes().get("assetName"); Asset asset; try { asset = plugin.fetchAsset(assetName); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } try { com.xpn.xwiki.api.Object obj = asset.getObject("CRS.CurrikiReviewStatusClass"); if (obj==null) { obj = asset.newObject("CRS.CurrikiReviewStatusClass"); obj.set("name",asset.getFullName()); obj.set("number",0); obj.set("reviewpending", 0); obj.set("status", "100"); asset.save(); } } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } asset.use("CRS.CurrikiReviewStatusClass"); asset.set("status", asterixReviewValue); asset.set("reviewpending", 0); asset.set("lastreview_user", xwikiContext.getUser()); asset.set("lastreview_date", xwikiContext.getWiki().formatDate(new Date(), "MM/dd/yyyy HH:mm:ss", xwikiContext)); try { List<String> crsvalue = new ArrayList<String>(1); crsvalue.add(xwikiContext.getMessageTool().get("curriki.crs.review.setas"+asterixReviewValue)); asset.save(xwikiContext.getMessageTool().get("curriki.coment.crsvalueadded", crsvalue)); } catch (XWikiException e) { throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); } String newPage = getRequest().getRootRef().toString(); if (!newPage.endsWith("/")) { newPage += "/"; } newPage += "assets/"+asset.getFullName(); getResponse().redirectSeeOther(newPage); } }
- CURRIKI-3135 - Fix spelling of translation string svn@13975
plugins/servlet/src/main/java/org/curriki/xwiki/servlet/restlet/resource/assets/AssetManagerResource.java
- CURRIKI-3135 - Fix spelling of translation string